phaser.js 2.9 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601826028260382604826058260682607826088260982610826118261282613826148261582616826178261882619826208262182622826238262482625826268262782628826298263082631826328263382634826358263682637826388263982640826418264282643826448264582646826478264882649826508265182652826538265482655826568265782658826598266082661826628266382664826658266682667826688266982670826718267282673826748267582676826778267882679826808268182682826838268482685826868268782688826898269082691826928269382694826958269682697826988269982700827018270282703827048270582706827078270882709827108271182712827138271482715827168271782718827198272082721827228272382724827258272682727827288272982730827318273282733827348273582736827378273882739827408274182742827438274482745827468274782748827498275082751827528275382754827558275682757827588275982760827618276282763827648276582766827678276882769827708277182772827738277482775827768277782778827798278082781827828278382784827858278682787827888278982790827918279282793827948279582796827978279882799828008280182802828038280482805828068280782808828098281082811828128281382814828158281682817828188281982820828218282282823828248282582826828278282882829828308283182832828338283482835828368283782838828398284082841828428284382844828458284682847828488284982850828518285282853828548285582856828578285882859828608286182862828638286482865828668286782868828698287082871828728287382874828758287682877828788287982880828818288282883828848288582886828878288882889828908289182892828938289482895828968289782898828998290082901829028290382904829058290682907829088290982910829118291282913829148291582916829178291882919829208292182922829238292482925829268292782928829298293082931829328293382934829358293682937829388293982940829418294282943829448294582946829478294882949829508295182952829538295482955829568295782958829598296082961829628296382964829658296682967829688296982970829718297282973829748297582976829778297882979829808298182982829838298482985829868298782988829898299082991829928299382994829958299682997829988299983000830018300283003830048300583006830078300883009830108301183012830138301483015830168301783018830198302083021830228302383024830258302683027830288302983030830318303283033830348303583036830378303883039830408304183042830438304483045830468304783048830498305083051830528305383054830558305683057830588305983060830618306283063830648306583066830678306883069830708307183072830738307483075830768307783078830798308083081830828308383084830858308683087830888308983090830918309283093830948309583096830978309883099831008310183102831038310483105831068310783108831098311083111831128311383114831158311683117831188311983120831218312283123831248312583126831278312883129831308313183132831338313483135831368313783138831398314083141831428314383144831458314683147831488314983150831518315283153831548315583156831578315883159831608316183162831638316483165831668316783168831698317083171831728317383174831758317683177831788317983180831818318283183831848318583186831878318883189831908319183192831938319483195831968319783198831998320083201832028320383204832058320683207832088320983210832118321283213832148321583216832178321883219832208322183222832238322483225832268322783228832298323083231832328323383234832358323683237832388323983240832418324283243832448324583246832478324883249832508325183252832538325483255832568325783258832598326083261832628326383264832658326683267832688326983270832718327283273832748327583276832778327883279832808328183282832838328483285832868328783288832898329083291832928329383294832958329683297832988329983300833018330283303833048330583306833078330883309833108331183312833138331483315833168331783318833198332083321833228332383324833258332683327833288332983330833318333283333833348333583336833378333883339833408334183342833438334483345833468334783348833498335083351833528335383354833558335683357833588335983360833618336283363833648336583366833678336883369833708337183372833738337483375833768337783378833798338083381833828338383384833858338683387833888338983390833918339283393833948339583396833978339883399834008340183402834038340483405834068340783408834098341083411834128341383414834158341683417834188341983420834218342283423834248342583426834278342883429834308343183432834338343483435834368343783438834398344083441834428344383444834458344683447834488344983450834518345283453834548345583456834578345883459834608346183462834638346483465834668346783468834698347083471834728347383474834758347683477834788347983480834818348283483834848348583486834878348883489834908349183492834938349483495834968349783498834998350083501835028350383504835058350683507835088350983510835118351283513835148351583516835178351883519835208352183522835238352483525835268352783528835298353083531835328353383534835358353683537835388353983540835418354283543835448354583546835478354883549835508355183552835538355483555835568355783558835598356083561835628356383564835658356683567835688356983570835718357283573835748357583576835778357883579835808358183582835838358483585835868358783588835898359083591835928359383594835958359683597835988359983600836018360283603836048360583606836078360883609836108361183612836138361483615836168361783618836198362083621836228362383624836258362683627836288362983630836318363283633836348363583636836378363883639836408364183642836438364483645836468364783648836498365083651836528365383654836558365683657836588365983660836618366283663836648366583666836678366883669836708367183672836738367483675836768367783678836798368083681836828368383684836858368683687836888368983690836918369283693836948369583696836978369883699837008370183702837038370483705837068370783708837098371083711837128371383714837158371683717837188371983720837218372283723837248372583726837278372883729837308373183732837338373483735837368373783738837398374083741837428374383744837458374683747837488374983750837518375283753837548375583756837578375883759837608376183762837638376483765837668376783768837698377083771837728377383774837758377683777837788377983780837818378283783837848378583786837878378883789837908379183792837938379483795837968379783798837998380083801838028380383804838058380683807838088380983810838118381283813838148381583816838178381883819838208382183822838238382483825838268382783828838298383083831838328383383834838358383683837838388383983840838418384283843838448384583846838478384883849838508385183852838538385483855838568385783858838598386083861838628386383864838658386683867838688386983870838718387283873838748387583876838778387883879838808388183882838838388483885838868388783888838898389083891838928389383894838958389683897838988389983900839018390283903839048390583906839078390883909839108391183912839138391483915839168391783918839198392083921839228392383924839258392683927839288392983930839318393283933839348393583936839378393883939839408394183942839438394483945839468394783948839498395083951839528395383954839558395683957839588395983960839618396283963839648396583966839678396883969839708397183972839738397483975839768397783978839798398083981839828398383984839858398683987839888398983990839918399283993839948399583996839978399883999840008400184002840038400484005840068400784008840098401084011840128401384014840158401684017840188401984020840218402284023840248402584026840278402884029840308403184032840338403484035840368403784038840398404084041840428404384044840458404684047840488404984050840518405284053840548405584056840578405884059840608406184062840638406484065840668406784068840698407084071840728407384074840758407684077840788407984080840818408284083840848408584086840878408884089840908409184092840938409484095840968409784098840998410084101841028410384104841058410684107841088410984110841118411284113841148411584116841178411884119841208412184122841238412484125841268412784128841298413084131841328413384134841358413684137841388413984140841418414284143841448414584146841478414884149841508415184152841538415484155841568415784158841598416084161841628416384164841658416684167841688416984170841718417284173841748417584176841778417884179841808418184182841838418484185841868418784188841898419084191841928419384194841958419684197841988419984200842018420284203842048420584206842078420884209842108421184212842138421484215842168421784218842198422084221842228422384224842258422684227842288422984230842318423284233842348423584236842378423884239842408424184242842438424484245842468424784248842498425084251842528425384254842558425684257842588425984260842618426284263842648426584266842678426884269842708427184272842738427484275842768427784278842798428084281842828428384284842858428684287842888428984290842918429284293842948429584296842978429884299843008430184302843038430484305843068430784308843098431084311843128431384314843158431684317843188431984320843218432284323843248432584326843278432884329843308433184332843338433484335843368433784338843398434084341843428434384344843458434684347843488434984350843518435284353843548435584356843578435884359843608436184362843638436484365843668436784368843698437084371843728437384374843758437684377843788437984380843818438284383843848438584386843878438884389843908439184392843938439484395843968439784398843998440084401844028440384404844058440684407844088440984410844118441284413844148441584416844178441884419844208442184422844238442484425844268442784428844298443084431844328443384434844358443684437844388443984440844418444284443844448444584446844478444884449844508445184452844538445484455844568445784458844598446084461844628446384464844658446684467844688446984470844718447284473844748447584476844778447884479844808448184482844838448484485844868448784488844898449084491844928449384494844958449684497844988449984500845018450284503845048450584506845078450884509845108451184512845138451484515845168451784518845198452084521845228452384524845258452684527845288452984530845318453284533845348453584536845378453884539845408454184542845438454484545845468454784548845498455084551845528455384554845558455684557845588455984560845618456284563845648456584566845678456884569845708457184572845738457484575845768457784578845798458084581845828458384584845858458684587845888458984590845918459284593845948459584596845978459884599846008460184602846038460484605846068460784608846098461084611846128461384614846158461684617846188461984620846218462284623846248462584626846278462884629846308463184632846338463484635846368463784638846398464084641846428464384644846458464684647846488464984650846518465284653846548465584656846578465884659846608466184662846638466484665846668466784668846698467084671846728467384674846758467684677846788467984680846818468284683846848468584686846878468884689846908469184692846938469484695846968469784698846998470084701847028470384704847058470684707847088470984710847118471284713847148471584716847178471884719847208472184722847238472484725847268472784728847298473084731847328473384734847358473684737847388473984740847418474284743847448474584746847478474884749847508475184752847538475484755847568475784758847598476084761847628476384764847658476684767847688476984770847718477284773847748477584776847778477884779847808478184782847838478484785847868478784788847898479084791847928479384794847958479684797847988479984800848018480284803848048480584806848078480884809848108481184812848138481484815848168481784818848198482084821848228482384824848258482684827848288482984830848318483284833848348483584836848378483884839848408484184842848438484484845848468484784848848498485084851848528485384854848558485684857848588485984860848618486284863848648486584866848678486884869848708487184872848738487484875848768487784878848798488084881848828488384884848858488684887848888488984890848918489284893848948489584896848978489884899849008490184902849038490484905849068490784908849098491084911849128491384914849158491684917849188491984920849218492284923849248492584926849278492884929849308493184932849338493484935849368493784938849398494084941849428494384944849458494684947849488494984950849518495284953849548495584956849578495884959849608496184962849638496484965849668496784968849698497084971849728497384974849758497684977849788497984980849818498284983849848498584986849878498884989849908499184992849938499484995849968499784998849998500085001850028500385004850058500685007850088500985010850118501285013850148501585016850178501885019850208502185022850238502485025850268502785028850298503085031850328503385034850358503685037850388503985040850418504285043850448504585046850478504885049850508505185052850538505485055850568505785058850598506085061850628506385064850658506685067850688506985070850718507285073850748507585076850778507885079850808508185082850838508485085850868508785088850898509085091850928509385094850958509685097850988509985100851018510285103851048510585106851078510885109851108511185112851138511485115851168511785118851198512085121851228512385124851258512685127851288512985130851318513285133851348513585136851378513885139851408514185142851438514485145851468514785148851498515085151851528515385154851558515685157851588515985160851618516285163851648516585166851678516885169851708517185172851738517485175851768517785178851798518085181851828518385184851858518685187851888518985190851918519285193851948519585196851978519885199852008520185202852038520485205852068520785208852098521085211852128521385214852158521685217852188521985220852218522285223852248522585226852278522885229852308523185232852338523485235852368523785238852398524085241852428524385244852458524685247852488524985250852518525285253852548525585256852578525885259852608526185262852638526485265852668526785268852698527085271852728527385274852758527685277852788527985280852818528285283852848528585286852878528885289852908529185292852938529485295852968529785298852998530085301853028530385304853058530685307853088530985310853118531285313853148531585316853178531885319853208532185322853238532485325853268532785328853298533085331853328533385334853358533685337853388533985340853418534285343853448534585346853478534885349853508535185352853538535485355853568535785358853598536085361853628536385364853658536685367853688536985370853718537285373853748537585376853778537885379853808538185382853838538485385853868538785388853898539085391853928539385394853958539685397853988539985400854018540285403854048540585406854078540885409854108541185412854138541485415854168541785418854198542085421854228542385424854258542685427854288542985430854318543285433854348543585436854378543885439854408544185442854438544485445854468544785448854498545085451854528545385454854558545685457854588545985460854618546285463854648546585466854678546885469854708547185472854738547485475854768547785478854798548085481854828548385484854858548685487854888548985490854918549285493854948549585496854978549885499855008550185502855038550485505855068550785508855098551085511855128551385514855158551685517855188551985520855218552285523855248552585526855278552885529855308553185532855338553485535855368553785538855398554085541855428554385544855458554685547855488554985550855518555285553855548555585556855578555885559855608556185562855638556485565855668556785568855698557085571855728557385574855758557685577855788557985580855818558285583855848558585586855878558885589855908559185592855938559485595855968559785598855998560085601856028560385604856058560685607856088560985610856118561285613856148561585616856178561885619856208562185622856238562485625856268562785628856298563085631856328563385634856358563685637856388563985640856418564285643856448564585646856478564885649856508565185652856538565485655856568565785658856598566085661856628566385664856658566685667856688566985670856718567285673856748567585676856778567885679856808568185682856838568485685856868568785688856898569085691856928569385694856958569685697856988569985700857018570285703857048570585706857078570885709857108571185712857138571485715857168571785718857198572085721857228572385724857258572685727857288572985730857318573285733857348573585736857378573885739857408574185742857438574485745857468574785748857498575085751857528575385754857558575685757857588575985760857618576285763857648576585766857678576885769857708577185772857738577485775857768577785778857798578085781857828578385784857858578685787857888578985790857918579285793857948579585796857978579885799858008580185802858038580485805858068580785808858098581085811858128581385814858158581685817858188581985820858218582285823858248582585826858278582885829858308583185832858338583485835858368583785838858398584085841858428584385844858458584685847858488584985850858518585285853858548585585856858578585885859858608586185862858638586485865858668586785868858698587085871858728587385874858758587685877858788587985880858818588285883858848588585886858878588885889858908589185892858938589485895858968589785898858998590085901859028590385904859058590685907859088590985910859118591285913859148591585916859178591885919859208592185922859238592485925859268592785928859298593085931859328593385934859358593685937859388593985940859418594285943859448594585946859478594885949859508595185952859538595485955859568595785958859598596085961859628596385964859658596685967859688596985970859718597285973859748597585976859778597885979859808598185982859838598485985859868598785988859898599085991859928599385994859958599685997859988599986000860018600286003860048600586006860078600886009860108601186012860138601486015860168601786018860198602086021860228602386024860258602686027860288602986030860318603286033860348603586036860378603886039860408604186042860438604486045860468604786048860498605086051860528605386054860558605686057860588605986060860618606286063860648606586066860678606886069860708607186072860738607486075860768607786078860798608086081860828608386084860858608686087860888608986090860918609286093860948609586096860978609886099861008610186102861038610486105861068610786108861098611086111861128611386114861158611686117861188611986120861218612286123861248612586126861278612886129861308613186132861338613486135861368613786138861398614086141861428614386144861458614686147861488614986150861518615286153861548615586156861578615886159861608616186162861638616486165861668616786168861698617086171861728617386174861758617686177861788617986180861818618286183861848618586186861878618886189861908619186192861938619486195861968619786198861998620086201862028620386204862058620686207862088620986210862118621286213862148621586216862178621886219862208622186222862238622486225862268622786228862298623086231862328623386234862358623686237862388623986240862418624286243862448624586246862478624886249862508625186252862538625486255862568625786258862598626086261862628626386264862658626686267862688626986270862718627286273862748627586276862778627886279862808628186282862838628486285862868628786288862898629086291862928629386294862958629686297862988629986300863018630286303863048630586306863078630886309863108631186312863138631486315863168631786318863198632086321863228632386324863258632686327863288632986330863318633286333863348633586336863378633886339863408634186342863438634486345863468634786348863498635086351863528635386354863558635686357863588635986360863618636286363863648636586366863678636886369863708637186372863738637486375863768637786378863798638086381863828638386384863858638686387863888638986390863918639286393863948639586396863978639886399864008640186402864038640486405864068640786408864098641086411864128641386414864158641686417864188641986420864218642286423864248642586426864278642886429864308643186432864338643486435864368643786438864398644086441864428644386444864458644686447864488644986450864518645286453864548645586456864578645886459864608646186462864638646486465864668646786468864698647086471864728647386474864758647686477864788647986480864818648286483864848648586486864878648886489864908649186492864938649486495864968649786498864998650086501865028650386504865058650686507865088650986510865118651286513865148651586516865178651886519865208652186522865238652486525865268652786528865298653086531865328653386534865358653686537865388653986540865418654286543865448654586546865478654886549865508655186552865538655486555865568655786558865598656086561865628656386564865658656686567865688656986570865718657286573865748657586576865778657886579865808658186582865838658486585865868658786588865898659086591865928659386594865958659686597865988659986600866018660286603866048660586606866078660886609866108661186612866138661486615866168661786618866198662086621866228662386624866258662686627866288662986630866318663286633866348663586636866378663886639866408664186642866438664486645866468664786648866498665086651866528665386654866558665686657866588665986660866618666286663866648666586666866678666886669866708667186672866738667486675866768667786678866798668086681866828668386684866858668686687866888668986690866918669286693866948669586696866978669886699867008670186702867038670486705867068670786708867098671086711867128671386714867158671686717867188671986720867218672286723867248672586726867278672886729867308673186732867338673486735867368673786738867398674086741867428674386744867458674686747867488674986750867518675286753867548675586756867578675886759867608676186762867638676486765867668676786768867698677086771867728677386774867758677686777867788677986780867818678286783867848678586786867878678886789867908679186792867938679486795867968679786798867998680086801868028680386804868058680686807868088680986810868118681286813868148681586816868178681886819868208682186822868238682486825868268682786828868298683086831868328683386834868358683686837868388683986840868418684286843868448684586846868478684886849868508685186852868538685486855868568685786858868598686086861868628686386864868658686686867868688686986870868718687286873868748687586876868778687886879868808688186882868838688486885868868688786888868898689086891868928689386894868958689686897868988689986900869018690286903869048690586906869078690886909869108691186912869138691486915869168691786918869198692086921869228692386924869258692686927869288692986930869318693286933869348693586936869378693886939869408694186942869438694486945869468694786948869498695086951869528695386954869558695686957869588695986960869618696286963869648696586966869678696886969869708697186972869738697486975869768697786978869798698086981869828698386984869858698686987869888698986990869918699286993869948699586996869978699886999870008700187002870038700487005870068700787008870098701087011870128701387014870158701687017870188701987020870218702287023870248702587026870278702887029870308703187032870338703487035870368703787038870398704087041870428704387044870458704687047870488704987050870518705287053870548705587056870578705887059870608706187062870638706487065870668706787068870698707087071870728707387074870758707687077870788707987080870818708287083870848708587086870878708887089870908709187092870938709487095870968709787098870998710087101871028710387104871058710687107871088710987110871118711287113871148711587116871178711887119871208712187122871238712487125871268712787128871298713087131871328713387134871358713687137871388713987140871418714287143871448714587146871478714887149871508715187152871538715487155871568715787158871598716087161871628716387164871658716687167871688716987170871718717287173871748717587176871778717887179871808718187182871838718487185871868718787188871898719087191871928719387194871958719687197871988719987200872018720287203872048720587206872078720887209872108721187212872138721487215872168721787218872198722087221872228722387224872258722687227872288722987230872318723287233872348723587236872378723887239872408724187242872438724487245872468724787248872498725087251872528725387254872558725687257872588725987260872618726287263872648726587266872678726887269872708727187272872738727487275872768727787278872798728087281872828728387284872858728687287872888728987290872918729287293872948729587296872978729887299873008730187302873038730487305873068730787308873098731087311873128731387314873158731687317873188731987320873218732287323873248732587326873278732887329873308733187332873338733487335873368733787338873398734087341873428734387344873458734687347873488734987350873518735287353873548735587356873578735887359873608736187362873638736487365873668736787368873698737087371873728737387374873758737687377873788737987380873818738287383873848738587386873878738887389873908739187392873938739487395873968739787398873998740087401874028740387404874058740687407874088740987410874118741287413874148741587416874178741887419874208742187422874238742487425874268742787428874298743087431874328743387434874358743687437874388743987440874418744287443874448744587446874478744887449874508745187452874538745487455874568745787458874598746087461874628746387464874658746687467874688746987470874718747287473874748747587476874778747887479874808748187482874838748487485874868748787488874898749087491874928749387494874958749687497874988749987500875018750287503875048750587506875078750887509875108751187512875138751487515875168751787518875198752087521875228752387524875258752687527875288752987530875318753287533875348753587536875378753887539875408754187542875438754487545875468754787548875498755087551875528755387554875558755687557875588755987560875618756287563875648756587566875678756887569875708757187572875738757487575875768757787578875798758087581875828758387584875858758687587875888758987590875918759287593875948759587596875978759887599876008760187602876038760487605876068760787608876098761087611876128761387614876158761687617876188761987620876218762287623876248762587626876278762887629876308763187632876338763487635876368763787638876398764087641876428764387644876458764687647876488764987650876518765287653876548765587656876578765887659876608766187662876638766487665876668766787668876698767087671876728767387674876758767687677876788767987680876818768287683876848768587686876878768887689876908769187692876938769487695876968769787698876998770087701877028770387704877058770687707877088770987710877118771287713877148771587716877178771887719877208772187722877238772487725877268772787728877298773087731877328773387734877358773687737877388773987740877418774287743877448774587746877478774887749877508775187752877538775487755877568775787758877598776087761877628776387764877658776687767877688776987770877718777287773877748777587776877778777887779877808778187782877838778487785877868778787788877898779087791877928779387794877958779687797877988779987800878018780287803878048780587806878078780887809878108781187812878138781487815878168781787818878198782087821878228782387824878258782687827878288782987830878318783287833878348783587836878378783887839878408784187842878438784487845878468784787848878498785087851878528785387854878558785687857878588785987860878618786287863878648786587866878678786887869878708787187872878738787487875878768787787878878798788087881878828788387884878858788687887878888788987890878918789287893878948789587896878978789887899879008790187902879038790487905879068790787908879098791087911879128791387914879158791687917879188791987920879218792287923879248792587926879278792887929879308793187932879338793487935879368793787938879398794087941879428794387944879458794687947879488794987950879518795287953879548795587956879578795887959879608796187962879638796487965879668796787968879698797087971879728797387974879758797687977879788797987980879818798287983879848798587986879878798887989879908799187992879938799487995879968799787998879998800088001880028800388004880058800688007880088800988010880118801288013880148801588016880178801888019880208802188022880238802488025880268802788028880298803088031880328803388034880358803688037880388803988040880418804288043880448804588046880478804888049880508805188052880538805488055880568805788058880598806088061880628806388064880658806688067880688806988070880718807288073880748807588076880778807888079880808808188082880838808488085880868808788088880898809088091880928809388094880958809688097880988809988100881018810288103881048810588106881078810888109881108811188112881138811488115881168811788118881198812088121881228812388124881258812688127881288812988130881318813288133881348813588136881378813888139881408814188142881438814488145881468814788148881498815088151881528815388154881558815688157881588815988160881618816288163881648816588166881678816888169881708817188172881738817488175881768817788178881798818088181881828818388184881858818688187881888818988190881918819288193881948819588196881978819888199882008820188202882038820488205882068820788208882098821088211882128821388214882158821688217882188821988220882218822288223882248822588226882278822888229882308823188232882338823488235882368823788238882398824088241882428824388244882458824688247882488824988250882518825288253882548825588256882578825888259882608826188262882638826488265882668826788268882698827088271882728827388274882758827688277882788827988280882818828288283882848828588286882878828888289882908829188292882938829488295882968829788298882998830088301883028830388304883058830688307883088830988310883118831288313883148831588316883178831888319883208832188322883238832488325883268832788328883298833088331883328833388334883358833688337883388833988340883418834288343883448834588346883478834888349883508835188352883538835488355883568835788358883598836088361883628836388364883658836688367883688836988370883718837288373883748837588376883778837888379883808838188382883838838488385883868838788388883898839088391883928839388394883958839688397883988839988400884018840288403884048840588406884078840888409884108841188412884138841488415884168841788418884198842088421884228842388424884258842688427884288842988430884318843288433884348843588436884378843888439884408844188442884438844488445884468844788448884498845088451884528845388454884558845688457884588845988460884618846288463884648846588466884678846888469884708847188472884738847488475884768847788478884798848088481884828848388484884858848688487884888848988490884918849288493884948849588496884978849888499885008850188502885038850488505885068850788508885098851088511885128851388514885158851688517885188851988520885218852288523885248852588526885278852888529885308853188532885338853488535885368853788538885398854088541885428854388544885458854688547885488854988550885518855288553885548855588556885578855888559885608856188562885638856488565885668856788568885698857088571885728857388574885758857688577885788857988580885818858288583885848858588586885878858888589885908859188592885938859488595885968859788598885998860088601886028860388604886058860688607886088860988610886118861288613886148861588616886178861888619886208862188622886238862488625886268862788628886298863088631886328863388634886358863688637886388863988640886418864288643886448864588646886478864888649886508865188652886538865488655886568865788658886598866088661886628866388664886658866688667886688866988670886718867288673886748867588676886778867888679886808868188682886838868488685886868868788688886898869088691886928869388694886958869688697886988869988700887018870288703887048870588706887078870888709887108871188712887138871488715887168871788718887198872088721887228872388724887258872688727887288872988730887318873288733887348873588736887378873888739887408874188742887438874488745887468874788748887498875088751887528875388754887558875688757887588875988760887618876288763887648876588766887678876888769887708877188772887738877488775887768877788778887798878088781887828878388784887858878688787887888878988790887918879288793887948879588796887978879888799888008880188802888038880488805888068880788808888098881088811888128881388814888158881688817888188881988820888218882288823888248882588826888278882888829888308883188832888338883488835888368883788838888398884088841888428884388844888458884688847888488884988850888518885288853888548885588856888578885888859888608886188862888638886488865888668886788868888698887088871888728887388874888758887688877888788887988880888818888288883888848888588886888878888888889888908889188892888938889488895888968889788898888998890088901889028890388904889058890688907889088890988910889118891288913889148891588916889178891888919889208892188922889238892488925889268892788928889298893088931889328893388934889358893688937889388893988940889418894288943889448894588946889478894888949889508895188952889538895488955889568895788958889598896088961889628896388964889658896688967889688896988970889718897288973889748897588976889778897888979889808898188982889838898488985889868898788988889898899088991889928899388994889958899688997889988899989000890018900289003890048900589006890078900889009890108901189012890138901489015890168901789018890198902089021890228902389024890258902689027890288902989030890318903289033890348903589036890378903889039890408904189042890438904489045890468904789048890498905089051890528905389054890558905689057890588905989060890618906289063890648906589066890678906889069890708907189072890738907489075890768907789078890798908089081890828908389084890858908689087890888908989090890918909289093890948909589096890978909889099891008910189102891038910489105891068910789108891098911089111891128911389114891158911689117891188911989120891218912289123891248912589126891278912889129891308913189132891338913489135891368913789138891398914089141891428914389144891458914689147891488914989150891518915289153891548915589156891578915889159891608916189162891638916489165891668916789168891698917089171891728917389174891758917689177891788917989180891818918289183891848918589186891878918889189891908919189192891938919489195891968919789198891998920089201892028920389204892058920689207892088920989210892118921289213892148921589216892178921889219892208922189222892238922489225892268922789228892298923089231892328923389234892358923689237892388923989240892418924289243892448924589246892478924889249892508925189252892538925489255892568925789258892598926089261892628926389264892658926689267892688926989270892718927289273892748927589276892778927889279892808928189282892838928489285892868928789288892898929089291892928929389294892958929689297892988929989300893018930289303893048930589306893078930889309893108931189312893138931489315893168931789318893198932089321893228932389324893258932689327893288932989330893318933289333893348933589336893378933889339893408934189342893438934489345893468934789348893498935089351893528935389354893558935689357893588935989360893618936289363893648936589366893678936889369893708937189372893738937489375893768937789378893798938089381893828938389384893858938689387893888938989390893918939289393893948939589396893978939889399894008940189402894038940489405894068940789408894098941089411894128941389414894158941689417894188941989420894218942289423894248942589426894278942889429894308943189432894338943489435894368943789438894398944089441894428944389444894458944689447894488944989450894518945289453894548945589456894578945889459894608946189462894638946489465894668946789468894698947089471894728947389474894758947689477894788947989480894818948289483894848948589486894878948889489894908949189492894938949489495894968949789498894998950089501895028950389504895058950689507895088950989510895118951289513895148951589516895178951889519895208952189522895238952489525895268952789528895298953089531895328953389534895358953689537895388953989540895418954289543895448954589546895478954889549895508955189552895538955489555895568955789558895598956089561895628956389564895658956689567895688956989570895718957289573895748957589576895778957889579895808958189582895838958489585895868958789588895898959089591895928959389594895958959689597895988959989600896018960289603896048960589606896078960889609896108961189612896138961489615896168961789618896198962089621896228962389624896258962689627896288962989630896318963289633896348963589636896378963889639896408964189642896438964489645896468964789648896498965089651896528965389654896558965689657896588965989660896618966289663896648966589666896678966889669896708967189672896738967489675896768967789678896798968089681896828968389684896858968689687896888968989690896918969289693896948969589696896978969889699897008970189702897038970489705897068970789708897098971089711897128971389714897158971689717897188971989720897218972289723897248972589726897278972889729897308973189732897338973489735897368973789738897398974089741897428974389744897458974689747897488974989750897518975289753897548975589756897578975889759897608976189762897638976489765897668976789768897698977089771897728977389774897758977689777897788977989780897818978289783897848978589786897878978889789897908979189792897938979489795897968979789798897998980089801898028980389804898058980689807898088980989810898118981289813898148981589816898178981889819898208982189822898238982489825898268982789828898298983089831898328983389834898358983689837898388983989840898418984289843898448984589846898478984889849898508985189852898538985489855898568985789858898598986089861898628986389864898658986689867898688986989870898718987289873898748987589876898778987889879898808988189882898838988489885898868988789888898898989089891898928989389894898958989689897898988989989900899018990289903899048990589906899078990889909899108991189912899138991489915899168991789918899198992089921899228992389924899258992689927899288992989930899318993289933899348993589936899378993889939899408994189942899438994489945899468994789948899498995089951899528995389954899558995689957899588995989960899618996289963899648996589966899678996889969899708997189972899738997489975899768997789978899798998089981899828998389984899858998689987899888998989990899918999289993899948999589996899978999889999900009000190002900039000490005900069000790008900099001090011900129001390014900159001690017900189001990020900219002290023900249002590026900279002890029900309003190032900339003490035900369003790038900399004090041900429004390044900459004690047900489004990050900519005290053900549005590056900579005890059900609006190062900639006490065900669006790068900699007090071900729007390074900759007690077900789007990080900819008290083900849008590086900879008890089900909009190092900939009490095900969009790098900999010090101901029010390104901059010690107901089010990110901119011290113901149011590116901179011890119901209012190122901239012490125901269012790128901299013090131901329013390134901359013690137901389013990140901419014290143901449014590146901479014890149901509015190152901539015490155901569015790158901599016090161901629016390164901659016690167901689016990170901719017290173901749017590176901779017890179901809018190182901839018490185901869018790188901899019090191901929019390194901959019690197901989019990200902019020290203902049020590206902079020890209902109021190212902139021490215902169021790218902199022090221902229022390224902259022690227902289022990230902319023290233902349023590236902379023890239902409024190242902439024490245902469024790248902499025090251902529025390254902559025690257902589025990260902619026290263902649026590266902679026890269902709027190272902739027490275902769027790278902799028090281902829028390284902859028690287902889028990290902919029290293902949029590296902979029890299903009030190302903039030490305903069030790308903099031090311903129031390314903159031690317903189031990320903219032290323903249032590326903279032890329903309033190332903339033490335903369033790338903399034090341903429034390344903459034690347903489034990350903519035290353903549035590356903579035890359903609036190362903639036490365903669036790368903699037090371903729037390374903759037690377903789037990380903819038290383903849038590386903879038890389903909039190392903939039490395903969039790398903999040090401904029040390404904059040690407904089040990410904119041290413904149041590416904179041890419904209042190422904239042490425904269042790428904299043090431904329043390434904359043690437904389043990440904419044290443904449044590446904479044890449904509045190452904539045490455904569045790458904599046090461904629046390464904659046690467904689046990470904719047290473904749047590476904779047890479904809048190482904839048490485904869048790488904899049090491904929049390494904959049690497904989049990500905019050290503905049050590506905079050890509905109051190512905139051490515905169051790518905199052090521905229052390524905259052690527905289052990530905319053290533905349053590536905379053890539905409054190542905439054490545905469054790548905499055090551905529055390554905559055690557905589055990560905619056290563905649056590566905679056890569905709057190572905739057490575905769057790578905799058090581905829058390584905859058690587905889058990590905919059290593905949059590596905979059890599906009060190602906039060490605906069060790608906099061090611906129061390614906159061690617906189061990620906219062290623906249062590626906279062890629906309063190632906339063490635906369063790638906399064090641906429064390644906459064690647906489064990650906519065290653906549065590656906579065890659906609066190662906639066490665906669066790668906699067090671906729067390674906759067690677906789067990680906819068290683906849068590686906879068890689906909069190692906939069490695906969069790698906999070090701907029070390704907059070690707907089070990710907119071290713907149071590716907179071890719907209072190722907239072490725907269072790728907299073090731907329073390734907359073690737907389073990740907419074290743907449074590746907479074890749907509075190752907539075490755907569075790758907599076090761907629076390764907659076690767907689076990770907719077290773907749077590776907779077890779907809078190782907839078490785907869078790788907899079090791907929079390794907959079690797907989079990800908019080290803908049080590806908079080890809908109081190812908139081490815908169081790818908199082090821908229082390824908259082690827908289082990830908319083290833908349083590836908379083890839908409084190842908439084490845908469084790848908499085090851908529085390854908559085690857908589085990860908619086290863908649086590866908679086890869908709087190872908739087490875908769087790878908799088090881908829088390884908859088690887908889088990890908919089290893908949089590896908979089890899909009090190902909039090490905909069090790908909099091090911909129091390914909159091690917909189091990920909219092290923909249092590926909279092890929909309093190932909339093490935909369093790938909399094090941909429094390944909459094690947909489094990950909519095290953909549095590956909579095890959909609096190962909639096490965909669096790968909699097090971909729097390974909759097690977909789097990980909819098290983909849098590986909879098890989909909099190992909939099490995909969099790998909999100091001910029100391004910059100691007910089100991010910119101291013910149101591016910179101891019910209102191022910239102491025910269102791028910299103091031910329103391034910359103691037910389103991040910419104291043910449104591046910479104891049910509105191052910539105491055910569105791058910599106091061910629106391064910659106691067910689106991070910719107291073910749107591076910779107891079910809108191082910839108491085910869108791088910899109091091910929109391094910959109691097910989109991100911019110291103911049110591106911079110891109911109111191112911139111491115911169111791118911199112091121911229112391124911259112691127911289112991130911319113291133911349113591136911379113891139911409114191142911439114491145911469114791148911499115091151911529115391154911559115691157911589115991160911619116291163911649116591166911679116891169911709117191172911739117491175911769117791178911799118091181911829118391184911859118691187911889118991190911919119291193911949119591196911979119891199912009120191202912039120491205912069120791208912099121091211912129121391214912159121691217912189121991220912219122291223912249122591226912279122891229912309123191232912339123491235912369123791238912399124091241912429124391244912459124691247912489124991250912519125291253912549125591256912579125891259912609126191262912639126491265912669126791268912699127091271912729127391274912759127691277912789127991280912819128291283912849128591286912879128891289912909129191292912939129491295912969129791298912999130091301913029130391304913059130691307913089130991310913119131291313913149131591316913179131891319913209132191322913239132491325913269132791328913299133091331913329133391334913359133691337913389133991340913419134291343913449134591346913479134891349913509135191352913539135491355913569135791358913599136091361913629136391364913659136691367913689136991370913719137291373913749137591376913779137891379913809138191382913839138491385913869138791388913899139091391913929139391394913959139691397913989139991400914019140291403914049140591406914079140891409914109141191412914139141491415914169141791418914199142091421914229142391424914259142691427914289142991430914319143291433914349143591436914379143891439914409144191442914439144491445914469144791448914499145091451914529145391454914559145691457914589145991460914619146291463914649146591466914679146891469914709147191472914739147491475914769147791478914799148091481914829148391484914859148691487914889148991490914919149291493914949149591496914979149891499915009150191502915039150491505915069150791508915099151091511915129151391514915159151691517915189151991520915219152291523915249152591526915279152891529915309153191532915339153491535915369153791538915399154091541915429154391544915459154691547915489154991550915519155291553915549155591556915579155891559915609156191562915639156491565915669156791568915699157091571915729157391574915759157691577915789157991580915819158291583915849158591586915879158891589915909159191592915939159491595915969159791598915999160091601916029160391604916059160691607916089160991610916119161291613916149161591616916179161891619916209162191622916239162491625916269162791628916299163091631916329163391634916359163691637916389163991640916419164291643916449164591646916479164891649916509165191652916539165491655916569165791658916599166091661916629166391664916659166691667916689166991670916719167291673916749167591676916779167891679916809168191682916839168491685916869168791688916899169091691916929169391694916959169691697916989169991700917019170291703917049170591706917079170891709917109171191712917139171491715917169171791718917199172091721917229172391724917259172691727917289172991730917319173291733917349173591736917379173891739917409174191742917439174491745917469174791748917499175091751917529175391754917559175691757917589175991760917619176291763917649176591766917679176891769917709177191772917739177491775917769177791778917799178091781917829178391784917859178691787917889178991790917919179291793917949179591796917979179891799918009180191802918039180491805918069180791808918099181091811918129181391814918159181691817918189181991820918219182291823918249182591826918279182891829918309183191832918339183491835918369183791838918399184091841918429184391844918459184691847918489184991850918519185291853918549185591856918579185891859918609186191862918639186491865918669186791868918699187091871918729187391874918759187691877918789187991880918819188291883918849188591886918879188891889918909189191892918939189491895918969189791898918999190091901919029190391904919059190691907919089190991910919119191291913919149191591916919179191891919919209192191922919239192491925919269192791928919299193091931919329193391934919359193691937919389193991940919419194291943919449194591946919479194891949919509195191952919539195491955919569195791958919599196091961919629196391964919659196691967919689196991970919719197291973919749197591976919779197891979919809198191982919839198491985919869198791988919899199091991919929199391994919959199691997919989199992000920019200292003920049200592006920079200892009920109201192012920139201492015920169201792018920199202092021920229202392024920259202692027920289202992030920319203292033920349203592036920379203892039920409204192042920439204492045920469204792048920499205092051920529205392054920559205692057920589205992060920619206292063920649206592066920679206892069920709207192072920739207492075920769207792078920799208092081920829208392084920859208692087920889208992090920919209292093920949209592096920979209892099921009210192102921039210492105921069210792108921099211092111921129211392114921159211692117921189211992120921219212292123921249212592126921279212892129921309213192132921339213492135921369213792138921399214092141921429214392144921459214692147921489214992150921519215292153921549215592156921579215892159921609216192162921639216492165921669216792168921699217092171921729217392174921759217692177921789217992180921819218292183921849218592186921879218892189921909219192192921939219492195921969219792198921999220092201922029220392204922059220692207922089220992210922119221292213922149221592216922179221892219922209222192222922239222492225922269222792228922299223092231922329223392234922359223692237922389223992240922419224292243922449224592246922479224892249922509225192252922539225492255922569225792258922599226092261922629226392264922659226692267922689226992270922719227292273922749227592276922779227892279922809228192282922839228492285922869228792288922899229092291922929229392294922959229692297922989229992300923019230292303923049230592306923079230892309923109231192312923139231492315923169231792318923199232092321923229232392324923259232692327923289232992330923319233292333923349233592336923379233892339923409234192342923439234492345923469234792348923499235092351923529235392354923559235692357923589235992360923619236292363923649236592366923679236892369923709237192372923739237492375923769237792378923799238092381923829238392384923859238692387923889238992390923919239292393923949239592396923979239892399924009240192402924039240492405924069240792408924099241092411924129241392414924159241692417924189241992420924219242292423924249242592426924279242892429924309243192432924339243492435924369243792438924399244092441924429244392444924459244692447924489244992450924519245292453924549245592456924579245892459924609246192462924639246492465924669246792468924699247092471924729247392474924759247692477924789247992480924819248292483924849248592486924879248892489924909249192492924939249492495924969249792498924999250092501925029250392504925059250692507925089250992510925119251292513925149251592516925179251892519925209252192522925239252492525925269252792528925299253092531925329253392534925359253692537925389253992540925419254292543925449254592546925479254892549925509255192552925539255492555925569255792558925599256092561925629256392564925659256692567925689256992570925719257292573925749257592576925779257892579925809258192582925839258492585925869258792588925899259092591925929259392594925959259692597925989259992600926019260292603926049260592606926079260892609926109261192612926139261492615926169261792618926199262092621926229262392624926259262692627926289262992630926319263292633926349263592636926379263892639926409264192642926439264492645926469264792648926499265092651926529265392654926559265692657926589265992660926619266292663926649266592666926679266892669926709267192672926739267492675926769267792678926799268092681926829268392684926859268692687926889268992690926919269292693926949269592696926979269892699927009270192702927039270492705927069270792708927099271092711927129271392714927159271692717927189271992720927219272292723927249272592726927279272892729927309273192732927339273492735927369273792738927399274092741927429274392744927459274692747927489274992750927519275292753927549275592756927579275892759927609276192762927639276492765927669276792768927699277092771927729277392774927759277692777927789277992780927819278292783927849278592786927879278892789927909279192792927939279492795927969279792798927999280092801928029280392804928059280692807928089280992810928119281292813928149281592816928179281892819928209282192822928239282492825928269282792828928299283092831928329283392834928359283692837928389283992840928419284292843928449284592846928479284892849928509285192852928539285492855928569285792858928599286092861928629286392864928659286692867928689286992870928719287292873928749287592876928779287892879928809288192882928839288492885928869288792888928899289092891928929289392894928959289692897928989289992900929019290292903929049290592906929079290892909929109291192912929139291492915929169291792918929199292092921929229292392924929259292692927929289292992930929319293292933929349293592936929379293892939929409294192942929439294492945929469294792948929499295092951929529295392954929559295692957929589295992960929619296292963929649296592966929679296892969929709297192972929739297492975929769297792978929799298092981929829298392984929859298692987929889298992990929919299292993929949299592996929979299892999930009300193002930039300493005930069300793008930099301093011930129301393014930159301693017930189301993020930219302293023930249302593026930279302893029930309303193032930339303493035930369303793038930399304093041930429304393044930459304693047930489304993050930519305293053930549305593056930579305893059930609306193062930639306493065930669306793068930699307093071930729307393074930759307693077930789307993080930819308293083930849308593086930879308893089930909309193092930939309493095930969309793098930999310093101931029310393104931059310693107931089310993110931119311293113931149311593116931179311893119931209312193122931239312493125931269312793128931299313093131931329313393134931359313693137931389313993140931419314293143931449314593146931479314893149931509315193152931539315493155931569315793158931599316093161931629316393164931659316693167931689316993170931719317293173931749317593176931779317893179931809318193182931839318493185931869318793188931899319093191931929319393194931959319693197931989319993200932019320293203932049320593206932079320893209932109321193212932139321493215932169321793218932199322093221932229322393224932259322693227932289322993230932319323293233932349323593236932379323893239932409324193242932439324493245932469324793248932499325093251932529325393254932559325693257932589325993260932619326293263932649326593266932679326893269932709327193272932739327493275932769327793278932799328093281932829328393284932859328693287932889328993290932919329293293932949329593296932979329893299933009330193302933039330493305933069330793308933099331093311933129331393314933159331693317933189331993320933219332293323933249332593326933279332893329933309333193332933339333493335933369333793338933399334093341933429334393344933459334693347933489334993350933519335293353933549335593356933579335893359933609336193362933639336493365933669336793368933699337093371933729337393374933759337693377933789337993380933819338293383933849338593386933879338893389933909339193392933939339493395933969339793398933999340093401934029340393404934059340693407934089340993410934119341293413934149341593416934179341893419934209342193422934239342493425934269342793428934299343093431934329343393434934359343693437934389343993440934419344293443934449344593446934479344893449934509345193452934539345493455934569345793458934599346093461934629346393464934659346693467934689346993470934719347293473934749347593476934779347893479934809348193482934839348493485934869348793488934899349093491934929349393494934959349693497934989349993500935019350293503935049350593506935079350893509935109351193512935139351493515935169351793518935199352093521935229352393524935259352693527935289352993530935319353293533935349353593536935379353893539935409354193542935439354493545935469354793548935499355093551935529355393554935559355693557935589355993560935619356293563935649356593566935679356893569935709357193572935739357493575935769357793578935799358093581935829358393584935859358693587935889358993590935919359293593935949359593596935979359893599936009360193602936039360493605936069360793608936099361093611936129361393614936159361693617936189361993620936219362293623936249362593626936279362893629936309363193632936339363493635936369363793638936399364093641936429364393644936459364693647936489364993650936519365293653936549365593656936579365893659936609366193662936639366493665936669366793668936699367093671936729367393674936759367693677936789367993680936819368293683936849368593686936879368893689936909369193692936939369493695936969369793698936999370093701937029370393704937059370693707937089370993710937119371293713937149371593716937179371893719937209372193722937239372493725937269372793728937299373093731937329373393734937359373693737937389373993740937419374293743937449374593746937479374893749937509375193752937539375493755937569375793758937599376093761937629376393764937659376693767937689376993770937719377293773937749377593776937779377893779937809378193782937839378493785937869378793788937899379093791937929379393794937959379693797937989379993800938019380293803938049380593806938079380893809938109381193812938139381493815938169381793818938199382093821938229382393824938259382693827938289382993830938319383293833938349383593836938379383893839938409384193842938439384493845938469384793848938499385093851938529385393854938559385693857938589385993860938619386293863938649386593866938679386893869938709387193872938739387493875938769387793878938799388093881938829388393884938859388693887938889388993890938919389293893938949389593896938979389893899939009390193902939039390493905939069390793908939099391093911939129391393914939159391693917939189391993920939219392293923939249392593926939279392893929939309393193932939339393493935939369393793938939399394093941939429394393944939459394693947939489394993950939519395293953939549395593956939579395893959939609396193962939639396493965939669396793968939699397093971939729397393974939759397693977939789397993980939819398293983939849398593986939879398893989939909399193992939939399493995939969399793998939999400094001940029400394004940059400694007940089400994010940119401294013940149401594016940179401894019940209402194022940239402494025940269402794028940299403094031940329403394034940359403694037940389403994040940419404294043940449404594046940479404894049940509405194052940539405494055940569405794058940599406094061940629406394064940659406694067940689406994070940719407294073940749407594076940779407894079940809408194082940839408494085940869408794088940899409094091940929409394094940959409694097940989409994100941019410294103941049410594106941079410894109941109411194112941139411494115941169411794118941199412094121941229412394124941259412694127941289412994130941319413294133941349413594136941379413894139941409414194142941439414494145941469414794148941499415094151941529415394154941559415694157941589415994160941619416294163941649416594166941679416894169941709417194172941739417494175941769417794178941799418094181941829418394184941859418694187941889418994190941919419294193941949419594196941979419894199942009420194202942039420494205942069420794208942099421094211942129421394214942159421694217942189421994220942219422294223942249422594226942279422894229942309423194232942339423494235942369423794238942399424094241942429424394244942459424694247942489424994250942519425294253942549425594256942579425894259942609426194262942639426494265942669426794268942699427094271942729427394274942759427694277942789427994280942819428294283942849428594286942879428894289942909429194292942939429494295942969429794298942999430094301943029430394304943059430694307943089430994310943119431294313943149431594316943179431894319943209432194322943239432494325943269432794328943299433094331943329433394334943359433694337943389433994340943419434294343943449434594346943479434894349943509435194352943539435494355943569435794358943599436094361943629436394364943659436694367943689436994370943719437294373943749437594376943779437894379943809438194382943839438494385943869438794388943899439094391943929439394394943959439694397943989439994400944019440294403944049440594406944079440894409944109441194412944139441494415944169441794418944199442094421944229442394424944259442694427944289442994430944319443294433944349443594436944379443894439944409444194442944439444494445944469444794448944499445094451944529445394454944559445694457944589445994460944619446294463944649446594466944679446894469944709447194472944739447494475944769447794478944799448094481944829448394484944859448694487944889448994490944919449294493944949449594496944979449894499945009450194502945039450494505945069450794508945099451094511945129451394514945159451694517945189451994520945219452294523945249452594526945279452894529945309453194532945339453494535945369453794538945399454094541945429454394544945459454694547945489454994550945519455294553945549455594556945579455894559945609456194562945639456494565945669456794568945699457094571945729457394574945759457694577945789457994580945819458294583945849458594586945879458894589945909459194592945939459494595945969459794598945999460094601946029460394604946059460694607946089460994610946119461294613946149461594616946179461894619946209462194622946239462494625946269462794628946299463094631946329463394634946359463694637946389463994640946419464294643946449464594646946479464894649946509465194652946539465494655946569465794658946599466094661946629466394664946659466694667946689466994670946719467294673946749467594676946779467894679946809468194682946839468494685946869468794688946899469094691946929469394694946959469694697946989469994700947019470294703947049470594706947079470894709947109471194712947139471494715947169471794718947199472094721947229472394724947259472694727947289472994730947319473294733947349473594736947379473894739947409474194742947439474494745947469474794748947499475094751947529475394754947559475694757947589475994760947619476294763947649476594766947679476894769947709477194772947739477494775947769477794778947799478094781947829478394784947859478694787947889478994790947919479294793947949479594796947979479894799948009480194802948039480494805948069480794808948099481094811948129481394814948159481694817948189481994820948219482294823948249482594826948279482894829948309483194832948339483494835948369483794838948399484094841948429484394844948459484694847948489484994850948519485294853948549485594856948579485894859948609486194862948639486494865948669486794868948699487094871948729487394874948759487694877948789487994880948819488294883948849488594886948879488894889948909489194892948939489494895948969489794898948999490094901949029490394904949059490694907949089490994910949119491294913949149491594916949179491894919949209492194922949239492494925949269492794928949299493094931949329493394934949359493694937949389493994940949419494294943949449494594946949479494894949949509495194952949539495494955949569495794958949599496094961949629496394964949659496694967949689496994970949719497294973949749497594976949779497894979949809498194982949839498494985949869498794988949899499094991949929499394994949959499694997949989499995000950019500295003950049500595006950079500895009950109501195012950139501495015950169501795018950199502095021950229502395024950259502695027950289502995030950319503295033950349503595036950379503895039950409504195042950439504495045950469504795048950499505095051950529505395054950559505695057950589505995060950619506295063950649506595066950679506895069950709507195072950739507495075950769507795078950799508095081950829508395084950859508695087950889508995090950919509295093950949509595096950979509895099951009510195102951039510495105951069510795108951099511095111951129511395114951159511695117951189511995120951219512295123951249512595126951279512895129951309513195132951339513495135951369513795138951399514095141951429514395144951459514695147951489514995150951519515295153951549515595156951579515895159951609516195162951639516495165951669516795168951699517095171951729517395174951759517695177951789517995180951819518295183951849518595186951879518895189951909519195192951939519495195951969519795198951999520095201952029520395204952059520695207952089520995210952119521295213952149521595216952179521895219952209522195222952239522495225952269522795228952299523095231952329523395234952359523695237952389523995240952419524295243952449524595246952479524895249952509525195252952539525495255952569525795258952599526095261952629526395264952659526695267952689526995270952719527295273952749527595276952779527895279952809528195282952839528495285952869528795288952899529095291952929529395294952959529695297952989529995300953019530295303953049530595306953079530895309953109531195312953139531495315953169531795318953199532095321953229532395324953259532695327953289532995330953319533295333953349533595336953379533895339953409534195342953439534495345953469534795348953499535095351953529535395354953559535695357953589535995360953619536295363953649536595366953679536895369953709537195372953739537495375953769537795378953799538095381953829538395384953859538695387953889538995390953919539295393953949539595396953979539895399954009540195402954039540495405954069540795408954099541095411954129541395414954159541695417954189541995420954219542295423954249542595426954279542895429954309543195432954339543495435954369543795438954399544095441954429544395444954459544695447954489544995450954519545295453954549545595456954579545895459954609546195462954639546495465954669546795468954699547095471954729547395474954759547695477954789547995480954819548295483954849548595486954879548895489954909549195492954939549495495954969549795498954999550095501955029550395504955059550695507955089550995510955119551295513955149551595516955179551895519955209552195522955239552495525955269552795528955299553095531955329553395534955359553695537955389553995540955419554295543955449554595546955479554895549955509555195552955539555495555955569555795558955599556095561955629556395564955659556695567955689556995570955719557295573955749557595576955779557895579955809558195582955839558495585955869558795588955899559095591955929559395594955959559695597955989559995600956019560295603956049560595606956079560895609956109561195612956139561495615956169561795618956199562095621956229562395624956259562695627956289562995630956319563295633956349563595636956379563895639956409564195642956439564495645956469564795648956499565095651956529565395654956559565695657956589565995660956619566295663956649566595666956679566895669956709567195672956739567495675956769567795678956799568095681956829568395684956859568695687956889568995690956919569295693956949569595696956979569895699957009570195702957039570495705957069570795708957099571095711957129571395714957159571695717957189571995720957219572295723957249572595726957279572895729957309573195732957339573495735957369573795738957399574095741957429574395744957459574695747957489574995750957519575295753957549575595756957579575895759957609576195762957639576495765957669576795768957699577095771957729577395774957759577695777957789577995780957819578295783957849578595786957879578895789957909579195792957939579495795957969579795798957999580095801958029580395804958059580695807958089580995810958119581295813958149581595816958179581895819958209582195822958239582495825958269582795828958299583095831958329583395834958359583695837958389583995840958419584295843958449584595846958479584895849958509585195852958539585495855958569585795858958599586095861958629586395864958659586695867958689586995870958719587295873958749587595876958779587895879958809588195882958839588495885958869588795888958899589095891958929589395894958959589695897958989589995900959019590295903959049590595906959079590895909959109591195912959139591495915959169591795918959199592095921959229592395924959259592695927959289592995930959319593295933959349593595936959379593895939959409594195942959439594495945959469594795948959499595095951959529595395954959559595695957959589595995960959619596295963959649596595966959679596895969959709597195972959739597495975959769597795978959799598095981959829598395984959859598695987959889598995990959919599295993959949599595996959979599895999960009600196002960039600496005960069600796008960099601096011960129601396014960159601696017960189601996020960219602296023960249602596026960279602896029960309603196032960339603496035960369603796038960399604096041960429604396044960459604696047960489604996050960519605296053960549605596056960579605896059960609606196062960639606496065960669606796068960699607096071960729607396074960759607696077960789607996080960819608296083960849608596086960879608896089960909609196092960939609496095960969609796098960999610096101961029610396104961059610696107961089610996110961119611296113961149611596116961179611896119961209612196122961239612496125961269612796128961299613096131961329613396134961359613696137961389613996140961419614296143961449614596146961479614896149961509615196152961539615496155961569615796158961599616096161961629616396164961659616696167961689616996170961719617296173961749617596176961779617896179961809618196182961839618496185961869618796188961899619096191961929619396194961959619696197961989619996200962019620296203962049620596206962079620896209962109621196212962139621496215962169621796218962199622096221962229622396224962259622696227962289622996230962319623296233962349623596236962379623896239962409624196242962439624496245962469624796248962499625096251962529625396254962559625696257962589625996260962619626296263962649626596266962679626896269962709627196272962739627496275962769627796278962799628096281962829628396284962859628696287962889628996290962919629296293962949629596296962979629896299963009630196302963039630496305963069630796308963099631096311963129631396314963159631696317963189631996320963219632296323963249632596326963279632896329963309633196332963339633496335963369633796338963399634096341963429634396344963459634696347963489634996350963519635296353963549635596356963579635896359963609636196362963639636496365963669636796368963699637096371963729637396374963759637696377963789637996380963819638296383963849638596386963879638896389963909639196392963939639496395963969639796398963999640096401964029640396404964059640696407964089640996410964119641296413964149641596416964179641896419964209642196422964239642496425964269642796428964299643096431964329643396434964359643696437964389643996440964419644296443964449644596446964479644896449964509645196452964539645496455964569645796458964599646096461964629646396464964659646696467964689646996470964719647296473964749647596476964779647896479964809648196482964839648496485964869648796488964899649096491964929649396494964959649696497964989649996500965019650296503965049650596506965079650896509965109651196512965139651496515965169651796518965199652096521965229652396524965259652696527965289652996530965319653296533965349653596536965379653896539965409654196542965439654496545965469654796548965499655096551965529655396554965559655696557965589655996560965619656296563965649656596566965679656896569965709657196572965739657496575965769657796578965799658096581965829658396584965859658696587965889658996590965919659296593965949659596596965979659896599966009660196602966039660496605966069660796608966099661096611966129661396614966159661696617966189661996620966219662296623966249662596626966279662896629966309663196632966339663496635966369663796638966399664096641966429664396644966459664696647966489664996650966519665296653966549665596656966579665896659966609666196662966639666496665966669666796668966699667096671966729667396674966759667696677966789667996680966819668296683966849668596686966879668896689966909669196692966939669496695966969669796698966999670096701967029670396704967059670696707967089670996710967119671296713967149671596716967179671896719967209672196722967239672496725967269672796728967299673096731967329673396734967359673696737967389673996740967419674296743967449674596746967479674896749967509675196752967539675496755967569675796758967599676096761967629676396764967659676696767967689676996770967719677296773967749677596776967779677896779967809678196782967839678496785967869678796788967899679096791967929679396794967959679696797967989679996800968019680296803968049680596806968079680896809968109681196812968139681496815968169681796818968199682096821968229682396824968259682696827968289682996830968319683296833968349683596836968379683896839968409684196842968439684496845968469684796848968499685096851968529685396854968559685696857968589685996860968619686296863968649686596866968679686896869968709687196872968739687496875968769687796878968799688096881968829688396884968859688696887968889688996890968919689296893968949689596896968979689896899969009690196902969039690496905969069690796908969099691096911969129691396914969159691696917969189691996920969219692296923969249692596926969279692896929969309693196932969339693496935969369693796938969399694096941969429694396944969459694696947969489694996950969519695296953969549695596956969579695896959969609696196962969639696496965969669696796968969699697096971969729697396974969759697696977969789697996980969819698296983969849698596986969879698896989969909699196992969939699496995969969699796998969999700097001970029700397004970059700697007970089700997010970119701297013970149701597016970179701897019970209702197022970239702497025970269702797028970299703097031970329703397034970359703697037970389703997040970419704297043970449704597046970479704897049970509705197052970539705497055970569705797058970599706097061970629706397064970659706697067970689706997070970719707297073970749707597076970779707897079970809708197082970839708497085970869708797088970899709097091970929709397094970959709697097970989709997100971019710297103971049710597106971079710897109971109711197112971139711497115971169711797118971199712097121971229712397124971259712697127971289712997130971319713297133971349713597136971379713897139971409714197142971439714497145971469714797148971499715097151971529715397154971559715697157971589715997160971619716297163971649716597166971679716897169971709717197172971739717497175971769717797178971799718097181971829718397184971859718697187971889718997190971919719297193971949719597196971979719897199972009720197202972039720497205972069720797208972099721097211972129721397214972159721697217972189721997220972219722297223972249722597226972279722897229972309723197232972339723497235972369723797238972399724097241972429724397244972459724697247972489724997250972519725297253972549725597256972579725897259972609726197262972639726497265972669726797268972699727097271972729727397274972759727697277972789727997280972819728297283972849728597286972879728897289972909729197292972939729497295972969729797298972999730097301973029730397304973059730697307973089730997310973119731297313973149731597316973179731897319973209732197322973239732497325973269732797328973299733097331973329733397334973359733697337973389733997340973419734297343973449734597346973479734897349973509735197352973539735497355973569735797358973599736097361973629736397364973659736697367973689736997370973719737297373973749737597376973779737897379973809738197382973839738497385973869738797388973899739097391973929739397394973959739697397973989739997400974019740297403974049740597406974079740897409974109741197412974139741497415974169741797418974199742097421974229742397424974259742697427974289742997430974319743297433974349743597436974379743897439974409744197442974439744497445974469744797448974499745097451974529745397454974559745697457974589745997460974619746297463974649746597466974679746897469974709747197472974739747497475974769747797478974799748097481974829748397484974859748697487974889748997490974919749297493974949749597496974979749897499975009750197502975039750497505975069750797508975099751097511975129751397514975159751697517975189751997520975219752297523975249752597526975279752897529975309753197532975339753497535975369753797538975399754097541975429754397544975459754697547975489754997550975519755297553975549755597556975579755897559975609756197562975639756497565975669756797568975699757097571975729757397574975759757697577975789757997580975819758297583975849758597586975879758897589975909759197592975939759497595975969759797598975999760097601976029760397604976059760697607976089760997610976119761297613976149761597616976179761897619976209762197622976239762497625976269762797628976299763097631976329763397634976359763697637976389763997640976419764297643976449764597646976479764897649976509765197652976539765497655976569765797658976599766097661976629766397664976659766697667976689766997670976719767297673976749767597676976779767897679976809768197682976839768497685976869768797688976899769097691976929769397694976959769697697976989769997700977019770297703977049770597706977079770897709977109771197712977139771497715977169771797718977199772097721977229772397724977259772697727977289772997730977319773297733977349773597736977379773897739977409774197742977439774497745977469774797748977499775097751977529775397754977559775697757977589775997760977619776297763977649776597766977679776897769977709777197772977739777497775977769777797778977799778097781977829778397784977859778697787977889778997790977919779297793977949779597796977979779897799978009780197802978039780497805978069780797808978099781097811978129781397814978159781697817978189781997820978219782297823978249782597826978279782897829978309783197832978339783497835978369783797838978399784097841978429784397844978459784697847978489784997850978519785297853978549785597856978579785897859978609786197862978639786497865978669786797868978699787097871978729787397874978759787697877978789787997880978819788297883978849788597886978879788897889978909789197892978939789497895978969789797898978999790097901979029790397904979059790697907979089790997910979119791297913979149791597916979179791897919979209792197922979239792497925979269792797928979299793097931979329793397934979359793697937979389793997940979419794297943979449794597946979479794897949979509795197952979539795497955979569795797958979599796097961979629796397964979659796697967979689796997970979719797297973979749797597976979779797897979979809798197982979839798497985979869798797988979899799097991979929799397994979959799697997979989799998000980019800298003980049800598006980079800898009980109801198012980139801498015980169801798018980199802098021980229802398024980259802698027980289802998030980319803298033980349803598036980379803898039980409804198042980439804498045980469804798048980499805098051980529805398054980559805698057980589805998060980619806298063980649806598066980679806898069980709807198072980739807498075980769807798078980799808098081980829808398084980859808698087980889808998090980919809298093980949809598096980979809898099981009810198102981039810498105981069810798108981099811098111981129811398114981159811698117981189811998120981219812298123981249812598126981279812898129981309813198132981339813498135981369813798138981399814098141981429814398144981459814698147981489814998150981519815298153981549815598156981579815898159981609816198162981639816498165981669816798168981699817098171981729817398174981759817698177981789817998180981819818298183981849818598186981879818898189981909819198192981939819498195981969819798198981999820098201982029820398204982059820698207982089820998210982119821298213982149821598216982179821898219982209822198222982239822498225982269822798228982299823098231982329823398234982359823698237982389823998240982419824298243982449824598246982479824898249982509825198252982539825498255982569825798258982599826098261982629826398264982659826698267982689826998270982719827298273982749827598276982779827898279982809828198282982839828498285982869828798288982899829098291982929829398294982959829698297982989829998300983019830298303983049830598306983079830898309983109831198312983139831498315983169831798318983199832098321983229832398324983259832698327983289832998330983319833298333983349833598336983379833898339983409834198342983439834498345983469834798348983499835098351983529835398354983559835698357983589835998360983619836298363983649836598366983679836898369983709837198372983739837498375983769837798378983799838098381983829838398384983859838698387
  1. /**
  2. * @author Richard Davey <rich@photonstorm.com>
  3. * @copyright 2016 Photon Storm Ltd.
  4. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  5. *
  6. * @overview
  7. *
  8. * Phaser - http://phaser.io
  9. *
  10. * v2.4.7 "Hinderstap" - Built: Fri Apr 22 2016 15:08:21
  11. *
  12. * By Richard Davey http://www.photonstorm.com @photonstorm
  13. *
  14. * Phaser is a fun, free and fast 2D game framework for making HTML5 games
  15. * for desktop and mobile web browsers, supporting Canvas and WebGL rendering.
  16. *
  17. * Phaser uses Pixi.js for rendering, created by Mat Groves http://matgroves.com @Doormat23
  18. * Phaser uses p2.js for full-body physics, created by Stefan Hedman https://github.com/schteppe/p2.js @schteppe
  19. * Phaser contains a port of N+ Physics, converted by Richard Davey, original by http://www.metanetsoftware.com
  20. *
  21. * Many thanks to Adam Saltsman (@ADAMATOMIC) for releasing Flixel, from which both Phaser
  22. * and my love of framework development originate.
  23. *
  24. * Follow development at http://phaser.io and on our forum
  25. *
  26. * "If you want your children to be intelligent, read them fairy tales."
  27. * "If you want them to be more intelligent, read them more fairy tales."
  28. * -- Albert Einstein
  29. */
  30. /**
  31. * The MIT License (MIT)
  32. *
  33. * Copyright (c) 2015 p2.js authors
  34. *
  35. * Permission is hereby granted, free of charge, to any person obtaining a copy
  36. * of this software and associated documentation files (the "Software"), to deal
  37. * in the Software without restriction, including without limitation the rights
  38. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  39. * copies of the Software, and to permit persons to whom the Software is
  40. * furnished to do so, subject to the following conditions:
  41. *
  42. * The above copyright notice and this permission notice shall be included in
  43. * all copies or substantial portions of the Software.
  44. *
  45. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  46. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  47. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  48. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  49. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  50. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  51. * THE SOFTWARE.
  52. */
  53. !function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&false)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.p2=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
  54. var Scalar = _dereq_('./Scalar');
  55. module.exports = Line;
  56. /**
  57. * Container for line-related functions
  58. * @class Line
  59. */
  60. function Line(){};
  61. /**
  62. * Compute the intersection between two lines.
  63. * @static
  64. * @method lineInt
  65. * @param {Array} l1 Line vector 1
  66. * @param {Array} l2 Line vector 2
  67. * @param {Number} precision Precision to use when checking if the lines are parallel
  68. * @return {Array} The intersection point.
  69. */
  70. Line.lineInt = function(l1,l2,precision){
  71. precision = precision || 0;
  72. var i = [0,0]; // point
  73. var a1, b1, c1, a2, b2, c2, det; // scalars
  74. a1 = l1[1][1] - l1[0][1];
  75. b1 = l1[0][0] - l1[1][0];
  76. c1 = a1 * l1[0][0] + b1 * l1[0][1];
  77. a2 = l2[1][1] - l2[0][1];
  78. b2 = l2[0][0] - l2[1][0];
  79. c2 = a2 * l2[0][0] + b2 * l2[0][1];
  80. det = a1 * b2 - a2*b1;
  81. if (!Scalar.eq(det, 0, precision)) { // lines are not parallel
  82. i[0] = (b2 * c1 - b1 * c2) / det;
  83. i[1] = (a1 * c2 - a2 * c1) / det;
  84. }
  85. return i;
  86. };
  87. /**
  88. * Checks if two line segments intersects.
  89. * @method segmentsIntersect
  90. * @param {Array} p1 The start vertex of the first line segment.
  91. * @param {Array} p2 The end vertex of the first line segment.
  92. * @param {Array} q1 The start vertex of the second line segment.
  93. * @param {Array} q2 The end vertex of the second line segment.
  94. * @return {Boolean} True if the two line segments intersect
  95. */
  96. Line.segmentsIntersect = function(p1, p2, q1, q2){
  97. var dx = p2[0] - p1[0];
  98. var dy = p2[1] - p1[1];
  99. var da = q2[0] - q1[0];
  100. var db = q2[1] - q1[1];
  101. // segments are parallel
  102. if(da*dy - db*dx == 0)
  103. return false;
  104. var s = (dx * (q1[1] - p1[1]) + dy * (p1[0] - q1[0])) / (da * dy - db * dx)
  105. var t = (da * (p1[1] - q1[1]) + db * (q1[0] - p1[0])) / (db * dx - da * dy)
  106. return (s>=0 && s<=1 && t>=0 && t<=1);
  107. };
  108. },{"./Scalar":4}],2:[function(_dereq_,module,exports){
  109. module.exports = Point;
  110. /**
  111. * Point related functions
  112. * @class Point
  113. */
  114. function Point(){};
  115. /**
  116. * Get the area of a triangle spanned by the three given points. Note that the area will be negative if the points are not given in counter-clockwise order.
  117. * @static
  118. * @method area
  119. * @param {Array} a
  120. * @param {Array} b
  121. * @param {Array} c
  122. * @return {Number}
  123. */
  124. Point.area = function(a,b,c){
  125. return (((b[0] - a[0])*(c[1] - a[1]))-((c[0] - a[0])*(b[1] - a[1])));
  126. };
  127. Point.left = function(a,b,c){
  128. return Point.area(a,b,c) > 0;
  129. };
  130. Point.leftOn = function(a,b,c) {
  131. return Point.area(a, b, c) >= 0;
  132. };
  133. Point.right = function(a,b,c) {
  134. return Point.area(a, b, c) < 0;
  135. };
  136. Point.rightOn = function(a,b,c) {
  137. return Point.area(a, b, c) <= 0;
  138. };
  139. var tmpPoint1 = [],
  140. tmpPoint2 = [];
  141. /**
  142. * Check if three points are collinear
  143. * @method collinear
  144. * @param {Array} a
  145. * @param {Array} b
  146. * @param {Array} c
  147. * @param {Number} [thresholdAngle=0] Threshold angle to use when comparing the vectors. The function will return true if the angle between the resulting vectors is less than this value. Use zero for max precision.
  148. * @return {Boolean}
  149. */
  150. Point.collinear = function(a,b,c,thresholdAngle) {
  151. if(!thresholdAngle)
  152. return Point.area(a, b, c) == 0;
  153. else {
  154. var ab = tmpPoint1,
  155. bc = tmpPoint2;
  156. ab[0] = b[0]-a[0];
  157. ab[1] = b[1]-a[1];
  158. bc[0] = c[0]-b[0];
  159. bc[1] = c[1]-b[1];
  160. var dot = ab[0]*bc[0] + ab[1]*bc[1],
  161. magA = Math.sqrt(ab[0]*ab[0] + ab[1]*ab[1]),
  162. magB = Math.sqrt(bc[0]*bc[0] + bc[1]*bc[1]),
  163. angle = Math.acos(dot/(magA*magB));
  164. return angle < thresholdAngle;
  165. }
  166. };
  167. Point.sqdist = function(a,b){
  168. var dx = b[0] - a[0];
  169. var dy = b[1] - a[1];
  170. return dx * dx + dy * dy;
  171. };
  172. },{}],3:[function(_dereq_,module,exports){
  173. var Line = _dereq_("./Line")
  174. , Point = _dereq_("./Point")
  175. , Scalar = _dereq_("./Scalar")
  176. module.exports = Polygon;
  177. /**
  178. * Polygon class.
  179. * @class Polygon
  180. * @constructor
  181. */
  182. function Polygon(){
  183. /**
  184. * Vertices that this polygon consists of. An array of array of numbers, example: [[0,0],[1,0],..]
  185. * @property vertices
  186. * @type {Array}
  187. */
  188. this.vertices = [];
  189. }
  190. /**
  191. * Get a vertex at position i. It does not matter if i is out of bounds, this function will just cycle.
  192. * @method at
  193. * @param {Number} i
  194. * @return {Array}
  195. */
  196. Polygon.prototype.at = function(i){
  197. var v = this.vertices,
  198. s = v.length;
  199. return v[i < 0 ? i % s + s : i % s];
  200. };
  201. /**
  202. * Get first vertex
  203. * @method first
  204. * @return {Array}
  205. */
  206. Polygon.prototype.first = function(){
  207. return this.vertices[0];
  208. };
  209. /**
  210. * Get last vertex
  211. * @method last
  212. * @return {Array}
  213. */
  214. Polygon.prototype.last = function(){
  215. return this.vertices[this.vertices.length-1];
  216. };
  217. /**
  218. * Clear the polygon data
  219. * @method clear
  220. * @return {Array}
  221. */
  222. Polygon.prototype.clear = function(){
  223. this.vertices.length = 0;
  224. };
  225. /**
  226. * Append points "from" to "to"-1 from an other polygon "poly" onto this one.
  227. * @method append
  228. * @param {Polygon} poly The polygon to get points from.
  229. * @param {Number} from The vertex index in "poly".
  230. * @param {Number} to The end vertex index in "poly". Note that this vertex is NOT included when appending.
  231. * @return {Array}
  232. */
  233. Polygon.prototype.append = function(poly,from,to){
  234. if(typeof(from) == "undefined") throw new Error("From is not given!");
  235. if(typeof(to) == "undefined") throw new Error("To is not given!");
  236. if(to-1 < from) throw new Error("lol1");
  237. if(to > poly.vertices.length) throw new Error("lol2");
  238. if(from < 0) throw new Error("lol3");
  239. for(var i=from; i<to; i++){
  240. this.vertices.push(poly.vertices[i]);
  241. }
  242. };
  243. /**
  244. * Make sure that the polygon vertices are ordered counter-clockwise.
  245. * @method makeCCW
  246. */
  247. Polygon.prototype.makeCCW = function(){
  248. var br = 0,
  249. v = this.vertices;
  250. // find bottom right point
  251. for (var i = 1; i < this.vertices.length; ++i) {
  252. if (v[i][1] < v[br][1] || (v[i][1] == v[br][1] && v[i][0] > v[br][0])) {
  253. br = i;
  254. }
  255. }
  256. // reverse poly if clockwise
  257. if (!Point.left(this.at(br - 1), this.at(br), this.at(br + 1))) {
  258. this.reverse();
  259. }
  260. };
  261. /**
  262. * Reverse the vertices in the polygon
  263. * @method reverse
  264. */
  265. Polygon.prototype.reverse = function(){
  266. var tmp = [];
  267. for(var i=0, N=this.vertices.length; i!==N; i++){
  268. tmp.push(this.vertices.pop());
  269. }
  270. this.vertices = tmp;
  271. };
  272. /**
  273. * Check if a point in the polygon is a reflex point
  274. * @method isReflex
  275. * @param {Number} i
  276. * @return {Boolean}
  277. */
  278. Polygon.prototype.isReflex = function(i){
  279. return Point.right(this.at(i - 1), this.at(i), this.at(i + 1));
  280. };
  281. var tmpLine1=[],
  282. tmpLine2=[];
  283. /**
  284. * Check if two vertices in the polygon can see each other
  285. * @method canSee
  286. * @param {Number} a Vertex index 1
  287. * @param {Number} b Vertex index 2
  288. * @return {Boolean}
  289. */
  290. Polygon.prototype.canSee = function(a,b) {
  291. var p, dist, l1=tmpLine1, l2=tmpLine2;
  292. if (Point.leftOn(this.at(a + 1), this.at(a), this.at(b)) && Point.rightOn(this.at(a - 1), this.at(a), this.at(b))) {
  293. return false;
  294. }
  295. dist = Point.sqdist(this.at(a), this.at(b));
  296. for (var i = 0; i !== this.vertices.length; ++i) { // for each edge
  297. if ((i + 1) % this.vertices.length === a || i === a) // ignore incident edges
  298. continue;
  299. if (Point.leftOn(this.at(a), this.at(b), this.at(i + 1)) && Point.rightOn(this.at(a), this.at(b), this.at(i))) { // if diag intersects an edge
  300. l1[0] = this.at(a);
  301. l1[1] = this.at(b);
  302. l2[0] = this.at(i);
  303. l2[1] = this.at(i + 1);
  304. p = Line.lineInt(l1,l2);
  305. if (Point.sqdist(this.at(a), p) < dist) { // if edge is blocking visibility to b
  306. return false;
  307. }
  308. }
  309. }
  310. return true;
  311. };
  312. /**
  313. * Copy the polygon from vertex i to vertex j.
  314. * @method copy
  315. * @param {Number} i
  316. * @param {Number} j
  317. * @param {Polygon} [targetPoly] Optional target polygon to save in.
  318. * @return {Polygon} The resulting copy.
  319. */
  320. Polygon.prototype.copy = function(i,j,targetPoly){
  321. var p = targetPoly || new Polygon();
  322. p.clear();
  323. if (i < j) {
  324. // Insert all vertices from i to j
  325. for(var k=i; k<=j; k++)
  326. p.vertices.push(this.vertices[k]);
  327. } else {
  328. // Insert vertices 0 to j
  329. for(var k=0; k<=j; k++)
  330. p.vertices.push(this.vertices[k]);
  331. // Insert vertices i to end
  332. for(var k=i; k<this.vertices.length; k++)
  333. p.vertices.push(this.vertices[k]);
  334. }
  335. return p;
  336. };
  337. /**
  338. * Decomposes the polygon into convex pieces. Returns a list of edges [[p1,p2],[p2,p3],...] that cuts the polygon.
  339. * Note that this algorithm has complexity O(N^4) and will be very slow for polygons with many vertices.
  340. * @method getCutEdges
  341. * @return {Array}
  342. */
  343. Polygon.prototype.getCutEdges = function() {
  344. var min=[], tmp1=[], tmp2=[], tmpPoly = new Polygon();
  345. var nDiags = Number.MAX_VALUE;
  346. for (var i = 0; i < this.vertices.length; ++i) {
  347. if (this.isReflex(i)) {
  348. for (var j = 0; j < this.vertices.length; ++j) {
  349. if (this.canSee(i, j)) {
  350. tmp1 = this.copy(i, j, tmpPoly).getCutEdges();
  351. tmp2 = this.copy(j, i, tmpPoly).getCutEdges();
  352. for(var k=0; k<tmp2.length; k++)
  353. tmp1.push(tmp2[k]);
  354. if (tmp1.length < nDiags) {
  355. min = tmp1;
  356. nDiags = tmp1.length;
  357. min.push([this.at(i), this.at(j)]);
  358. }
  359. }
  360. }
  361. }
  362. }
  363. return min;
  364. };
  365. /**
  366. * Decomposes the polygon into one or more convex sub-Polygons.
  367. * @method decomp
  368. * @return {Array} An array or Polygon objects.
  369. */
  370. Polygon.prototype.decomp = function(){
  371. var edges = this.getCutEdges();
  372. if(edges.length > 0)
  373. return this.slice(edges);
  374. else
  375. return [this];
  376. };
  377. /**
  378. * Slices the polygon given one or more cut edges. If given one, this function will return two polygons (false on failure). If many, an array of polygons.
  379. * @method slice
  380. * @param {Array} cutEdges A list of edges, as returned by .getCutEdges()
  381. * @return {Array}
  382. */
  383. Polygon.prototype.slice = function(cutEdges){
  384. if(cutEdges.length == 0) return [this];
  385. if(cutEdges instanceof Array && cutEdges.length && cutEdges[0] instanceof Array && cutEdges[0].length==2 && cutEdges[0][0] instanceof Array){
  386. var polys = [this];
  387. for(var i=0; i<cutEdges.length; i++){
  388. var cutEdge = cutEdges[i];
  389. // Cut all polys
  390. for(var j=0; j<polys.length; j++){
  391. var poly = polys[j];
  392. var result = poly.slice(cutEdge);
  393. if(result){
  394. // Found poly! Cut and quit
  395. polys.splice(j,1);
  396. polys.push(result[0],result[1]);
  397. break;
  398. }
  399. }
  400. }
  401. return polys;
  402. } else {
  403. // Was given one edge
  404. var cutEdge = cutEdges;
  405. var i = this.vertices.indexOf(cutEdge[0]);
  406. var j = this.vertices.indexOf(cutEdge[1]);
  407. if(i != -1 && j != -1){
  408. return [this.copy(i,j),
  409. this.copy(j,i)];
  410. } else {
  411. return false;
  412. }
  413. }
  414. };
  415. /**
  416. * Checks that the line segments of this polygon do not intersect each other.
  417. * @method isSimple
  418. * @param {Array} path An array of vertices e.g. [[0,0],[0,1],...]
  419. * @return {Boolean}
  420. * @todo Should it check all segments with all others?
  421. */
  422. Polygon.prototype.isSimple = function(){
  423. var path = this.vertices;
  424. // Check
  425. for(var i=0; i<path.length-1; i++){
  426. for(var j=0; j<i-1; j++){
  427. if(Line.segmentsIntersect(path[i], path[i+1], path[j], path[j+1] )){
  428. return false;
  429. }
  430. }
  431. }
  432. // Check the segment between the last and the first point to all others
  433. for(var i=1; i<path.length-2; i++){
  434. if(Line.segmentsIntersect(path[0], path[path.length-1], path[i], path[i+1] )){
  435. return false;
  436. }
  437. }
  438. return true;
  439. };
  440. function getIntersectionPoint(p1, p2, q1, q2, delta){
  441. delta = delta || 0;
  442. var a1 = p2[1] - p1[1];
  443. var b1 = p1[0] - p2[0];
  444. var c1 = (a1 * p1[0]) + (b1 * p1[1]);
  445. var a2 = q2[1] - q1[1];
  446. var b2 = q1[0] - q2[0];
  447. var c2 = (a2 * q1[0]) + (b2 * q1[1]);
  448. var det = (a1 * b2) - (a2 * b1);
  449. if(!Scalar.eq(det,0,delta))
  450. return [((b2 * c1) - (b1 * c2)) / det, ((a1 * c2) - (a2 * c1)) / det]
  451. else
  452. return [0,0]
  453. }
  454. /**
  455. * Quickly decompose the Polygon into convex sub-polygons.
  456. * @method quickDecomp
  457. * @param {Array} result
  458. * @param {Array} [reflexVertices]
  459. * @param {Array} [steinerPoints]
  460. * @param {Number} [delta]
  461. * @param {Number} [maxlevel]
  462. * @param {Number} [level]
  463. * @return {Array}
  464. */
  465. Polygon.prototype.quickDecomp = function(result,reflexVertices,steinerPoints,delta,maxlevel,level){
  466. maxlevel = maxlevel || 100;
  467. level = level || 0;
  468. delta = delta || 25;
  469. result = typeof(result)!="undefined" ? result : [];
  470. reflexVertices = reflexVertices || [];
  471. steinerPoints = steinerPoints || [];
  472. var upperInt=[0,0], lowerInt=[0,0], p=[0,0]; // Points
  473. var upperDist=0, lowerDist=0, d=0, closestDist=0; // scalars
  474. var upperIndex=0, lowerIndex=0, closestIndex=0; // Integers
  475. var lowerPoly=new Polygon(), upperPoly=new Polygon(); // polygons
  476. var poly = this,
  477. v = this.vertices;
  478. if(v.length < 3) return result;
  479. level++;
  480. if(level > maxlevel){
  481. console.warn("quickDecomp: max level ("+maxlevel+") reached.");
  482. return result;
  483. }
  484. for (var i = 0; i < this.vertices.length; ++i) {
  485. if (poly.isReflex(i)) {
  486. reflexVertices.push(poly.vertices[i]);
  487. upperDist = lowerDist = Number.MAX_VALUE;
  488. for (var j = 0; j < this.vertices.length; ++j) {
  489. if (Point.left(poly.at(i - 1), poly.at(i), poly.at(j))
  490. && Point.rightOn(poly.at(i - 1), poly.at(i), poly.at(j - 1))) { // if line intersects with an edge
  491. p = getIntersectionPoint(poly.at(i - 1), poly.at(i), poly.at(j), poly.at(j - 1)); // find the point of intersection
  492. if (Point.right(poly.at(i + 1), poly.at(i), p)) { // make sure it's inside the poly
  493. d = Point.sqdist(poly.vertices[i], p);
  494. if (d < lowerDist) { // keep only the closest intersection
  495. lowerDist = d;
  496. lowerInt = p;
  497. lowerIndex = j;
  498. }
  499. }
  500. }
  501. if (Point.left(poly.at(i + 1), poly.at(i), poly.at(j + 1))
  502. && Point.rightOn(poly.at(i + 1), poly.at(i), poly.at(j))) {
  503. p = getIntersectionPoint(poly.at(i + 1), poly.at(i), poly.at(j), poly.at(j + 1));
  504. if (Point.left(poly.at(i - 1), poly.at(i), p)) {
  505. d = Point.sqdist(poly.vertices[i], p);
  506. if (d < upperDist) {
  507. upperDist = d;
  508. upperInt = p;
  509. upperIndex = j;
  510. }
  511. }
  512. }
  513. }
  514. // if there are no vertices to connect to, choose a point in the middle
  515. if (lowerIndex == (upperIndex + 1) % this.vertices.length) {
  516. //console.log("Case 1: Vertex("+i+"), lowerIndex("+lowerIndex+"), upperIndex("+upperIndex+"), poly.size("+this.vertices.length+")");
  517. p[0] = (lowerInt[0] + upperInt[0]) / 2;
  518. p[1] = (lowerInt[1] + upperInt[1]) / 2;
  519. steinerPoints.push(p);
  520. if (i < upperIndex) {
  521. //lowerPoly.insert(lowerPoly.end(), poly.begin() + i, poly.begin() + upperIndex + 1);
  522. lowerPoly.append(poly, i, upperIndex+1);
  523. lowerPoly.vertices.push(p);
  524. upperPoly.vertices.push(p);
  525. if (lowerIndex != 0){
  526. //upperPoly.insert(upperPoly.end(), poly.begin() + lowerIndex, poly.end());
  527. upperPoly.append(poly,lowerIndex,poly.vertices.length);
  528. }
  529. //upperPoly.insert(upperPoly.end(), poly.begin(), poly.begin() + i + 1);
  530. upperPoly.append(poly,0,i+1);
  531. } else {
  532. if (i != 0){
  533. //lowerPoly.insert(lowerPoly.end(), poly.begin() + i, poly.end());
  534. lowerPoly.append(poly,i,poly.vertices.length);
  535. }
  536. //lowerPoly.insert(lowerPoly.end(), poly.begin(), poly.begin() + upperIndex + 1);
  537. lowerPoly.append(poly,0,upperIndex+1);
  538. lowerPoly.vertices.push(p);
  539. upperPoly.vertices.push(p);
  540. //upperPoly.insert(upperPoly.end(), poly.begin() + lowerIndex, poly.begin() + i + 1);
  541. upperPoly.append(poly,lowerIndex,i+1);
  542. }
  543. } else {
  544. // connect to the closest point within the triangle
  545. //console.log("Case 2: Vertex("+i+"), closestIndex("+closestIndex+"), poly.size("+this.vertices.length+")\n");
  546. if (lowerIndex > upperIndex) {
  547. upperIndex += this.vertices.length;
  548. }
  549. closestDist = Number.MAX_VALUE;
  550. if(upperIndex < lowerIndex){
  551. return result;
  552. }
  553. for (var j = lowerIndex; j <= upperIndex; ++j) {
  554. if (Point.leftOn(poly.at(i - 1), poly.at(i), poly.at(j))
  555. && Point.rightOn(poly.at(i + 1), poly.at(i), poly.at(j))) {
  556. d = Point.sqdist(poly.at(i), poly.at(j));
  557. if (d < closestDist) {
  558. closestDist = d;
  559. closestIndex = j % this.vertices.length;
  560. }
  561. }
  562. }
  563. if (i < closestIndex) {
  564. lowerPoly.append(poly,i,closestIndex+1);
  565. if (closestIndex != 0){
  566. upperPoly.append(poly,closestIndex,v.length);
  567. }
  568. upperPoly.append(poly,0,i+1);
  569. } else {
  570. if (i != 0){
  571. lowerPoly.append(poly,i,v.length);
  572. }
  573. lowerPoly.append(poly,0,closestIndex+1);
  574. upperPoly.append(poly,closestIndex,i+1);
  575. }
  576. }
  577. // solve smallest poly first
  578. if (lowerPoly.vertices.length < upperPoly.vertices.length) {
  579. lowerPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level);
  580. upperPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level);
  581. } else {
  582. upperPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level);
  583. lowerPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level);
  584. }
  585. return result;
  586. }
  587. }
  588. result.push(this);
  589. return result;
  590. };
  591. /**
  592. * Remove collinear points in the polygon.
  593. * @method removeCollinearPoints
  594. * @param {Number} [precision] The threshold angle to use when determining whether two edges are collinear. Use zero for finest precision.
  595. * @return {Number} The number of points removed
  596. */
  597. Polygon.prototype.removeCollinearPoints = function(precision){
  598. var num = 0;
  599. for(var i=this.vertices.length-1; this.vertices.length>3 && i>=0; --i){
  600. if(Point.collinear(this.at(i-1),this.at(i),this.at(i+1),precision)){
  601. // Remove the middle point
  602. this.vertices.splice(i%this.vertices.length,1);
  603. i--; // Jump one point forward. Otherwise we may get a chain removal
  604. num++;
  605. }
  606. }
  607. return num;
  608. };
  609. },{"./Line":1,"./Point":2,"./Scalar":4}],4:[function(_dereq_,module,exports){
  610. module.exports = Scalar;
  611. /**
  612. * Scalar functions
  613. * @class Scalar
  614. */
  615. function Scalar(){}
  616. /**
  617. * Check if two scalars are equal
  618. * @static
  619. * @method eq
  620. * @param {Number} a
  621. * @param {Number} b
  622. * @param {Number} [precision]
  623. * @return {Boolean}
  624. */
  625. Scalar.eq = function(a,b,precision){
  626. precision = precision || 0;
  627. return Math.abs(a-b) < precision;
  628. };
  629. },{}],5:[function(_dereq_,module,exports){
  630. module.exports = {
  631. Polygon : _dereq_("./Polygon"),
  632. Point : _dereq_("./Point"),
  633. };
  634. },{"./Point":2,"./Polygon":3}],6:[function(_dereq_,module,exports){
  635. module.exports={
  636. "name": "p2",
  637. "version": "0.7.0",
  638. "description": "A JavaScript 2D physics engine.",
  639. "author": "Stefan Hedman <schteppe@gmail.com> (http://steffe.se)",
  640. "keywords": [
  641. "p2.js",
  642. "p2",
  643. "physics",
  644. "engine",
  645. "2d"
  646. ],
  647. "main": "./src/p2.js",
  648. "engines": {
  649. "node": "*"
  650. },
  651. "repository": {
  652. "type": "git",
  653. "url": "https://github.com/schteppe/p2.js.git"
  654. },
  655. "bugs": {
  656. "url": "https://github.com/schteppe/p2.js/issues"
  657. },
  658. "licenses": [
  659. {
  660. "type": "MIT"
  661. }
  662. ],
  663. "devDependencies": {
  664. "grunt": "^0.4.5",
  665. "grunt-contrib-jshint": "^0.11.2",
  666. "grunt-contrib-nodeunit": "^0.4.1",
  667. "grunt-contrib-uglify": "~0.4.0",
  668. "grunt-contrib-watch": "~0.5.0",
  669. "grunt-browserify": "~2.0.1",
  670. "grunt-contrib-concat": "^0.4.0"
  671. },
  672. "dependencies": {
  673. "poly-decomp": "0.1.0"
  674. }
  675. }
  676. },{}],7:[function(_dereq_,module,exports){
  677. var vec2 = _dereq_('../math/vec2')
  678. , Utils = _dereq_('../utils/Utils');
  679. module.exports = AABB;
  680. /**
  681. * Axis aligned bounding box class.
  682. * @class AABB
  683. * @constructor
  684. * @param {Object} [options]
  685. * @param {Array} [options.upperBound]
  686. * @param {Array} [options.lowerBound]
  687. */
  688. function AABB(options){
  689. /**
  690. * The lower bound of the bounding box.
  691. * @property lowerBound
  692. * @type {Array}
  693. */
  694. this.lowerBound = vec2.create();
  695. if(options && options.lowerBound){
  696. vec2.copy(this.lowerBound, options.lowerBound);
  697. }
  698. /**
  699. * The upper bound of the bounding box.
  700. * @property upperBound
  701. * @type {Array}
  702. */
  703. this.upperBound = vec2.create();
  704. if(options && options.upperBound){
  705. vec2.copy(this.upperBound, options.upperBound);
  706. }
  707. }
  708. var tmp = vec2.create();
  709. /**
  710. * Set the AABB bounds from a set of points, transformed by the given position and angle.
  711. * @method setFromPoints
  712. * @param {Array} points An array of vec2's.
  713. * @param {Array} position
  714. * @param {number} angle
  715. * @param {number} skinSize Some margin to be added to the AABB.
  716. */
  717. AABB.prototype.setFromPoints = function(points, position, angle, skinSize){
  718. var l = this.lowerBound,
  719. u = this.upperBound;
  720. if(typeof(angle) !== "number"){
  721. angle = 0;
  722. }
  723. // Set to the first point
  724. if(angle !== 0){
  725. vec2.rotate(l, points[0], angle);
  726. } else {
  727. vec2.copy(l, points[0]);
  728. }
  729. vec2.copy(u, l);
  730. // Compute cosines and sines just once
  731. var cosAngle = Math.cos(angle),
  732. sinAngle = Math.sin(angle);
  733. for(var i = 1; i<points.length; i++){
  734. var p = points[i];
  735. if(angle !== 0){
  736. var x = p[0],
  737. y = p[1];
  738. tmp[0] = cosAngle * x -sinAngle * y;
  739. tmp[1] = sinAngle * x +cosAngle * y;
  740. p = tmp;
  741. }
  742. for(var j=0; j<2; j++){
  743. if(p[j] > u[j]){
  744. u[j] = p[j];
  745. }
  746. if(p[j] < l[j]){
  747. l[j] = p[j];
  748. }
  749. }
  750. }
  751. // Add offset
  752. if(position){
  753. vec2.add(this.lowerBound, this.lowerBound, position);
  754. vec2.add(this.upperBound, this.upperBound, position);
  755. }
  756. if(skinSize){
  757. this.lowerBound[0] -= skinSize;
  758. this.lowerBound[1] -= skinSize;
  759. this.upperBound[0] += skinSize;
  760. this.upperBound[1] += skinSize;
  761. }
  762. };
  763. /**
  764. * Copy bounds from an AABB to this AABB
  765. * @method copy
  766. * @param {AABB} aabb
  767. */
  768. AABB.prototype.copy = function(aabb){
  769. vec2.copy(this.lowerBound, aabb.lowerBound);
  770. vec2.copy(this.upperBound, aabb.upperBound);
  771. };
  772. /**
  773. * Extend this AABB so that it covers the given AABB too.
  774. * @method extend
  775. * @param {AABB} aabb
  776. */
  777. AABB.prototype.extend = function(aabb){
  778. // Loop over x and y
  779. var i = 2;
  780. while(i--){
  781. // Extend lower bound
  782. var l = aabb.lowerBound[i];
  783. if(this.lowerBound[i] > l){
  784. this.lowerBound[i] = l;
  785. }
  786. // Upper
  787. var u = aabb.upperBound[i];
  788. if(this.upperBound[i] < u){
  789. this.upperBound[i] = u;
  790. }
  791. }
  792. };
  793. /**
  794. * Returns true if the given AABB overlaps this AABB.
  795. * @method overlaps
  796. * @param {AABB} aabb
  797. * @return {Boolean}
  798. */
  799. AABB.prototype.overlaps = function(aabb){
  800. var l1 = this.lowerBound,
  801. u1 = this.upperBound,
  802. l2 = aabb.lowerBound,
  803. u2 = aabb.upperBound;
  804. // l2 u2
  805. // |---------|
  806. // |--------|
  807. // l1 u1
  808. return ((l2[0] <= u1[0] && u1[0] <= u2[0]) || (l1[0] <= u2[0] && u2[0] <= u1[0])) &&
  809. ((l2[1] <= u1[1] && u1[1] <= u2[1]) || (l1[1] <= u2[1] && u2[1] <= u1[1]));
  810. };
  811. /**
  812. * @method containsPoint
  813. * @param {Array} point
  814. * @return {boolean}
  815. */
  816. AABB.prototype.containsPoint = function(point){
  817. var l = this.lowerBound,
  818. u = this.upperBound;
  819. return l[0] <= point[0] && point[0] <= u[0] && l[1] <= point[1] && point[1] <= u[1];
  820. };
  821. /**
  822. * Check if the AABB is hit by a ray.
  823. * @method overlapsRay
  824. * @param {Ray} ray
  825. * @return {number} -1 if no hit, a number between 0 and 1 if hit.
  826. */
  827. AABB.prototype.overlapsRay = function(ray){
  828. var t = 0;
  829. // ray.direction is unit direction vector of ray
  830. var dirFracX = 1 / ray.direction[0];
  831. var dirFracY = 1 / ray.direction[1];
  832. // this.lowerBound is the corner of AABB with minimal coordinates - left bottom, rt is maximal corner
  833. var t1 = (this.lowerBound[0] - ray.from[0]) * dirFracX;
  834. var t2 = (this.upperBound[0] - ray.from[0]) * dirFracX;
  835. var t3 = (this.lowerBound[1] - ray.from[1]) * dirFracY;
  836. var t4 = (this.upperBound[1] - ray.from[1]) * dirFracY;
  837. var tmin = Math.max(Math.max(Math.min(t1, t2), Math.min(t3, t4)));
  838. var tmax = Math.min(Math.min(Math.max(t1, t2), Math.max(t3, t4)));
  839. // if tmax < 0, ray (line) is intersecting AABB, but whole AABB is behing us
  840. if (tmax < 0){
  841. //t = tmax;
  842. return -1;
  843. }
  844. // if tmin > tmax, ray doesn't intersect AABB
  845. if (tmin > tmax){
  846. //t = tmax;
  847. return -1;
  848. }
  849. return tmin;
  850. };
  851. },{"../math/vec2":30,"../utils/Utils":57}],8:[function(_dereq_,module,exports){
  852. var vec2 = _dereq_('../math/vec2');
  853. var Body = _dereq_('../objects/Body');
  854. module.exports = Broadphase;
  855. /**
  856. * Base class for broadphase implementations.
  857. * @class Broadphase
  858. * @constructor
  859. */
  860. function Broadphase(type){
  861. this.type = type;
  862. /**
  863. * The resulting overlapping pairs. Will be filled with results during .getCollisionPairs().
  864. * @property result
  865. * @type {Array}
  866. */
  867. this.result = [];
  868. /**
  869. * The world to search for collision pairs in. To change it, use .setWorld()
  870. * @property world
  871. * @type {World}
  872. * @readOnly
  873. */
  874. this.world = null;
  875. /**
  876. * The bounding volume type to use in the broadphase algorithms. Should be set to Broadphase.AABB or Broadphase.BOUNDING_CIRCLE.
  877. * @property {Number} boundingVolumeType
  878. */
  879. this.boundingVolumeType = Broadphase.AABB;
  880. }
  881. /**
  882. * Axis aligned bounding box type.
  883. * @static
  884. * @property {Number} AABB
  885. */
  886. Broadphase.AABB = 1;
  887. /**
  888. * Bounding circle type.
  889. * @static
  890. * @property {Number} BOUNDING_CIRCLE
  891. */
  892. Broadphase.BOUNDING_CIRCLE = 2;
  893. /**
  894. * Set the world that we are searching for collision pairs in.
  895. * @method setWorld
  896. * @param {World} world
  897. */
  898. Broadphase.prototype.setWorld = function(world){
  899. this.world = world;
  900. };
  901. /**
  902. * Get all potential intersecting body pairs.
  903. * @method getCollisionPairs
  904. * @param {World} world The world to search in.
  905. * @return {Array} An array of the bodies, ordered in pairs. Example: A result of [a,b,c,d] means that the potential pairs are: (a,b), (c,d).
  906. */
  907. Broadphase.prototype.getCollisionPairs = function(world){};
  908. var dist = vec2.create();
  909. /**
  910. * Check whether the bounding radius of two bodies overlap.
  911. * @method boundingRadiusCheck
  912. * @param {Body} bodyA
  913. * @param {Body} bodyB
  914. * @return {Boolean}
  915. */
  916. Broadphase.boundingRadiusCheck = function(bodyA, bodyB){
  917. vec2.sub(dist, bodyA.position, bodyB.position);
  918. var d2 = vec2.squaredLength(dist),
  919. r = bodyA.boundingRadius + bodyB.boundingRadius;
  920. return d2 <= r*r;
  921. };
  922. /**
  923. * Check whether the bounding radius of two bodies overlap.
  924. * @method boundingRadiusCheck
  925. * @param {Body} bodyA
  926. * @param {Body} bodyB
  927. * @return {Boolean}
  928. */
  929. Broadphase.aabbCheck = function(bodyA, bodyB){
  930. return bodyA.getAABB().overlaps(bodyB.getAABB());
  931. };
  932. /**
  933. * Check whether the bounding radius of two bodies overlap.
  934. * @method boundingRadiusCheck
  935. * @param {Body} bodyA
  936. * @param {Body} bodyB
  937. * @return {Boolean}
  938. */
  939. Broadphase.prototype.boundingVolumeCheck = function(bodyA, bodyB){
  940. var result;
  941. switch(this.boundingVolumeType){
  942. case Broadphase.BOUNDING_CIRCLE:
  943. result = Broadphase.boundingRadiusCheck(bodyA,bodyB);
  944. break;
  945. case Broadphase.AABB:
  946. result = Broadphase.aabbCheck(bodyA,bodyB);
  947. break;
  948. default:
  949. throw new Error('Bounding volume type not recognized: '+this.boundingVolumeType);
  950. }
  951. return result;
  952. };
  953. /**
  954. * Check whether two bodies are allowed to collide at all.
  955. * @method canCollide
  956. * @param {Body} bodyA
  957. * @param {Body} bodyB
  958. * @return {Boolean}
  959. */
  960. Broadphase.canCollide = function(bodyA, bodyB){
  961. var KINEMATIC = Body.KINEMATIC;
  962. var STATIC = Body.STATIC;
  963. // Cannot collide static bodies
  964. if(bodyA.type === STATIC && bodyB.type === STATIC){
  965. return false;
  966. }
  967. // Cannot collide static vs kinematic bodies
  968. if( (bodyA.type === KINEMATIC && bodyB.type === STATIC) ||
  969. (bodyA.type === STATIC && bodyB.type === KINEMATIC)){
  970. return false;
  971. }
  972. // Cannot collide kinematic vs kinematic
  973. if(bodyA.type === KINEMATIC && bodyB.type === KINEMATIC){
  974. return false;
  975. }
  976. // Cannot collide both sleeping bodies
  977. if(bodyA.sleepState === Body.SLEEPING && bodyB.sleepState === Body.SLEEPING){
  978. return false;
  979. }
  980. // Cannot collide if one is static and the other is sleeping
  981. if( (bodyA.sleepState === Body.SLEEPING && bodyB.type === STATIC) ||
  982. (bodyB.sleepState === Body.SLEEPING && bodyA.type === STATIC)){
  983. return false;
  984. }
  985. return true;
  986. };
  987. Broadphase.NAIVE = 1;
  988. Broadphase.SAP = 2;
  989. },{"../math/vec2":30,"../objects/Body":31}],9:[function(_dereq_,module,exports){
  990. var Circle = _dereq_('../shapes/Circle'),
  991. Plane = _dereq_('../shapes/Plane'),
  992. Shape = _dereq_('../shapes/Shape'),
  993. Particle = _dereq_('../shapes/Particle'),
  994. Broadphase = _dereq_('../collision/Broadphase'),
  995. vec2 = _dereq_('../math/vec2');
  996. module.exports = NaiveBroadphase;
  997. /**
  998. * Naive broadphase implementation. Does N^2 tests.
  999. *
  1000. * @class NaiveBroadphase
  1001. * @constructor
  1002. * @extends Broadphase
  1003. */
  1004. function NaiveBroadphase(){
  1005. Broadphase.call(this, Broadphase.NAIVE);
  1006. }
  1007. NaiveBroadphase.prototype = new Broadphase();
  1008. NaiveBroadphase.prototype.constructor = NaiveBroadphase;
  1009. /**
  1010. * Get the colliding pairs
  1011. * @method getCollisionPairs
  1012. * @param {World} world
  1013. * @return {Array}
  1014. */
  1015. NaiveBroadphase.prototype.getCollisionPairs = function(world){
  1016. var bodies = world.bodies,
  1017. result = this.result;
  1018. result.length = 0;
  1019. for(var i=0, Ncolliding=bodies.length; i!==Ncolliding; i++){
  1020. var bi = bodies[i];
  1021. for(var j=0; j<i; j++){
  1022. var bj = bodies[j];
  1023. if(Broadphase.canCollide(bi,bj) && this.boundingVolumeCheck(bi,bj)){
  1024. result.push(bi,bj);
  1025. }
  1026. }
  1027. }
  1028. return result;
  1029. };
  1030. /**
  1031. * Returns all the bodies within an AABB.
  1032. * @method aabbQuery
  1033. * @param {World} world
  1034. * @param {AABB} aabb
  1035. * @param {array} result An array to store resulting bodies in.
  1036. * @return {array}
  1037. */
  1038. NaiveBroadphase.prototype.aabbQuery = function(world, aabb, result){
  1039. result = result || [];
  1040. var bodies = world.bodies;
  1041. for(var i = 0; i < bodies.length; i++){
  1042. var b = bodies[i];
  1043. if(b.aabbNeedsUpdate){
  1044. b.updateAABB();
  1045. }
  1046. if(b.aabb.overlaps(aabb)){
  1047. result.push(b);
  1048. }
  1049. }
  1050. return result;
  1051. };
  1052. },{"../collision/Broadphase":8,"../math/vec2":30,"../shapes/Circle":39,"../shapes/Particle":43,"../shapes/Plane":44,"../shapes/Shape":45}],10:[function(_dereq_,module,exports){
  1053. var vec2 = _dereq_('../math/vec2')
  1054. , sub = vec2.sub
  1055. , add = vec2.add
  1056. , dot = vec2.dot
  1057. , Utils = _dereq_('../utils/Utils')
  1058. , ContactEquationPool = _dereq_('../utils/ContactEquationPool')
  1059. , FrictionEquationPool = _dereq_('../utils/FrictionEquationPool')
  1060. , TupleDictionary = _dereq_('../utils/TupleDictionary')
  1061. , Equation = _dereq_('../equations/Equation')
  1062. , ContactEquation = _dereq_('../equations/ContactEquation')
  1063. , FrictionEquation = _dereq_('../equations/FrictionEquation')
  1064. , Circle = _dereq_('../shapes/Circle')
  1065. , Convex = _dereq_('../shapes/Convex')
  1066. , Shape = _dereq_('../shapes/Shape')
  1067. , Body = _dereq_('../objects/Body')
  1068. , Box = _dereq_('../shapes/Box');
  1069. module.exports = Narrowphase;
  1070. // Temp things
  1071. var yAxis = vec2.fromValues(0,1);
  1072. var tmp1 = vec2.fromValues(0,0)
  1073. , tmp2 = vec2.fromValues(0,0)
  1074. , tmp3 = vec2.fromValues(0,0)
  1075. , tmp4 = vec2.fromValues(0,0)
  1076. , tmp5 = vec2.fromValues(0,0)
  1077. , tmp6 = vec2.fromValues(0,0)
  1078. , tmp7 = vec2.fromValues(0,0)
  1079. , tmp8 = vec2.fromValues(0,0)
  1080. , tmp9 = vec2.fromValues(0,0)
  1081. , tmp10 = vec2.fromValues(0,0)
  1082. , tmp11 = vec2.fromValues(0,0)
  1083. , tmp12 = vec2.fromValues(0,0)
  1084. , tmp13 = vec2.fromValues(0,0)
  1085. , tmp14 = vec2.fromValues(0,0)
  1086. , tmp15 = vec2.fromValues(0,0)
  1087. , tmp16 = vec2.fromValues(0,0)
  1088. , tmp17 = vec2.fromValues(0,0)
  1089. , tmp18 = vec2.fromValues(0,0)
  1090. , tmpArray = [];
  1091. /**
  1092. * Narrowphase. Creates contacts and friction given shapes and transforms.
  1093. * @class Narrowphase
  1094. * @constructor
  1095. */
  1096. function Narrowphase(){
  1097. /**
  1098. * @property contactEquations
  1099. * @type {Array}
  1100. */
  1101. this.contactEquations = [];
  1102. /**
  1103. * @property frictionEquations
  1104. * @type {Array}
  1105. */
  1106. this.frictionEquations = [];
  1107. /**
  1108. * Whether to make friction equations in the upcoming contacts.
  1109. * @property enableFriction
  1110. * @type {Boolean}
  1111. */
  1112. this.enableFriction = true;
  1113. /**
  1114. * Whether to make equations enabled in upcoming contacts.
  1115. * @property enabledEquations
  1116. * @type {Boolean}
  1117. */
  1118. this.enabledEquations = true;
  1119. /**
  1120. * The friction slip force to use when creating friction equations.
  1121. * @property slipForce
  1122. * @type {Number}
  1123. */
  1124. this.slipForce = 10.0;
  1125. /**
  1126. * The friction value to use in the upcoming friction equations.
  1127. * @property frictionCoefficient
  1128. * @type {Number}
  1129. */
  1130. this.frictionCoefficient = 0.3;
  1131. /**
  1132. * Will be the .relativeVelocity in each produced FrictionEquation.
  1133. * @property {Number} surfaceVelocity
  1134. */
  1135. this.surfaceVelocity = 0;
  1136. /**
  1137. * Keeps track of the allocated ContactEquations.
  1138. * @property {ContactEquationPool} contactEquationPool
  1139. *
  1140. * @example
  1141. *
  1142. * // Allocate a few equations before starting the simulation.
  1143. * // This way, no contact objects need to be created on the fly in the game loop.
  1144. * world.narrowphase.contactEquationPool.resize(1024);
  1145. * world.narrowphase.frictionEquationPool.resize(1024);
  1146. */
  1147. this.contactEquationPool = new ContactEquationPool({ size: 32 });
  1148. /**
  1149. * Keeps track of the allocated ContactEquations.
  1150. * @property {FrictionEquationPool} frictionEquationPool
  1151. */
  1152. this.frictionEquationPool = new FrictionEquationPool({ size: 64 });
  1153. /**
  1154. * The restitution value to use in the next contact equations.
  1155. * @property restitution
  1156. * @type {Number}
  1157. */
  1158. this.restitution = 0;
  1159. /**
  1160. * The stiffness value to use in the next contact equations.
  1161. * @property {Number} stiffness
  1162. */
  1163. this.stiffness = Equation.DEFAULT_STIFFNESS;
  1164. /**
  1165. * The stiffness value to use in the next contact equations.
  1166. * @property {Number} stiffness
  1167. */
  1168. this.relaxation = Equation.DEFAULT_RELAXATION;
  1169. /**
  1170. * The stiffness value to use in the next friction equations.
  1171. * @property frictionStiffness
  1172. * @type {Number}
  1173. */
  1174. this.frictionStiffness = Equation.DEFAULT_STIFFNESS;
  1175. /**
  1176. * The relaxation value to use in the next friction equations.
  1177. * @property frictionRelaxation
  1178. * @type {Number}
  1179. */
  1180. this.frictionRelaxation = Equation.DEFAULT_RELAXATION;
  1181. /**
  1182. * Enable reduction of friction equations. If disabled, a box on a plane will generate 2 contact equations and 2 friction equations. If enabled, there will be only one friction equation. Same kind of simplifications are made for all collision types.
  1183. * @property enableFrictionReduction
  1184. * @type {Boolean}
  1185. * @deprecated This flag will be removed when the feature is stable enough.
  1186. * @default true
  1187. */
  1188. this.enableFrictionReduction = true;
  1189. /**
  1190. * Keeps track of the colliding bodies last step.
  1191. * @private
  1192. * @property collidingBodiesLastStep
  1193. * @type {TupleDictionary}
  1194. */
  1195. this.collidingBodiesLastStep = new TupleDictionary();
  1196. /**
  1197. * Contact skin size value to use in the next contact equations.
  1198. * @property {Number} contactSkinSize
  1199. * @default 0.01
  1200. */
  1201. this.contactSkinSize = 0.01;
  1202. }
  1203. var bodiesOverlap_shapePositionA = vec2.create();
  1204. var bodiesOverlap_shapePositionB = vec2.create();
  1205. /**
  1206. * @method bodiesOverlap
  1207. * @param {Body} bodyA
  1208. * @param {Body} bodyB
  1209. * @return {Boolean}
  1210. * @todo shape world transforms are wrong
  1211. */
  1212. Narrowphase.prototype.bodiesOverlap = function(bodyA, bodyB){
  1213. var shapePositionA = bodiesOverlap_shapePositionA;
  1214. var shapePositionB = bodiesOverlap_shapePositionB;
  1215. // Loop over all shapes of bodyA
  1216. for(var k=0, Nshapesi=bodyA.shapes.length; k!==Nshapesi; k++){
  1217. var shapeA = bodyA.shapes[k];
  1218. bodyA.toWorldFrame(shapePositionA, shapeA.position);
  1219. // All shapes of body j
  1220. for(var l=0, Nshapesj=bodyB.shapes.length; l!==Nshapesj; l++){
  1221. var shapeB = bodyB.shapes[l];
  1222. bodyB.toWorldFrame(shapePositionB, shapeB.position);
  1223. if(this[shapeA.type | shapeB.type](
  1224. bodyA,
  1225. shapeA,
  1226. shapePositionA,
  1227. shapeA.angle + bodyA.angle,
  1228. bodyB,
  1229. shapeB,
  1230. shapePositionB,
  1231. shapeB.angle + bodyB.angle,
  1232. true
  1233. )){
  1234. return true;
  1235. }
  1236. }
  1237. }
  1238. return false;
  1239. };
  1240. /**
  1241. * Check if the bodies were in contact since the last reset().
  1242. * @method collidedLastStep
  1243. * @param {Body} bodyA
  1244. * @param {Body} bodyB
  1245. * @return {Boolean}
  1246. */
  1247. Narrowphase.prototype.collidedLastStep = function(bodyA, bodyB){
  1248. var id1 = bodyA.id|0,
  1249. id2 = bodyB.id|0;
  1250. return !!this.collidingBodiesLastStep.get(id1, id2);
  1251. };
  1252. /**
  1253. * Throws away the old equations and gets ready to create new
  1254. * @method reset
  1255. */
  1256. Narrowphase.prototype.reset = function(){
  1257. this.collidingBodiesLastStep.reset();
  1258. var eqs = this.contactEquations;
  1259. var l = eqs.length;
  1260. while(l--){
  1261. var eq = eqs[l],
  1262. id1 = eq.bodyA.id,
  1263. id2 = eq.bodyB.id;
  1264. this.collidingBodiesLastStep.set(id1, id2, true);
  1265. }
  1266. var ce = this.contactEquations,
  1267. fe = this.frictionEquations;
  1268. for(var i=0; i<ce.length; i++){
  1269. this.contactEquationPool.release(ce[i]);
  1270. }
  1271. for(var i=0; i<fe.length; i++){
  1272. this.frictionEquationPool.release(fe[i]);
  1273. }
  1274. // Reset
  1275. this.contactEquations.length = this.frictionEquations.length = 0;
  1276. };
  1277. /**
  1278. * Creates a ContactEquation, either by reusing an existing object or creating a new one.
  1279. * @method createContactEquation
  1280. * @param {Body} bodyA
  1281. * @param {Body} bodyB
  1282. * @return {ContactEquation}
  1283. */
  1284. Narrowphase.prototype.createContactEquation = function(bodyA, bodyB, shapeA, shapeB){
  1285. var c = this.contactEquationPool.get();
  1286. c.bodyA = bodyA;
  1287. c.bodyB = bodyB;
  1288. c.shapeA = shapeA;
  1289. c.shapeB = shapeB;
  1290. c.restitution = this.restitution;
  1291. c.firstImpact = !this.collidedLastStep(bodyA,bodyB);
  1292. c.stiffness = this.stiffness;
  1293. c.relaxation = this.relaxation;
  1294. c.needsUpdate = true;
  1295. c.enabled = this.enabledEquations;
  1296. c.offset = this.contactSkinSize;
  1297. return c;
  1298. };
  1299. /**
  1300. * Creates a FrictionEquation, either by reusing an existing object or creating a new one.
  1301. * @method createFrictionEquation
  1302. * @param {Body} bodyA
  1303. * @param {Body} bodyB
  1304. * @return {FrictionEquation}
  1305. */
  1306. Narrowphase.prototype.createFrictionEquation = function(bodyA, bodyB, shapeA, shapeB){
  1307. var c = this.frictionEquationPool.get();
  1308. c.bodyA = bodyA;
  1309. c.bodyB = bodyB;
  1310. c.shapeA = shapeA;
  1311. c.shapeB = shapeB;
  1312. c.setSlipForce(this.slipForce);
  1313. c.frictionCoefficient = this.frictionCoefficient;
  1314. c.relativeVelocity = this.surfaceVelocity;
  1315. c.enabled = this.enabledEquations;
  1316. c.needsUpdate = true;
  1317. c.stiffness = this.frictionStiffness;
  1318. c.relaxation = this.frictionRelaxation;
  1319. c.contactEquations.length = 0;
  1320. return c;
  1321. };
  1322. /**
  1323. * Creates a FrictionEquation given the data in the ContactEquation. Uses same offset vectors ri and rj, but the tangent vector will be constructed from the collision normal.
  1324. * @method createFrictionFromContact
  1325. * @param {ContactEquation} contactEquation
  1326. * @return {FrictionEquation}
  1327. */
  1328. Narrowphase.prototype.createFrictionFromContact = function(c){
  1329. var eq = this.createFrictionEquation(c.bodyA, c.bodyB, c.shapeA, c.shapeB);
  1330. vec2.copy(eq.contactPointA, c.contactPointA);
  1331. vec2.copy(eq.contactPointB, c.contactPointB);
  1332. vec2.rotate90cw(eq.t, c.normalA);
  1333. eq.contactEquations.push(c);
  1334. return eq;
  1335. };
  1336. // Take the average N latest contact point on the plane.
  1337. Narrowphase.prototype.createFrictionFromAverage = function(numContacts){
  1338. var c = this.contactEquations[this.contactEquations.length - 1];
  1339. var eq = this.createFrictionEquation(c.bodyA, c.bodyB, c.shapeA, c.shapeB);
  1340. var bodyA = c.bodyA;
  1341. var bodyB = c.bodyB;
  1342. vec2.set(eq.contactPointA, 0, 0);
  1343. vec2.set(eq.contactPointB, 0, 0);
  1344. vec2.set(eq.t, 0, 0);
  1345. for(var i=0; i!==numContacts; i++){
  1346. c = this.contactEquations[this.contactEquations.length - 1 - i];
  1347. if(c.bodyA === bodyA){
  1348. vec2.add(eq.t, eq.t, c.normalA);
  1349. vec2.add(eq.contactPointA, eq.contactPointA, c.contactPointA);
  1350. vec2.add(eq.contactPointB, eq.contactPointB, c.contactPointB);
  1351. } else {
  1352. vec2.sub(eq.t, eq.t, c.normalA);
  1353. vec2.add(eq.contactPointA, eq.contactPointA, c.contactPointB);
  1354. vec2.add(eq.contactPointB, eq.contactPointB, c.contactPointA);
  1355. }
  1356. eq.contactEquations.push(c);
  1357. }
  1358. var invNumContacts = 1/numContacts;
  1359. vec2.scale(eq.contactPointA, eq.contactPointA, invNumContacts);
  1360. vec2.scale(eq.contactPointB, eq.contactPointB, invNumContacts);
  1361. vec2.normalize(eq.t, eq.t);
  1362. vec2.rotate90cw(eq.t, eq.t);
  1363. return eq;
  1364. };
  1365. /**
  1366. * Convex/line narrowphase
  1367. * @method convexLine
  1368. * @param {Body} convexBody
  1369. * @param {Convex} convexShape
  1370. * @param {Array} convexOffset
  1371. * @param {Number} convexAngle
  1372. * @param {Body} lineBody
  1373. * @param {Line} lineShape
  1374. * @param {Array} lineOffset
  1375. * @param {Number} lineAngle
  1376. * @param {boolean} justTest
  1377. * @todo Implement me!
  1378. */
  1379. Narrowphase.prototype[Shape.LINE | Shape.CONVEX] =
  1380. Narrowphase.prototype.convexLine = function(
  1381. convexBody,
  1382. convexShape,
  1383. convexOffset,
  1384. convexAngle,
  1385. lineBody,
  1386. lineShape,
  1387. lineOffset,
  1388. lineAngle,
  1389. justTest
  1390. ){
  1391. // TODO
  1392. if(justTest){
  1393. return false;
  1394. } else {
  1395. return 0;
  1396. }
  1397. };
  1398. /**
  1399. * Line/box narrowphase
  1400. * @method lineBox
  1401. * @param {Body} lineBody
  1402. * @param {Line} lineShape
  1403. * @param {Array} lineOffset
  1404. * @param {Number} lineAngle
  1405. * @param {Body} boxBody
  1406. * @param {Box} boxShape
  1407. * @param {Array} boxOffset
  1408. * @param {Number} boxAngle
  1409. * @param {Boolean} justTest
  1410. * @todo Implement me!
  1411. */
  1412. Narrowphase.prototype[Shape.LINE | Shape.BOX] =
  1413. Narrowphase.prototype.lineBox = function(
  1414. lineBody,
  1415. lineShape,
  1416. lineOffset,
  1417. lineAngle,
  1418. boxBody,
  1419. boxShape,
  1420. boxOffset,
  1421. boxAngle,
  1422. justTest
  1423. ){
  1424. // TODO
  1425. if(justTest){
  1426. return false;
  1427. } else {
  1428. return 0;
  1429. }
  1430. };
  1431. function setConvexToCapsuleShapeMiddle(convexShape, capsuleShape){
  1432. vec2.set(convexShape.vertices[0], -capsuleShape.length * 0.5, -capsuleShape.radius);
  1433. vec2.set(convexShape.vertices[1], capsuleShape.length * 0.5, -capsuleShape.radius);
  1434. vec2.set(convexShape.vertices[2], capsuleShape.length * 0.5, capsuleShape.radius);
  1435. vec2.set(convexShape.vertices[3], -capsuleShape.length * 0.5, capsuleShape.radius);
  1436. }
  1437. var convexCapsule_tempRect = new Box({ width: 1, height: 1 }),
  1438. convexCapsule_tempVec = vec2.create();
  1439. /**
  1440. * Convex/capsule narrowphase
  1441. * @method convexCapsule
  1442. * @param {Body} convexBody
  1443. * @param {Convex} convexShape
  1444. * @param {Array} convexPosition
  1445. * @param {Number} convexAngle
  1446. * @param {Body} capsuleBody
  1447. * @param {Capsule} capsuleShape
  1448. * @param {Array} capsulePosition
  1449. * @param {Number} capsuleAngle
  1450. */
  1451. Narrowphase.prototype[Shape.CAPSULE | Shape.CONVEX] =
  1452. Narrowphase.prototype[Shape.CAPSULE | Shape.BOX] =
  1453. Narrowphase.prototype.convexCapsule = function(
  1454. convexBody,
  1455. convexShape,
  1456. convexPosition,
  1457. convexAngle,
  1458. capsuleBody,
  1459. capsuleShape,
  1460. capsulePosition,
  1461. capsuleAngle,
  1462. justTest
  1463. ){
  1464. // Check the circles
  1465. // Add offsets!
  1466. var circlePos = convexCapsule_tempVec;
  1467. vec2.set(circlePos, capsuleShape.length/2,0);
  1468. vec2.rotate(circlePos,circlePos,capsuleAngle);
  1469. vec2.add(circlePos,circlePos,capsulePosition);
  1470. var result1 = this.circleConvex(capsuleBody,capsuleShape,circlePos,capsuleAngle, convexBody,convexShape,convexPosition,convexAngle, justTest, capsuleShape.radius);
  1471. vec2.set(circlePos,-capsuleShape.length/2, 0);
  1472. vec2.rotate(circlePos,circlePos,capsuleAngle);
  1473. vec2.add(circlePos,circlePos,capsulePosition);
  1474. var result2 = this.circleConvex(capsuleBody,capsuleShape,circlePos,capsuleAngle, convexBody,convexShape,convexPosition,convexAngle, justTest, capsuleShape.radius);
  1475. if(justTest && (result1 || result2)){
  1476. return true;
  1477. }
  1478. // Check center rect
  1479. var r = convexCapsule_tempRect;
  1480. setConvexToCapsuleShapeMiddle(r,capsuleShape);
  1481. var result = this.convexConvex(convexBody,convexShape,convexPosition,convexAngle, capsuleBody,r,capsulePosition,capsuleAngle, justTest);
  1482. return result + result1 + result2;
  1483. };
  1484. /**
  1485. * Capsule/line narrowphase
  1486. * @method lineCapsule
  1487. * @param {Body} lineBody
  1488. * @param {Line} lineShape
  1489. * @param {Array} linePosition
  1490. * @param {Number} lineAngle
  1491. * @param {Body} capsuleBody
  1492. * @param {Capsule} capsuleShape
  1493. * @param {Array} capsulePosition
  1494. * @param {Number} capsuleAngle
  1495. * @todo Implement me!
  1496. */
  1497. Narrowphase.prototype[Shape.CAPSULE | Shape.LINE] =
  1498. Narrowphase.prototype.lineCapsule = function(
  1499. lineBody,
  1500. lineShape,
  1501. linePosition,
  1502. lineAngle,
  1503. capsuleBody,
  1504. capsuleShape,
  1505. capsulePosition,
  1506. capsuleAngle,
  1507. justTest
  1508. ){
  1509. // TODO
  1510. if(justTest){
  1511. return false;
  1512. } else {
  1513. return 0;
  1514. }
  1515. };
  1516. var capsuleCapsule_tempVec1 = vec2.create();
  1517. var capsuleCapsule_tempVec2 = vec2.create();
  1518. var capsuleCapsule_tempRect1 = new Box({ width: 1, height: 1 });
  1519. /**
  1520. * Capsule/capsule narrowphase
  1521. * @method capsuleCapsule
  1522. * @param {Body} bi
  1523. * @param {Capsule} si
  1524. * @param {Array} xi
  1525. * @param {Number} ai
  1526. * @param {Body} bj
  1527. * @param {Capsule} sj
  1528. * @param {Array} xj
  1529. * @param {Number} aj
  1530. */
  1531. Narrowphase.prototype[Shape.CAPSULE | Shape.CAPSULE] =
  1532. Narrowphase.prototype.capsuleCapsule = function(bi,si,xi,ai, bj,sj,xj,aj, justTest){
  1533. var enableFrictionBefore;
  1534. // Check the circles
  1535. // Add offsets!
  1536. var circlePosi = capsuleCapsule_tempVec1,
  1537. circlePosj = capsuleCapsule_tempVec2;
  1538. var numContacts = 0;
  1539. // Need 4 circle checks, between all
  1540. for(var i=0; i<2; i++){
  1541. vec2.set(circlePosi,(i===0?-1:1)*si.length/2,0);
  1542. vec2.rotate(circlePosi,circlePosi,ai);
  1543. vec2.add(circlePosi,circlePosi,xi);
  1544. for(var j=0; j<2; j++){
  1545. vec2.set(circlePosj,(j===0?-1:1)*sj.length/2, 0);
  1546. vec2.rotate(circlePosj,circlePosj,aj);
  1547. vec2.add(circlePosj,circlePosj,xj);
  1548. // Temporarily turn off friction
  1549. if(this.enableFrictionReduction){
  1550. enableFrictionBefore = this.enableFriction;
  1551. this.enableFriction = false;
  1552. }
  1553. var result = this.circleCircle(bi,si,circlePosi,ai, bj,sj,circlePosj,aj, justTest, si.radius, sj.radius);
  1554. if(this.enableFrictionReduction){
  1555. this.enableFriction = enableFrictionBefore;
  1556. }
  1557. if(justTest && result){
  1558. return true;
  1559. }
  1560. numContacts += result;
  1561. }
  1562. }
  1563. if(this.enableFrictionReduction){
  1564. // Temporarily turn off friction
  1565. enableFrictionBefore = this.enableFriction;
  1566. this.enableFriction = false;
  1567. }
  1568. // Check circles against the center boxs
  1569. var rect = capsuleCapsule_tempRect1;
  1570. setConvexToCapsuleShapeMiddle(rect,si);
  1571. var result1 = this.convexCapsule(bi,rect,xi,ai, bj,sj,xj,aj, justTest);
  1572. if(this.enableFrictionReduction){
  1573. this.enableFriction = enableFrictionBefore;
  1574. }
  1575. if(justTest && result1){
  1576. return true;
  1577. }
  1578. numContacts += result1;
  1579. if(this.enableFrictionReduction){
  1580. // Temporarily turn off friction
  1581. var enableFrictionBefore = this.enableFriction;
  1582. this.enableFriction = false;
  1583. }
  1584. setConvexToCapsuleShapeMiddle(rect,sj);
  1585. var result2 = this.convexCapsule(bj,rect,xj,aj, bi,si,xi,ai, justTest);
  1586. if(this.enableFrictionReduction){
  1587. this.enableFriction = enableFrictionBefore;
  1588. }
  1589. if(justTest && result2){
  1590. return true;
  1591. }
  1592. numContacts += result2;
  1593. if(this.enableFrictionReduction){
  1594. if(numContacts && this.enableFriction){
  1595. this.frictionEquations.push(this.createFrictionFromAverage(numContacts));
  1596. }
  1597. }
  1598. return numContacts;
  1599. };
  1600. /**
  1601. * Line/line narrowphase
  1602. * @method lineLine
  1603. * @param {Body} bodyA
  1604. * @param {Line} shapeA
  1605. * @param {Array} positionA
  1606. * @param {Number} angleA
  1607. * @param {Body} bodyB
  1608. * @param {Line} shapeB
  1609. * @param {Array} positionB
  1610. * @param {Number} angleB
  1611. * @todo Implement me!
  1612. */
  1613. Narrowphase.prototype[Shape.LINE | Shape.LINE] =
  1614. Narrowphase.prototype.lineLine = function(
  1615. bodyA,
  1616. shapeA,
  1617. positionA,
  1618. angleA,
  1619. bodyB,
  1620. shapeB,
  1621. positionB,
  1622. angleB,
  1623. justTest
  1624. ){
  1625. // TODO
  1626. if(justTest){
  1627. return false;
  1628. } else {
  1629. return 0;
  1630. }
  1631. };
  1632. /**
  1633. * Plane/line Narrowphase
  1634. * @method planeLine
  1635. * @param {Body} planeBody
  1636. * @param {Plane} planeShape
  1637. * @param {Array} planeOffset
  1638. * @param {Number} planeAngle
  1639. * @param {Body} lineBody
  1640. * @param {Line} lineShape
  1641. * @param {Array} lineOffset
  1642. * @param {Number} lineAngle
  1643. */
  1644. Narrowphase.prototype[Shape.PLANE | Shape.LINE] =
  1645. Narrowphase.prototype.planeLine = function(planeBody, planeShape, planeOffset, planeAngle,
  1646. lineBody, lineShape, lineOffset, lineAngle, justTest){
  1647. var worldVertex0 = tmp1,
  1648. worldVertex1 = tmp2,
  1649. worldVertex01 = tmp3,
  1650. worldVertex11 = tmp4,
  1651. worldEdge = tmp5,
  1652. worldEdgeUnit = tmp6,
  1653. dist = tmp7,
  1654. worldNormal = tmp8,
  1655. worldTangent = tmp9,
  1656. verts = tmpArray,
  1657. numContacts = 0;
  1658. // Get start and end points
  1659. vec2.set(worldVertex0, -lineShape.length/2, 0);
  1660. vec2.set(worldVertex1, lineShape.length/2, 0);
  1661. // Not sure why we have to use worldVertex*1 here, but it won't work otherwise. Tired.
  1662. vec2.rotate(worldVertex01, worldVertex0, lineAngle);
  1663. vec2.rotate(worldVertex11, worldVertex1, lineAngle);
  1664. add(worldVertex01, worldVertex01, lineOffset);
  1665. add(worldVertex11, worldVertex11, lineOffset);
  1666. vec2.copy(worldVertex0,worldVertex01);
  1667. vec2.copy(worldVertex1,worldVertex11);
  1668. // Get vector along the line
  1669. sub(worldEdge, worldVertex1, worldVertex0);
  1670. vec2.normalize(worldEdgeUnit, worldEdge);
  1671. // Get tangent to the edge.
  1672. vec2.rotate90cw(worldTangent, worldEdgeUnit);
  1673. vec2.rotate(worldNormal, yAxis, planeAngle);
  1674. // Check line ends
  1675. verts[0] = worldVertex0;
  1676. verts[1] = worldVertex1;
  1677. for(var i=0; i<verts.length; i++){
  1678. var v = verts[i];
  1679. sub(dist, v, planeOffset);
  1680. var d = dot(dist,worldNormal);
  1681. if(d < 0){
  1682. if(justTest){
  1683. return true;
  1684. }
  1685. var c = this.createContactEquation(planeBody,lineBody,planeShape,lineShape);
  1686. numContacts++;
  1687. vec2.copy(c.normalA, worldNormal);
  1688. vec2.normalize(c.normalA,c.normalA);
  1689. // distance vector along plane normal
  1690. vec2.scale(dist, worldNormal, d);
  1691. // Vector from plane center to contact
  1692. sub(c.contactPointA, v, dist);
  1693. sub(c.contactPointA, c.contactPointA, planeBody.position);
  1694. // From line center to contact
  1695. sub(c.contactPointB, v, lineOffset);
  1696. add(c.contactPointB, c.contactPointB, lineOffset);
  1697. sub(c.contactPointB, c.contactPointB, lineBody.position);
  1698. this.contactEquations.push(c);
  1699. if(!this.enableFrictionReduction){
  1700. if(this.enableFriction){
  1701. this.frictionEquations.push(this.createFrictionFromContact(c));
  1702. }
  1703. }
  1704. }
  1705. }
  1706. if(justTest){
  1707. return false;
  1708. }
  1709. if(!this.enableFrictionReduction){
  1710. if(numContacts && this.enableFriction){
  1711. this.frictionEquations.push(this.createFrictionFromAverage(numContacts));
  1712. }
  1713. }
  1714. return numContacts;
  1715. };
  1716. Narrowphase.prototype[Shape.PARTICLE | Shape.CAPSULE] =
  1717. Narrowphase.prototype.particleCapsule = function(
  1718. particleBody,
  1719. particleShape,
  1720. particlePosition,
  1721. particleAngle,
  1722. capsuleBody,
  1723. capsuleShape,
  1724. capsulePosition,
  1725. capsuleAngle,
  1726. justTest
  1727. ){
  1728. return this.circleLine(particleBody,particleShape,particlePosition,particleAngle, capsuleBody,capsuleShape,capsulePosition,capsuleAngle, justTest, capsuleShape.radius, 0);
  1729. };
  1730. /**
  1731. * Circle/line Narrowphase
  1732. * @method circleLine
  1733. * @param {Body} circleBody
  1734. * @param {Circle} circleShape
  1735. * @param {Array} circleOffset
  1736. * @param {Number} circleAngle
  1737. * @param {Body} lineBody
  1738. * @param {Line} lineShape
  1739. * @param {Array} lineOffset
  1740. * @param {Number} lineAngle
  1741. * @param {Boolean} justTest If set to true, this function will return the result (intersection or not) without adding equations.
  1742. * @param {Number} lineRadius Radius to add to the line. Can be used to test Capsules.
  1743. * @param {Number} circleRadius If set, this value overrides the circle shape radius.
  1744. */
  1745. Narrowphase.prototype[Shape.CIRCLE | Shape.LINE] =
  1746. Narrowphase.prototype.circleLine = function(
  1747. circleBody,
  1748. circleShape,
  1749. circleOffset,
  1750. circleAngle,
  1751. lineBody,
  1752. lineShape,
  1753. lineOffset,
  1754. lineAngle,
  1755. justTest,
  1756. lineRadius,
  1757. circleRadius
  1758. ){
  1759. var lineRadius = lineRadius || 0,
  1760. circleRadius = typeof(circleRadius)!=="undefined" ? circleRadius : circleShape.radius,
  1761. orthoDist = tmp1,
  1762. lineToCircleOrthoUnit = tmp2,
  1763. projectedPoint = tmp3,
  1764. centerDist = tmp4,
  1765. worldTangent = tmp5,
  1766. worldEdge = tmp6,
  1767. worldEdgeUnit = tmp7,
  1768. worldVertex0 = tmp8,
  1769. worldVertex1 = tmp9,
  1770. worldVertex01 = tmp10,
  1771. worldVertex11 = tmp11,
  1772. dist = tmp12,
  1773. lineToCircle = tmp13,
  1774. lineEndToLineRadius = tmp14,
  1775. verts = tmpArray;
  1776. // Get start and end points
  1777. vec2.set(worldVertex0, -lineShape.length/2, 0);
  1778. vec2.set(worldVertex1, lineShape.length/2, 0);
  1779. // Not sure why we have to use worldVertex*1 here, but it won't work otherwise. Tired.
  1780. vec2.rotate(worldVertex01, worldVertex0, lineAngle);
  1781. vec2.rotate(worldVertex11, worldVertex1, lineAngle);
  1782. add(worldVertex01, worldVertex01, lineOffset);
  1783. add(worldVertex11, worldVertex11, lineOffset);
  1784. vec2.copy(worldVertex0,worldVertex01);
  1785. vec2.copy(worldVertex1,worldVertex11);
  1786. // Get vector along the line
  1787. sub(worldEdge, worldVertex1, worldVertex0);
  1788. vec2.normalize(worldEdgeUnit, worldEdge);
  1789. // Get tangent to the edge.
  1790. vec2.rotate90cw(worldTangent, worldEdgeUnit);
  1791. // Check distance from the plane spanned by the edge vs the circle
  1792. sub(dist, circleOffset, worldVertex0);
  1793. var d = dot(dist, worldTangent); // Distance from center of line to circle center
  1794. sub(centerDist, worldVertex0, lineOffset);
  1795. sub(lineToCircle, circleOffset, lineOffset);
  1796. var radiusSum = circleRadius + lineRadius;
  1797. if(Math.abs(d) < radiusSum){
  1798. // Now project the circle onto the edge
  1799. vec2.scale(orthoDist, worldTangent, d);
  1800. sub(projectedPoint, circleOffset, orthoDist);
  1801. // Add the missing line radius
  1802. vec2.scale(lineToCircleOrthoUnit, worldTangent, dot(worldTangent, lineToCircle));
  1803. vec2.normalize(lineToCircleOrthoUnit,lineToCircleOrthoUnit);
  1804. vec2.scale(lineToCircleOrthoUnit, lineToCircleOrthoUnit, lineRadius);
  1805. add(projectedPoint,projectedPoint,lineToCircleOrthoUnit);
  1806. // Check if the point is within the edge span
  1807. var pos = dot(worldEdgeUnit, projectedPoint);
  1808. var pos0 = dot(worldEdgeUnit, worldVertex0);
  1809. var pos1 = dot(worldEdgeUnit, worldVertex1);
  1810. if(pos > pos0 && pos < pos1){
  1811. // We got contact!
  1812. if(justTest){
  1813. return true;
  1814. }
  1815. var c = this.createContactEquation(circleBody,lineBody,circleShape,lineShape);
  1816. vec2.scale(c.normalA, orthoDist, -1);
  1817. vec2.normalize(c.normalA, c.normalA);
  1818. vec2.scale( c.contactPointA, c.normalA, circleRadius);
  1819. add(c.contactPointA, c.contactPointA, circleOffset);
  1820. sub(c.contactPointA, c.contactPointA, circleBody.position);
  1821. sub(c.contactPointB, projectedPoint, lineOffset);
  1822. add(c.contactPointB, c.contactPointB, lineOffset);
  1823. sub(c.contactPointB, c.contactPointB, lineBody.position);
  1824. this.contactEquations.push(c);
  1825. if(this.enableFriction){
  1826. this.frictionEquations.push(this.createFrictionFromContact(c));
  1827. }
  1828. return 1;
  1829. }
  1830. }
  1831. // Add corner
  1832. verts[0] = worldVertex0;
  1833. verts[1] = worldVertex1;
  1834. for(var i=0; i<verts.length; i++){
  1835. var v = verts[i];
  1836. sub(dist, v, circleOffset);
  1837. if(vec2.squaredLength(dist) < Math.pow(radiusSum, 2)){
  1838. if(justTest){
  1839. return true;
  1840. }
  1841. var c = this.createContactEquation(circleBody,lineBody,circleShape,lineShape);
  1842. vec2.copy(c.normalA, dist);
  1843. vec2.normalize(c.normalA,c.normalA);
  1844. // Vector from circle to contact point is the normal times the circle radius
  1845. vec2.scale(c.contactPointA, c.normalA, circleRadius);
  1846. add(c.contactPointA, c.contactPointA, circleOffset);
  1847. sub(c.contactPointA, c.contactPointA, circleBody.position);
  1848. sub(c.contactPointB, v, lineOffset);
  1849. vec2.scale(lineEndToLineRadius, c.normalA, -lineRadius);
  1850. add(c.contactPointB, c.contactPointB, lineEndToLineRadius);
  1851. add(c.contactPointB, c.contactPointB, lineOffset);
  1852. sub(c.contactPointB, c.contactPointB, lineBody.position);
  1853. this.contactEquations.push(c);
  1854. if(this.enableFriction){
  1855. this.frictionEquations.push(this.createFrictionFromContact(c));
  1856. }
  1857. return 1;
  1858. }
  1859. }
  1860. return 0;
  1861. };
  1862. /**
  1863. * Circle/capsule Narrowphase
  1864. * @method circleCapsule
  1865. * @param {Body} bi
  1866. * @param {Circle} si
  1867. * @param {Array} xi
  1868. * @param {Number} ai
  1869. * @param {Body} bj
  1870. * @param {Line} sj
  1871. * @param {Array} xj
  1872. * @param {Number} aj
  1873. */
  1874. Narrowphase.prototype[Shape.CIRCLE | Shape.CAPSULE] =
  1875. Narrowphase.prototype.circleCapsule = function(bi,si,xi,ai, bj,sj,xj,aj, justTest){
  1876. return this.circleLine(bi,si,xi,ai, bj,sj,xj,aj, justTest, sj.radius);
  1877. };
  1878. /**
  1879. * Circle/convex Narrowphase.
  1880. * @method circleConvex
  1881. * @param {Body} circleBody
  1882. * @param {Circle} circleShape
  1883. * @param {Array} circleOffset
  1884. * @param {Number} circleAngle
  1885. * @param {Body} convexBody
  1886. * @param {Convex} convexShape
  1887. * @param {Array} convexOffset
  1888. * @param {Number} convexAngle
  1889. * @param {Boolean} justTest
  1890. * @param {Number} circleRadius
  1891. */
  1892. Narrowphase.prototype[Shape.CIRCLE | Shape.CONVEX] =
  1893. Narrowphase.prototype[Shape.CIRCLE | Shape.BOX] =
  1894. Narrowphase.prototype.circleConvex = function(
  1895. circleBody,
  1896. circleShape,
  1897. circleOffset,
  1898. circleAngle,
  1899. convexBody,
  1900. convexShape,
  1901. convexOffset,
  1902. convexAngle,
  1903. justTest,
  1904. circleRadius
  1905. ){
  1906. var circleRadius = typeof(circleRadius)==="number" ? circleRadius : circleShape.radius;
  1907. var worldVertex0 = tmp1,
  1908. worldVertex1 = tmp2,
  1909. worldEdge = tmp3,
  1910. worldEdgeUnit = tmp4,
  1911. worldNormal = tmp5,
  1912. centerDist = tmp6,
  1913. convexToCircle = tmp7,
  1914. orthoDist = tmp8,
  1915. projectedPoint = tmp9,
  1916. dist = tmp10,
  1917. worldVertex = tmp11,
  1918. closestEdge = -1,
  1919. closestEdgeDistance = null,
  1920. closestEdgeOrthoDist = tmp12,
  1921. closestEdgeProjectedPoint = tmp13,
  1922. candidate = tmp14,
  1923. candidateDist = tmp15,
  1924. minCandidate = tmp16,
  1925. found = false,
  1926. minCandidateDistance = Number.MAX_VALUE;
  1927. var numReported = 0;
  1928. // New algorithm:
  1929. // 1. Check so center of circle is not inside the polygon. If it is, this wont work...
  1930. // 2. For each edge
  1931. // 2. 1. Get point on circle that is closest to the edge (scale normal with -radius)
  1932. // 2. 2. Check if point is inside.
  1933. var verts = convexShape.vertices;
  1934. // Check all edges first
  1935. for(var i=0; i!==verts.length+1; i++){
  1936. var v0 = verts[i%verts.length],
  1937. v1 = verts[(i+1)%verts.length];
  1938. vec2.rotate(worldVertex0, v0, convexAngle);
  1939. vec2.rotate(worldVertex1, v1, convexAngle);
  1940. add(worldVertex0, worldVertex0, convexOffset);
  1941. add(worldVertex1, worldVertex1, convexOffset);
  1942. sub(worldEdge, worldVertex1, worldVertex0);
  1943. vec2.normalize(worldEdgeUnit, worldEdge);
  1944. // Get tangent to the edge. Points out of the Convex
  1945. vec2.rotate90cw(worldNormal, worldEdgeUnit);
  1946. // Get point on circle, closest to the polygon
  1947. vec2.scale(candidate,worldNormal,-circleShape.radius);
  1948. add(candidate,candidate,circleOffset);
  1949. if(pointInConvex(candidate,convexShape,convexOffset,convexAngle)){
  1950. vec2.sub(candidateDist,worldVertex0,candidate);
  1951. var candidateDistance = Math.abs(vec2.dot(candidateDist,worldNormal));
  1952. if(candidateDistance < minCandidateDistance){
  1953. vec2.copy(minCandidate,candidate);
  1954. minCandidateDistance = candidateDistance;
  1955. vec2.scale(closestEdgeProjectedPoint,worldNormal,candidateDistance);
  1956. vec2.add(closestEdgeProjectedPoint,closestEdgeProjectedPoint,candidate);
  1957. found = true;
  1958. }
  1959. }
  1960. }
  1961. if(found){
  1962. if(justTest){
  1963. return true;
  1964. }
  1965. var c = this.createContactEquation(circleBody,convexBody,circleShape,convexShape);
  1966. vec2.sub(c.normalA, minCandidate, circleOffset);
  1967. vec2.normalize(c.normalA, c.normalA);
  1968. vec2.scale(c.contactPointA, c.normalA, circleRadius);
  1969. add(c.contactPointA, c.contactPointA, circleOffset);
  1970. sub(c.contactPointA, c.contactPointA, circleBody.position);
  1971. sub(c.contactPointB, closestEdgeProjectedPoint, convexOffset);
  1972. add(c.contactPointB, c.contactPointB, convexOffset);
  1973. sub(c.contactPointB, c.contactPointB, convexBody.position);
  1974. this.contactEquations.push(c);
  1975. if(this.enableFriction){
  1976. this.frictionEquations.push( this.createFrictionFromContact(c) );
  1977. }
  1978. return 1;
  1979. }
  1980. // Check all vertices
  1981. if(circleRadius > 0){
  1982. for(var i=0; i<verts.length; i++){
  1983. var localVertex = verts[i];
  1984. vec2.rotate(worldVertex, localVertex, convexAngle);
  1985. add(worldVertex, worldVertex, convexOffset);
  1986. sub(dist, worldVertex, circleOffset);
  1987. if(vec2.squaredLength(dist) < Math.pow(circleRadius, 2)){
  1988. if(justTest){
  1989. return true;
  1990. }
  1991. var c = this.createContactEquation(circleBody,convexBody,circleShape,convexShape);
  1992. vec2.copy(c.normalA, dist);
  1993. vec2.normalize(c.normalA,c.normalA);
  1994. // Vector from circle to contact point is the normal times the circle radius
  1995. vec2.scale(c.contactPointA, c.normalA, circleRadius);
  1996. add(c.contactPointA, c.contactPointA, circleOffset);
  1997. sub(c.contactPointA, c.contactPointA, circleBody.position);
  1998. sub(c.contactPointB, worldVertex, convexOffset);
  1999. add(c.contactPointB, c.contactPointB, convexOffset);
  2000. sub(c.contactPointB, c.contactPointB, convexBody.position);
  2001. this.contactEquations.push(c);
  2002. if(this.enableFriction){
  2003. this.frictionEquations.push(this.createFrictionFromContact(c));
  2004. }
  2005. return 1;
  2006. }
  2007. }
  2008. }
  2009. return 0;
  2010. };
  2011. var pic_worldVertex0 = vec2.create(),
  2012. pic_worldVertex1 = vec2.create(),
  2013. pic_r0 = vec2.create(),
  2014. pic_r1 = vec2.create();
  2015. /*
  2016. * Check if a point is in a polygon
  2017. */
  2018. function pointInConvex(worldPoint,convexShape,convexOffset,convexAngle){
  2019. var worldVertex0 = pic_worldVertex0,
  2020. worldVertex1 = pic_worldVertex1,
  2021. r0 = pic_r0,
  2022. r1 = pic_r1,
  2023. point = worldPoint,
  2024. verts = convexShape.vertices,
  2025. lastCross = null;
  2026. for(var i=0; i!==verts.length+1; i++){
  2027. var v0 = verts[i%verts.length],
  2028. v1 = verts[(i+1)%verts.length];
  2029. // Transform vertices to world
  2030. // @todo The point should be transformed to local coordinates in the convex, no need to transform each vertex
  2031. vec2.rotate(worldVertex0, v0, convexAngle);
  2032. vec2.rotate(worldVertex1, v1, convexAngle);
  2033. add(worldVertex0, worldVertex0, convexOffset);
  2034. add(worldVertex1, worldVertex1, convexOffset);
  2035. sub(r0, worldVertex0, point);
  2036. sub(r1, worldVertex1, point);
  2037. var cross = vec2.crossLength(r0,r1);
  2038. if(lastCross===null){
  2039. lastCross = cross;
  2040. }
  2041. // If we got a different sign of the distance vector, the point is out of the polygon
  2042. if(cross*lastCross <= 0){
  2043. return false;
  2044. }
  2045. lastCross = cross;
  2046. }
  2047. return true;
  2048. }
  2049. /**
  2050. * Particle/convex Narrowphase
  2051. * @method particleConvex
  2052. * @param {Body} particleBody
  2053. * @param {Particle} particleShape
  2054. * @param {Array} particleOffset
  2055. * @param {Number} particleAngle
  2056. * @param {Body} convexBody
  2057. * @param {Convex} convexShape
  2058. * @param {Array} convexOffset
  2059. * @param {Number} convexAngle
  2060. * @param {Boolean} justTest
  2061. * @todo use pointInConvex and code more similar to circleConvex
  2062. * @todo don't transform each vertex, but transform the particle position to convex-local instead
  2063. */
  2064. Narrowphase.prototype[Shape.PARTICLE | Shape.CONVEX] =
  2065. Narrowphase.prototype[Shape.PARTICLE | Shape.BOX] =
  2066. Narrowphase.prototype.particleConvex = function(
  2067. particleBody,
  2068. particleShape,
  2069. particleOffset,
  2070. particleAngle,
  2071. convexBody,
  2072. convexShape,
  2073. convexOffset,
  2074. convexAngle,
  2075. justTest
  2076. ){
  2077. var worldVertex0 = tmp1,
  2078. worldVertex1 = tmp2,
  2079. worldEdge = tmp3,
  2080. worldEdgeUnit = tmp4,
  2081. worldTangent = tmp5,
  2082. centerDist = tmp6,
  2083. convexToparticle = tmp7,
  2084. orthoDist = tmp8,
  2085. projectedPoint = tmp9,
  2086. dist = tmp10,
  2087. worldVertex = tmp11,
  2088. closestEdge = -1,
  2089. closestEdgeDistance = null,
  2090. closestEdgeOrthoDist = tmp12,
  2091. closestEdgeProjectedPoint = tmp13,
  2092. r0 = tmp14, // vector from particle to vertex0
  2093. r1 = tmp15,
  2094. localPoint = tmp16,
  2095. candidateDist = tmp17,
  2096. minEdgeNormal = tmp18,
  2097. minCandidateDistance = Number.MAX_VALUE;
  2098. var numReported = 0,
  2099. found = false,
  2100. verts = convexShape.vertices;
  2101. // Check if the particle is in the polygon at all
  2102. if(!pointInConvex(particleOffset,convexShape,convexOffset,convexAngle)){
  2103. return 0;
  2104. }
  2105. if(justTest){
  2106. return true;
  2107. }
  2108. // Check edges first
  2109. var lastCross = null;
  2110. for(var i=0; i!==verts.length+1; i++){
  2111. var v0 = verts[i%verts.length],
  2112. v1 = verts[(i+1)%verts.length];
  2113. // Transform vertices to world
  2114. vec2.rotate(worldVertex0, v0, convexAngle);
  2115. vec2.rotate(worldVertex1, v1, convexAngle);
  2116. add(worldVertex0, worldVertex0, convexOffset);
  2117. add(worldVertex1, worldVertex1, convexOffset);
  2118. // Get world edge
  2119. sub(worldEdge, worldVertex1, worldVertex0);
  2120. vec2.normalize(worldEdgeUnit, worldEdge);
  2121. // Get tangent to the edge. Points out of the Convex
  2122. vec2.rotate90cw(worldTangent, worldEdgeUnit);
  2123. // Check distance from the infinite line (spanned by the edge) to the particle
  2124. sub(dist, particleOffset, worldVertex0);
  2125. var d = dot(dist, worldTangent);
  2126. sub(centerDist, worldVertex0, convexOffset);
  2127. sub(convexToparticle, particleOffset, convexOffset);
  2128. vec2.sub(candidateDist,worldVertex0,particleOffset);
  2129. var candidateDistance = Math.abs(vec2.dot(candidateDist,worldTangent));
  2130. if(candidateDistance < minCandidateDistance){
  2131. minCandidateDistance = candidateDistance;
  2132. vec2.scale(closestEdgeProjectedPoint,worldTangent,candidateDistance);
  2133. vec2.add(closestEdgeProjectedPoint,closestEdgeProjectedPoint,particleOffset);
  2134. vec2.copy(minEdgeNormal,worldTangent);
  2135. found = true;
  2136. }
  2137. }
  2138. if(found){
  2139. var c = this.createContactEquation(particleBody,convexBody,particleShape,convexShape);
  2140. vec2.scale(c.normalA, minEdgeNormal, -1);
  2141. vec2.normalize(c.normalA, c.normalA);
  2142. // Particle has no extent to the contact point
  2143. vec2.set(c.contactPointA, 0, 0);
  2144. add(c.contactPointA, c.contactPointA, particleOffset);
  2145. sub(c.contactPointA, c.contactPointA, particleBody.position);
  2146. // From convex center to point
  2147. sub(c.contactPointB, closestEdgeProjectedPoint, convexOffset);
  2148. add(c.contactPointB, c.contactPointB, convexOffset);
  2149. sub(c.contactPointB, c.contactPointB, convexBody.position);
  2150. this.contactEquations.push(c);
  2151. if(this.enableFriction){
  2152. this.frictionEquations.push( this.createFrictionFromContact(c) );
  2153. }
  2154. return 1;
  2155. }
  2156. return 0;
  2157. };
  2158. /**
  2159. * Circle/circle Narrowphase
  2160. * @method circleCircle
  2161. * @param {Body} bodyA
  2162. * @param {Circle} shapeA
  2163. * @param {Array} offsetA
  2164. * @param {Number} angleA
  2165. * @param {Body} bodyB
  2166. * @param {Circle} shapeB
  2167. * @param {Array} offsetB
  2168. * @param {Number} angleB
  2169. * @param {Boolean} justTest
  2170. * @param {Number} [radiusA] Optional radius to use for shapeA
  2171. * @param {Number} [radiusB] Optional radius to use for shapeB
  2172. */
  2173. Narrowphase.prototype[Shape.CIRCLE] =
  2174. Narrowphase.prototype.circleCircle = function(
  2175. bodyA,
  2176. shapeA,
  2177. offsetA,
  2178. angleA,
  2179. bodyB,
  2180. shapeB,
  2181. offsetB,
  2182. angleB,
  2183. justTest,
  2184. radiusA,
  2185. radiusB
  2186. ){
  2187. var dist = tmp1,
  2188. radiusA = radiusA || shapeA.radius,
  2189. radiusB = radiusB || shapeB.radius;
  2190. sub(dist,offsetA,offsetB);
  2191. var r = radiusA + radiusB;
  2192. if(vec2.squaredLength(dist) > Math.pow(r,2)){
  2193. return 0;
  2194. }
  2195. if(justTest){
  2196. return true;
  2197. }
  2198. var c = this.createContactEquation(bodyA,bodyB,shapeA,shapeB);
  2199. sub(c.normalA, offsetB, offsetA);
  2200. vec2.normalize(c.normalA,c.normalA);
  2201. vec2.scale( c.contactPointA, c.normalA, radiusA);
  2202. vec2.scale( c.contactPointB, c.normalA, -radiusB);
  2203. add(c.contactPointA, c.contactPointA, offsetA);
  2204. sub(c.contactPointA, c.contactPointA, bodyA.position);
  2205. add(c.contactPointB, c.contactPointB, offsetB);
  2206. sub(c.contactPointB, c.contactPointB, bodyB.position);
  2207. this.contactEquations.push(c);
  2208. if(this.enableFriction){
  2209. this.frictionEquations.push(this.createFrictionFromContact(c));
  2210. }
  2211. return 1;
  2212. };
  2213. /**
  2214. * Plane/Convex Narrowphase
  2215. * @method planeConvex
  2216. * @param {Body} planeBody
  2217. * @param {Plane} planeShape
  2218. * @param {Array} planeOffset
  2219. * @param {Number} planeAngle
  2220. * @param {Body} convexBody
  2221. * @param {Convex} convexShape
  2222. * @param {Array} convexOffset
  2223. * @param {Number} convexAngle
  2224. * @param {Boolean} justTest
  2225. */
  2226. Narrowphase.prototype[Shape.PLANE | Shape.CONVEX] =
  2227. Narrowphase.prototype[Shape.PLANE | Shape.BOX] =
  2228. Narrowphase.prototype.planeConvex = function(
  2229. planeBody,
  2230. planeShape,
  2231. planeOffset,
  2232. planeAngle,
  2233. convexBody,
  2234. convexShape,
  2235. convexOffset,
  2236. convexAngle,
  2237. justTest
  2238. ){
  2239. var worldVertex = tmp1,
  2240. worldNormal = tmp2,
  2241. dist = tmp3;
  2242. var numReported = 0;
  2243. vec2.rotate(worldNormal, yAxis, planeAngle);
  2244. for(var i=0; i!==convexShape.vertices.length; i++){
  2245. var v = convexShape.vertices[i];
  2246. vec2.rotate(worldVertex, v, convexAngle);
  2247. add(worldVertex, worldVertex, convexOffset);
  2248. sub(dist, worldVertex, planeOffset);
  2249. if(dot(dist,worldNormal) <= 0){
  2250. if(justTest){
  2251. return true;
  2252. }
  2253. // Found vertex
  2254. numReported++;
  2255. var c = this.createContactEquation(planeBody,convexBody,planeShape,convexShape);
  2256. sub(dist, worldVertex, planeOffset);
  2257. vec2.copy(c.normalA, worldNormal);
  2258. var d = dot(dist, c.normalA);
  2259. vec2.scale(dist, c.normalA, d);
  2260. // rj is from convex center to contact
  2261. sub(c.contactPointB, worldVertex, convexBody.position);
  2262. // ri is from plane center to contact
  2263. sub( c.contactPointA, worldVertex, dist);
  2264. sub( c.contactPointA, c.contactPointA, planeBody.position);
  2265. this.contactEquations.push(c);
  2266. if(!this.enableFrictionReduction){
  2267. if(this.enableFriction){
  2268. this.frictionEquations.push(this.createFrictionFromContact(c));
  2269. }
  2270. }
  2271. }
  2272. }
  2273. if(this.enableFrictionReduction){
  2274. if(this.enableFriction && numReported){
  2275. this.frictionEquations.push(this.createFrictionFromAverage(numReported));
  2276. }
  2277. }
  2278. return numReported;
  2279. };
  2280. /**
  2281. * Narrowphase for particle vs plane
  2282. * @method particlePlane
  2283. * @param {Body} particleBody
  2284. * @param {Particle} particleShape
  2285. * @param {Array} particleOffset
  2286. * @param {Number} particleAngle
  2287. * @param {Body} planeBody
  2288. * @param {Plane} planeShape
  2289. * @param {Array} planeOffset
  2290. * @param {Number} planeAngle
  2291. * @param {Boolean} justTest
  2292. */
  2293. Narrowphase.prototype[Shape.PARTICLE | Shape.PLANE] =
  2294. Narrowphase.prototype.particlePlane = function(
  2295. particleBody,
  2296. particleShape,
  2297. particleOffset,
  2298. particleAngle,
  2299. planeBody,
  2300. planeShape,
  2301. planeOffset,
  2302. planeAngle,
  2303. justTest
  2304. ){
  2305. var dist = tmp1,
  2306. worldNormal = tmp2;
  2307. planeAngle = planeAngle || 0;
  2308. sub(dist, particleOffset, planeOffset);
  2309. vec2.rotate(worldNormal, yAxis, planeAngle);
  2310. var d = dot(dist, worldNormal);
  2311. if(d > 0){
  2312. return 0;
  2313. }
  2314. if(justTest){
  2315. return true;
  2316. }
  2317. var c = this.createContactEquation(planeBody,particleBody,planeShape,particleShape);
  2318. vec2.copy(c.normalA, worldNormal);
  2319. vec2.scale( dist, c.normalA, d );
  2320. // dist is now the distance vector in the normal direction
  2321. // ri is the particle position projected down onto the plane, from the plane center
  2322. sub( c.contactPointA, particleOffset, dist);
  2323. sub( c.contactPointA, c.contactPointA, planeBody.position);
  2324. // rj is from the body center to the particle center
  2325. sub( c.contactPointB, particleOffset, particleBody.position );
  2326. this.contactEquations.push(c);
  2327. if(this.enableFriction){
  2328. this.frictionEquations.push(this.createFrictionFromContact(c));
  2329. }
  2330. return 1;
  2331. };
  2332. /**
  2333. * Circle/Particle Narrowphase
  2334. * @method circleParticle
  2335. * @param {Body} circleBody
  2336. * @param {Circle} circleShape
  2337. * @param {Array} circleOffset
  2338. * @param {Number} circleAngle
  2339. * @param {Body} particleBody
  2340. * @param {Particle} particleShape
  2341. * @param {Array} particleOffset
  2342. * @param {Number} particleAngle
  2343. * @param {Boolean} justTest
  2344. */
  2345. Narrowphase.prototype[Shape.CIRCLE | Shape.PARTICLE] =
  2346. Narrowphase.prototype.circleParticle = function(
  2347. circleBody,
  2348. circleShape,
  2349. circleOffset,
  2350. circleAngle,
  2351. particleBody,
  2352. particleShape,
  2353. particleOffset,
  2354. particleAngle,
  2355. justTest
  2356. ){
  2357. var dist = tmp1;
  2358. sub(dist, particleOffset, circleOffset);
  2359. if(vec2.squaredLength(dist) > Math.pow(circleShape.radius, 2)){
  2360. return 0;
  2361. }
  2362. if(justTest){
  2363. return true;
  2364. }
  2365. var c = this.createContactEquation(circleBody,particleBody,circleShape,particleShape);
  2366. vec2.copy(c.normalA, dist);
  2367. vec2.normalize(c.normalA,c.normalA);
  2368. // Vector from circle to contact point is the normal times the circle radius
  2369. vec2.scale(c.contactPointA, c.normalA, circleShape.radius);
  2370. add(c.contactPointA, c.contactPointA, circleOffset);
  2371. sub(c.contactPointA, c.contactPointA, circleBody.position);
  2372. // Vector from particle center to contact point is zero
  2373. sub(c.contactPointB, particleOffset, particleBody.position);
  2374. this.contactEquations.push(c);
  2375. if(this.enableFriction){
  2376. this.frictionEquations.push(this.createFrictionFromContact(c));
  2377. }
  2378. return 1;
  2379. };
  2380. var planeCapsule_tmpCircle = new Circle({ radius: 1 }),
  2381. planeCapsule_tmp1 = vec2.create(),
  2382. planeCapsule_tmp2 = vec2.create(),
  2383. planeCapsule_tmp3 = vec2.create();
  2384. /**
  2385. * @method planeCapsule
  2386. * @param {Body} planeBody
  2387. * @param {Circle} planeShape
  2388. * @param {Array} planeOffset
  2389. * @param {Number} planeAngle
  2390. * @param {Body} capsuleBody
  2391. * @param {Particle} capsuleShape
  2392. * @param {Array} capsuleOffset
  2393. * @param {Number} capsuleAngle
  2394. * @param {Boolean} justTest
  2395. */
  2396. Narrowphase.prototype[Shape.PLANE | Shape.CAPSULE] =
  2397. Narrowphase.prototype.planeCapsule = function(
  2398. planeBody,
  2399. planeShape,
  2400. planeOffset,
  2401. planeAngle,
  2402. capsuleBody,
  2403. capsuleShape,
  2404. capsuleOffset,
  2405. capsuleAngle,
  2406. justTest
  2407. ){
  2408. var end1 = planeCapsule_tmp1,
  2409. end2 = planeCapsule_tmp2,
  2410. circle = planeCapsule_tmpCircle,
  2411. dst = planeCapsule_tmp3;
  2412. // Compute world end positions
  2413. vec2.set(end1, -capsuleShape.length/2, 0);
  2414. vec2.rotate(end1,end1,capsuleAngle);
  2415. add(end1,end1,capsuleOffset);
  2416. vec2.set(end2, capsuleShape.length/2, 0);
  2417. vec2.rotate(end2,end2,capsuleAngle);
  2418. add(end2,end2,capsuleOffset);
  2419. circle.radius = capsuleShape.radius;
  2420. var enableFrictionBefore;
  2421. // Temporarily turn off friction
  2422. if(this.enableFrictionReduction){
  2423. enableFrictionBefore = this.enableFriction;
  2424. this.enableFriction = false;
  2425. }
  2426. // Do Narrowphase as two circles
  2427. var numContacts1 = this.circlePlane(capsuleBody,circle,end1,0, planeBody,planeShape,planeOffset,planeAngle, justTest),
  2428. numContacts2 = this.circlePlane(capsuleBody,circle,end2,0, planeBody,planeShape,planeOffset,planeAngle, justTest);
  2429. // Restore friction
  2430. if(this.enableFrictionReduction){
  2431. this.enableFriction = enableFrictionBefore;
  2432. }
  2433. if(justTest){
  2434. return numContacts1 || numContacts2;
  2435. } else {
  2436. var numTotal = numContacts1 + numContacts2;
  2437. if(this.enableFrictionReduction){
  2438. if(numTotal){
  2439. this.frictionEquations.push(this.createFrictionFromAverage(numTotal));
  2440. }
  2441. }
  2442. return numTotal;
  2443. }
  2444. };
  2445. /**
  2446. * Creates ContactEquations and FrictionEquations for a collision.
  2447. * @method circlePlane
  2448. * @param {Body} bi The first body that should be connected to the equations.
  2449. * @param {Circle} si The circle shape participating in the collision.
  2450. * @param {Array} xi Extra offset to take into account for the Shape, in addition to the one in circleBody.position. Will *not* be rotated by circleBody.angle (maybe it should, for sake of homogenity?). Set to null if none.
  2451. * @param {Body} bj The second body that should be connected to the equations.
  2452. * @param {Plane} sj The Plane shape that is participating
  2453. * @param {Array} xj Extra offset for the plane shape.
  2454. * @param {Number} aj Extra angle to apply to the plane
  2455. */
  2456. Narrowphase.prototype[Shape.CIRCLE | Shape.PLANE] =
  2457. Narrowphase.prototype.circlePlane = function( bi,si,xi,ai, bj,sj,xj,aj, justTest ){
  2458. var circleBody = bi,
  2459. circleShape = si,
  2460. circleOffset = xi, // Offset from body center, rotated!
  2461. planeBody = bj,
  2462. shapeB = sj,
  2463. planeOffset = xj,
  2464. planeAngle = aj;
  2465. planeAngle = planeAngle || 0;
  2466. // Vector from plane to circle
  2467. var planeToCircle = tmp1,
  2468. worldNormal = tmp2,
  2469. temp = tmp3;
  2470. sub(planeToCircle, circleOffset, planeOffset);
  2471. // World plane normal
  2472. vec2.rotate(worldNormal, yAxis, planeAngle);
  2473. // Normal direction distance
  2474. var d = dot(worldNormal, planeToCircle);
  2475. if(d > circleShape.radius){
  2476. return 0; // No overlap. Abort.
  2477. }
  2478. if(justTest){
  2479. return true;
  2480. }
  2481. // Create contact
  2482. var contact = this.createContactEquation(planeBody,circleBody,sj,si);
  2483. // ni is the plane world normal
  2484. vec2.copy(contact.normalA, worldNormal);
  2485. // rj is the vector from circle center to the contact point
  2486. vec2.scale(contact.contactPointB, contact.normalA, -circleShape.radius);
  2487. add(contact.contactPointB, contact.contactPointB, circleOffset);
  2488. sub(contact.contactPointB, contact.contactPointB, circleBody.position);
  2489. // ri is the distance from plane center to contact.
  2490. vec2.scale(temp, contact.normalA, d);
  2491. sub(contact.contactPointA, planeToCircle, temp ); // Subtract normal distance vector from the distance vector
  2492. add(contact.contactPointA, contact.contactPointA, planeOffset);
  2493. sub(contact.contactPointA, contact.contactPointA, planeBody.position);
  2494. this.contactEquations.push(contact);
  2495. if(this.enableFriction){
  2496. this.frictionEquations.push( this.createFrictionFromContact(contact) );
  2497. }
  2498. return 1;
  2499. };
  2500. /**
  2501. * Convex/convex Narrowphase.See <a href="http://www.altdevblogaday.com/2011/05/13/contact-generation-between-3d-convex-meshes/">this article</a> for more info.
  2502. * @method convexConvex
  2503. * @param {Body} bi
  2504. * @param {Convex} si
  2505. * @param {Array} xi
  2506. * @param {Number} ai
  2507. * @param {Body} bj
  2508. * @param {Convex} sj
  2509. * @param {Array} xj
  2510. * @param {Number} aj
  2511. */
  2512. Narrowphase.prototype[Shape.CONVEX] =
  2513. Narrowphase.prototype[Shape.CONVEX | Shape.BOX] =
  2514. Narrowphase.prototype[Shape.BOX] =
  2515. Narrowphase.prototype.convexConvex = function( bi,si,xi,ai, bj,sj,xj,aj, justTest, precision ){
  2516. var sepAxis = tmp1,
  2517. worldPoint = tmp2,
  2518. worldPoint0 = tmp3,
  2519. worldPoint1 = tmp4,
  2520. worldEdge = tmp5,
  2521. projected = tmp6,
  2522. penetrationVec = tmp7,
  2523. dist = tmp8,
  2524. worldNormal = tmp9,
  2525. numContacts = 0,
  2526. precision = typeof(precision) === 'number' ? precision : 0;
  2527. var found = Narrowphase.findSeparatingAxis(si,xi,ai,sj,xj,aj,sepAxis);
  2528. if(!found){
  2529. return 0;
  2530. }
  2531. // Make sure the separating axis is directed from shape i to shape j
  2532. sub(dist,xj,xi);
  2533. if(dot(sepAxis,dist) > 0){
  2534. vec2.scale(sepAxis,sepAxis,-1);
  2535. }
  2536. // Find edges with normals closest to the separating axis
  2537. var closestEdge1 = Narrowphase.getClosestEdge(si,ai,sepAxis,true), // Flipped axis
  2538. closestEdge2 = Narrowphase.getClosestEdge(sj,aj,sepAxis);
  2539. if(closestEdge1 === -1 || closestEdge2 === -1){
  2540. return 0;
  2541. }
  2542. // Loop over the shapes
  2543. for(var k=0; k<2; k++){
  2544. var closestEdgeA = closestEdge1,
  2545. closestEdgeB = closestEdge2,
  2546. shapeA = si, shapeB = sj,
  2547. offsetA = xi, offsetB = xj,
  2548. angleA = ai, angleB = aj,
  2549. bodyA = bi, bodyB = bj;
  2550. if(k === 0){
  2551. // Swap!
  2552. var tmp;
  2553. tmp = closestEdgeA;
  2554. closestEdgeA = closestEdgeB;
  2555. closestEdgeB = tmp;
  2556. tmp = shapeA;
  2557. shapeA = shapeB;
  2558. shapeB = tmp;
  2559. tmp = offsetA;
  2560. offsetA = offsetB;
  2561. offsetB = tmp;
  2562. tmp = angleA;
  2563. angleA = angleB;
  2564. angleB = tmp;
  2565. tmp = bodyA;
  2566. bodyA = bodyB;
  2567. bodyB = tmp;
  2568. }
  2569. // Loop over 2 points in convex B
  2570. for(var j=closestEdgeB; j<closestEdgeB+2; j++){
  2571. // Get world point
  2572. var v = shapeB.vertices[(j+shapeB.vertices.length)%shapeB.vertices.length];
  2573. vec2.rotate(worldPoint, v, angleB);
  2574. add(worldPoint, worldPoint, offsetB);
  2575. var insideNumEdges = 0;
  2576. // Loop over the 3 closest edges in convex A
  2577. for(var i=closestEdgeA-1; i<closestEdgeA+2; i++){
  2578. var v0 = shapeA.vertices[(i +shapeA.vertices.length)%shapeA.vertices.length],
  2579. v1 = shapeA.vertices[(i+1+shapeA.vertices.length)%shapeA.vertices.length];
  2580. // Construct the edge
  2581. vec2.rotate(worldPoint0, v0, angleA);
  2582. vec2.rotate(worldPoint1, v1, angleA);
  2583. add(worldPoint0, worldPoint0, offsetA);
  2584. add(worldPoint1, worldPoint1, offsetA);
  2585. sub(worldEdge, worldPoint1, worldPoint0);
  2586. vec2.rotate90cw(worldNormal, worldEdge); // Normal points out of convex 1
  2587. vec2.normalize(worldNormal,worldNormal);
  2588. sub(dist, worldPoint, worldPoint0);
  2589. var d = dot(worldNormal,dist);
  2590. if((i === closestEdgeA && d <= precision) || (i !== closestEdgeA && d <= 0)){
  2591. insideNumEdges++;
  2592. }
  2593. }
  2594. if(insideNumEdges >= 3){
  2595. if(justTest){
  2596. return true;
  2597. }
  2598. // worldPoint was on the "inside" side of each of the 3 checked edges.
  2599. // Project it to the center edge and use the projection direction as normal
  2600. // Create contact
  2601. var c = this.createContactEquation(bodyA,bodyB,shapeA,shapeB);
  2602. numContacts++;
  2603. // Get center edge from body A
  2604. var v0 = shapeA.vertices[(closestEdgeA) % shapeA.vertices.length],
  2605. v1 = shapeA.vertices[(closestEdgeA+1) % shapeA.vertices.length];
  2606. // Construct the edge
  2607. vec2.rotate(worldPoint0, v0, angleA);
  2608. vec2.rotate(worldPoint1, v1, angleA);
  2609. add(worldPoint0, worldPoint0, offsetA);
  2610. add(worldPoint1, worldPoint1, offsetA);
  2611. sub(worldEdge, worldPoint1, worldPoint0);
  2612. vec2.rotate90cw(c.normalA, worldEdge); // Normal points out of convex A
  2613. vec2.normalize(c.normalA,c.normalA);
  2614. sub(dist, worldPoint, worldPoint0); // From edge point to the penetrating point
  2615. var d = dot(c.normalA,dist); // Penetration
  2616. vec2.scale(penetrationVec, c.normalA, d); // Vector penetration
  2617. sub(c.contactPointA, worldPoint, offsetA);
  2618. sub(c.contactPointA, c.contactPointA, penetrationVec);
  2619. add(c.contactPointA, c.contactPointA, offsetA);
  2620. sub(c.contactPointA, c.contactPointA, bodyA.position);
  2621. sub(c.contactPointB, worldPoint, offsetB);
  2622. add(c.contactPointB, c.contactPointB, offsetB);
  2623. sub(c.contactPointB, c.contactPointB, bodyB.position);
  2624. this.contactEquations.push(c);
  2625. // Todo reduce to 1 friction equation if we have 2 contact points
  2626. if(!this.enableFrictionReduction){
  2627. if(this.enableFriction){
  2628. this.frictionEquations.push(this.createFrictionFromContact(c));
  2629. }
  2630. }
  2631. }
  2632. }
  2633. }
  2634. if(this.enableFrictionReduction){
  2635. if(this.enableFriction && numContacts){
  2636. this.frictionEquations.push(this.createFrictionFromAverage(numContacts));
  2637. }
  2638. }
  2639. return numContacts;
  2640. };
  2641. // .projectConvex is called by other functions, need local tmp vectors
  2642. var pcoa_tmp1 = vec2.fromValues(0,0);
  2643. /**
  2644. * Project a Convex onto a world-oriented axis
  2645. * @method projectConvexOntoAxis
  2646. * @static
  2647. * @param {Convex} convexShape
  2648. * @param {Array} convexOffset
  2649. * @param {Number} convexAngle
  2650. * @param {Array} worldAxis
  2651. * @param {Array} result
  2652. */
  2653. Narrowphase.projectConvexOntoAxis = function(convexShape, convexOffset, convexAngle, worldAxis, result){
  2654. var max=null,
  2655. min=null,
  2656. v,
  2657. value,
  2658. localAxis = pcoa_tmp1;
  2659. // Convert the axis to local coords of the body
  2660. vec2.rotate(localAxis, worldAxis, -convexAngle);
  2661. // Get projected position of all vertices
  2662. for(var i=0; i<convexShape.vertices.length; i++){
  2663. v = convexShape.vertices[i];
  2664. value = dot(v,localAxis);
  2665. if(max === null || value > max){
  2666. max = value;
  2667. }
  2668. if(min === null || value < min){
  2669. min = value;
  2670. }
  2671. }
  2672. if(min > max){
  2673. var t = min;
  2674. min = max;
  2675. max = t;
  2676. }
  2677. // Project the position of the body onto the axis - need to add this to the result
  2678. var offset = dot(convexOffset, worldAxis);
  2679. vec2.set( result, min + offset, max + offset);
  2680. };
  2681. // .findSeparatingAxis is called by other functions, need local tmp vectors
  2682. var fsa_tmp1 = vec2.fromValues(0,0)
  2683. , fsa_tmp2 = vec2.fromValues(0,0)
  2684. , fsa_tmp3 = vec2.fromValues(0,0)
  2685. , fsa_tmp4 = vec2.fromValues(0,0)
  2686. , fsa_tmp5 = vec2.fromValues(0,0)
  2687. , fsa_tmp6 = vec2.fromValues(0,0);
  2688. /**
  2689. * Find a separating axis between the shapes, that maximizes the separating distance between them.
  2690. * @method findSeparatingAxis
  2691. * @static
  2692. * @param {Convex} c1
  2693. * @param {Array} offset1
  2694. * @param {Number} angle1
  2695. * @param {Convex} c2
  2696. * @param {Array} offset2
  2697. * @param {Number} angle2
  2698. * @param {Array} sepAxis The resulting axis
  2699. * @return {Boolean} Whether the axis could be found.
  2700. */
  2701. Narrowphase.findSeparatingAxis = function(c1,offset1,angle1,c2,offset2,angle2,sepAxis){
  2702. var maxDist = null,
  2703. overlap = false,
  2704. found = false,
  2705. edge = fsa_tmp1,
  2706. worldPoint0 = fsa_tmp2,
  2707. worldPoint1 = fsa_tmp3,
  2708. normal = fsa_tmp4,
  2709. span1 = fsa_tmp5,
  2710. span2 = fsa_tmp6;
  2711. if(c1 instanceof Box && c2 instanceof Box){
  2712. for(var j=0; j!==2; j++){
  2713. var c = c1,
  2714. angle = angle1;
  2715. if(j===1){
  2716. c = c2;
  2717. angle = angle2;
  2718. }
  2719. for(var i=0; i!==2; i++){
  2720. // Get the world edge
  2721. if(i === 0){
  2722. vec2.set(normal, 0, 1);
  2723. } else if(i === 1) {
  2724. vec2.set(normal, 1, 0);
  2725. }
  2726. if(angle !== 0){
  2727. vec2.rotate(normal, normal, angle);
  2728. }
  2729. // Project hulls onto that normal
  2730. Narrowphase.projectConvexOntoAxis(c1,offset1,angle1,normal,span1);
  2731. Narrowphase.projectConvexOntoAxis(c2,offset2,angle2,normal,span2);
  2732. // Order by span position
  2733. var a=span1,
  2734. b=span2,
  2735. swapped = false;
  2736. if(span1[0] > span2[0]){
  2737. b=span1;
  2738. a=span2;
  2739. swapped = true;
  2740. }
  2741. // Get separating distance
  2742. var dist = b[0] - a[1];
  2743. overlap = (dist <= 0);
  2744. if(maxDist===null || dist > maxDist){
  2745. vec2.copy(sepAxis, normal);
  2746. maxDist = dist;
  2747. found = overlap;
  2748. }
  2749. }
  2750. }
  2751. } else {
  2752. for(var j=0; j!==2; j++){
  2753. var c = c1,
  2754. angle = angle1;
  2755. if(j===1){
  2756. c = c2;
  2757. angle = angle2;
  2758. }
  2759. for(var i=0; i!==c.vertices.length; i++){
  2760. // Get the world edge
  2761. vec2.rotate(worldPoint0, c.vertices[i], angle);
  2762. vec2.rotate(worldPoint1, c.vertices[(i+1)%c.vertices.length], angle);
  2763. sub(edge, worldPoint1, worldPoint0);
  2764. // Get normal - just rotate 90 degrees since vertices are given in CCW
  2765. vec2.rotate90cw(normal, edge);
  2766. vec2.normalize(normal,normal);
  2767. // Project hulls onto that normal
  2768. Narrowphase.projectConvexOntoAxis(c1,offset1,angle1,normal,span1);
  2769. Narrowphase.projectConvexOntoAxis(c2,offset2,angle2,normal,span2);
  2770. // Order by span position
  2771. var a=span1,
  2772. b=span2,
  2773. swapped = false;
  2774. if(span1[0] > span2[0]){
  2775. b=span1;
  2776. a=span2;
  2777. swapped = true;
  2778. }
  2779. // Get separating distance
  2780. var dist = b[0] - a[1];
  2781. overlap = (dist <= 0);
  2782. if(maxDist===null || dist > maxDist){
  2783. vec2.copy(sepAxis, normal);
  2784. maxDist = dist;
  2785. found = overlap;
  2786. }
  2787. }
  2788. }
  2789. }
  2790. /*
  2791. // Needs to be tested some more
  2792. for(var j=0; j!==2; j++){
  2793. var c = c1,
  2794. angle = angle1;
  2795. if(j===1){
  2796. c = c2;
  2797. angle = angle2;
  2798. }
  2799. for(var i=0; i!==c.axes.length; i++){
  2800. var normal = c.axes[i];
  2801. // Project hulls onto that normal
  2802. Narrowphase.projectConvexOntoAxis(c1, offset1, angle1, normal, span1);
  2803. Narrowphase.projectConvexOntoAxis(c2, offset2, angle2, normal, span2);
  2804. // Order by span position
  2805. var a=span1,
  2806. b=span2,
  2807. swapped = false;
  2808. if(span1[0] > span2[0]){
  2809. b=span1;
  2810. a=span2;
  2811. swapped = true;
  2812. }
  2813. // Get separating distance
  2814. var dist = b[0] - a[1];
  2815. overlap = (dist <= Narrowphase.convexPrecision);
  2816. if(maxDist===null || dist > maxDist){
  2817. vec2.copy(sepAxis, normal);
  2818. maxDist = dist;
  2819. found = overlap;
  2820. }
  2821. }
  2822. }
  2823. */
  2824. return found;
  2825. };
  2826. // .getClosestEdge is called by other functions, need local tmp vectors
  2827. var gce_tmp1 = vec2.fromValues(0,0)
  2828. , gce_tmp2 = vec2.fromValues(0,0)
  2829. , gce_tmp3 = vec2.fromValues(0,0);
  2830. /**
  2831. * Get the edge that has a normal closest to an axis.
  2832. * @method getClosestEdge
  2833. * @static
  2834. * @param {Convex} c
  2835. * @param {Number} angle
  2836. * @param {Array} axis
  2837. * @param {Boolean} flip
  2838. * @return {Number} Index of the edge that is closest. This index and the next spans the resulting edge. Returns -1 if failed.
  2839. */
  2840. Narrowphase.getClosestEdge = function(c,angle,axis,flip){
  2841. var localAxis = gce_tmp1,
  2842. edge = gce_tmp2,
  2843. normal = gce_tmp3;
  2844. // Convert the axis to local coords of the body
  2845. vec2.rotate(localAxis, axis, -angle);
  2846. if(flip){
  2847. vec2.scale(localAxis,localAxis,-1);
  2848. }
  2849. var closestEdge = -1,
  2850. N = c.vertices.length,
  2851. maxDot = -1;
  2852. for(var i=0; i!==N; i++){
  2853. // Get the edge
  2854. sub(edge, c.vertices[(i+1)%N], c.vertices[i%N]);
  2855. // Get normal - just rotate 90 degrees since vertices are given in CCW
  2856. vec2.rotate90cw(normal, edge);
  2857. vec2.normalize(normal,normal);
  2858. var d = dot(normal,localAxis);
  2859. if(closestEdge === -1 || d > maxDot){
  2860. closestEdge = i % N;
  2861. maxDot = d;
  2862. }
  2863. }
  2864. return closestEdge;
  2865. };
  2866. var circleHeightfield_candidate = vec2.create(),
  2867. circleHeightfield_dist = vec2.create(),
  2868. circleHeightfield_v0 = vec2.create(),
  2869. circleHeightfield_v1 = vec2.create(),
  2870. circleHeightfield_minCandidate = vec2.create(),
  2871. circleHeightfield_worldNormal = vec2.create(),
  2872. circleHeightfield_minCandidateNormal = vec2.create();
  2873. /**
  2874. * @method circleHeightfield
  2875. * @param {Body} bi
  2876. * @param {Circle} si
  2877. * @param {Array} xi
  2878. * @param {Body} bj
  2879. * @param {Heightfield} sj
  2880. * @param {Array} xj
  2881. * @param {Number} aj
  2882. */
  2883. Narrowphase.prototype[Shape.CIRCLE | Shape.HEIGHTFIELD] =
  2884. Narrowphase.prototype.circleHeightfield = function( circleBody,circleShape,circlePos,circleAngle,
  2885. hfBody,hfShape,hfPos,hfAngle, justTest, radius ){
  2886. var data = hfShape.heights,
  2887. radius = radius || circleShape.radius,
  2888. w = hfShape.elementWidth,
  2889. dist = circleHeightfield_dist,
  2890. candidate = circleHeightfield_candidate,
  2891. minCandidate = circleHeightfield_minCandidate,
  2892. minCandidateNormal = circleHeightfield_minCandidateNormal,
  2893. worldNormal = circleHeightfield_worldNormal,
  2894. v0 = circleHeightfield_v0,
  2895. v1 = circleHeightfield_v1;
  2896. // Get the index of the points to test against
  2897. var idxA = Math.floor( (circlePos[0] - radius - hfPos[0]) / w ),
  2898. idxB = Math.ceil( (circlePos[0] + radius - hfPos[0]) / w );
  2899. /*if(idxB < 0 || idxA >= data.length)
  2900. return justTest ? false : 0;*/
  2901. if(idxA < 0){
  2902. idxA = 0;
  2903. }
  2904. if(idxB >= data.length){
  2905. idxB = data.length-1;
  2906. }
  2907. // Get max and min
  2908. var max = data[idxA],
  2909. min = data[idxB];
  2910. for(var i=idxA; i<idxB; i++){
  2911. if(data[i] < min){
  2912. min = data[i];
  2913. }
  2914. if(data[i] > max){
  2915. max = data[i];
  2916. }
  2917. }
  2918. if(circlePos[1]-radius > max){
  2919. return justTest ? false : 0;
  2920. }
  2921. /*
  2922. if(circlePos[1]+radius < min){
  2923. // Below the minimum point... We can just guess.
  2924. // TODO
  2925. }
  2926. */
  2927. // 1. Check so center of circle is not inside the field. If it is, this wont work...
  2928. // 2. For each edge
  2929. // 2. 1. Get point on circle that is closest to the edge (scale normal with -radius)
  2930. // 2. 2. Check if point is inside.
  2931. var found = false;
  2932. // Check all edges first
  2933. for(var i=idxA; i<idxB; i++){
  2934. // Get points
  2935. vec2.set(v0, i*w, data[i] );
  2936. vec2.set(v1, (i+1)*w, data[i+1]);
  2937. vec2.add(v0,v0,hfPos);
  2938. vec2.add(v1,v1,hfPos);
  2939. // Get normal
  2940. vec2.sub(worldNormal, v1, v0);
  2941. vec2.rotate(worldNormal, worldNormal, Math.PI/2);
  2942. vec2.normalize(worldNormal,worldNormal);
  2943. // Get point on circle, closest to the edge
  2944. vec2.scale(candidate,worldNormal,-radius);
  2945. vec2.add(candidate,candidate,circlePos);
  2946. // Distance from v0 to the candidate point
  2947. vec2.sub(dist,candidate,v0);
  2948. // Check if it is in the element "stick"
  2949. var d = vec2.dot(dist,worldNormal);
  2950. if(candidate[0] >= v0[0] && candidate[0] < v1[0] && d <= 0){
  2951. if(justTest){
  2952. return true;
  2953. }
  2954. found = true;
  2955. // Store the candidate point, projected to the edge
  2956. vec2.scale(dist,worldNormal,-d);
  2957. vec2.add(minCandidate,candidate,dist);
  2958. vec2.copy(minCandidateNormal,worldNormal);
  2959. var c = this.createContactEquation(hfBody,circleBody,hfShape,circleShape);
  2960. // Normal is out of the heightfield
  2961. vec2.copy(c.normalA, minCandidateNormal);
  2962. // Vector from circle to heightfield
  2963. vec2.scale(c.contactPointB, c.normalA, -radius);
  2964. add(c.contactPointB, c.contactPointB, circlePos);
  2965. sub(c.contactPointB, c.contactPointB, circleBody.position);
  2966. vec2.copy(c.contactPointA, minCandidate);
  2967. vec2.sub(c.contactPointA, c.contactPointA, hfBody.position);
  2968. this.contactEquations.push(c);
  2969. if(this.enableFriction){
  2970. this.frictionEquations.push( this.createFrictionFromContact(c) );
  2971. }
  2972. }
  2973. }
  2974. // Check all vertices
  2975. found = false;
  2976. if(radius > 0){
  2977. for(var i=idxA; i<=idxB; i++){
  2978. // Get point
  2979. vec2.set(v0, i*w, data[i]);
  2980. vec2.add(v0,v0,hfPos);
  2981. vec2.sub(dist, circlePos, v0);
  2982. if(vec2.squaredLength(dist) < Math.pow(radius, 2)){
  2983. if(justTest){
  2984. return true;
  2985. }
  2986. found = true;
  2987. var c = this.createContactEquation(hfBody,circleBody,hfShape,circleShape);
  2988. // Construct normal - out of heightfield
  2989. vec2.copy(c.normalA, dist);
  2990. vec2.normalize(c.normalA,c.normalA);
  2991. vec2.scale(c.contactPointB, c.normalA, -radius);
  2992. add(c.contactPointB, c.contactPointB, circlePos);
  2993. sub(c.contactPointB, c.contactPointB, circleBody.position);
  2994. sub(c.contactPointA, v0, hfPos);
  2995. add(c.contactPointA, c.contactPointA, hfPos);
  2996. sub(c.contactPointA, c.contactPointA, hfBody.position);
  2997. this.contactEquations.push(c);
  2998. if(this.enableFriction){
  2999. this.frictionEquations.push(this.createFrictionFromContact(c));
  3000. }
  3001. }
  3002. }
  3003. }
  3004. if(found){
  3005. return 1;
  3006. }
  3007. return 0;
  3008. };
  3009. var convexHeightfield_v0 = vec2.create(),
  3010. convexHeightfield_v1 = vec2.create(),
  3011. convexHeightfield_tilePos = vec2.create(),
  3012. convexHeightfield_tempConvexShape = new Convex({ vertices: [vec2.create(),vec2.create(),vec2.create(),vec2.create()] });
  3013. /**
  3014. * @method circleHeightfield
  3015. * @param {Body} bi
  3016. * @param {Circle} si
  3017. * @param {Array} xi
  3018. * @param {Body} bj
  3019. * @param {Heightfield} sj
  3020. * @param {Array} xj
  3021. * @param {Number} aj
  3022. */
  3023. Narrowphase.prototype[Shape.BOX | Shape.HEIGHTFIELD] =
  3024. Narrowphase.prototype[Shape.CONVEX | Shape.HEIGHTFIELD] =
  3025. Narrowphase.prototype.convexHeightfield = function( convexBody,convexShape,convexPos,convexAngle,
  3026. hfBody,hfShape,hfPos,hfAngle, justTest ){
  3027. var data = hfShape.heights,
  3028. w = hfShape.elementWidth,
  3029. v0 = convexHeightfield_v0,
  3030. v1 = convexHeightfield_v1,
  3031. tilePos = convexHeightfield_tilePos,
  3032. tileConvex = convexHeightfield_tempConvexShape;
  3033. // Get the index of the points to test against
  3034. var idxA = Math.floor( (convexBody.aabb.lowerBound[0] - hfPos[0]) / w ),
  3035. idxB = Math.ceil( (convexBody.aabb.upperBound[0] - hfPos[0]) / w );
  3036. if(idxA < 0){
  3037. idxA = 0;
  3038. }
  3039. if(idxB >= data.length){
  3040. idxB = data.length-1;
  3041. }
  3042. // Get max and min
  3043. var max = data[idxA],
  3044. min = data[idxB];
  3045. for(var i=idxA; i<idxB; i++){
  3046. if(data[i] < min){
  3047. min = data[i];
  3048. }
  3049. if(data[i] > max){
  3050. max = data[i];
  3051. }
  3052. }
  3053. if(convexBody.aabb.lowerBound[1] > max){
  3054. return justTest ? false : 0;
  3055. }
  3056. var found = false;
  3057. var numContacts = 0;
  3058. // Loop over all edges
  3059. // TODO: If possible, construct a convex from several data points (need o check if the points make a convex shape)
  3060. for(var i=idxA; i<idxB; i++){
  3061. // Get points
  3062. vec2.set(v0, i*w, data[i] );
  3063. vec2.set(v1, (i+1)*w, data[i+1]);
  3064. vec2.add(v0,v0,hfPos);
  3065. vec2.add(v1,v1,hfPos);
  3066. // Construct a convex
  3067. var tileHeight = 100; // todo
  3068. vec2.set(tilePos, (v1[0] + v0[0])*0.5, (v1[1] + v0[1] - tileHeight)*0.5);
  3069. vec2.sub(tileConvex.vertices[0], v1, tilePos);
  3070. vec2.sub(tileConvex.vertices[1], v0, tilePos);
  3071. vec2.copy(tileConvex.vertices[2], tileConvex.vertices[1]);
  3072. vec2.copy(tileConvex.vertices[3], tileConvex.vertices[0]);
  3073. tileConvex.vertices[2][1] -= tileHeight;
  3074. tileConvex.vertices[3][1] -= tileHeight;
  3075. // Do convex collision
  3076. numContacts += this.convexConvex( convexBody, convexShape, convexPos, convexAngle,
  3077. hfBody, tileConvex, tilePos, 0, justTest);
  3078. }
  3079. return numContacts;
  3080. };
  3081. },{"../equations/ContactEquation":21,"../equations/Equation":22,"../equations/FrictionEquation":23,"../math/vec2":30,"../objects/Body":31,"../shapes/Box":37,"../shapes/Circle":39,"../shapes/Convex":40,"../shapes/Shape":45,"../utils/ContactEquationPool":48,"../utils/FrictionEquationPool":49,"../utils/TupleDictionary":56,"../utils/Utils":57}],11:[function(_dereq_,module,exports){
  3082. module.exports = Ray;
  3083. var vec2 = _dereq_('../math/vec2');
  3084. var RaycastResult = _dereq_('../collision/RaycastResult');
  3085. var Shape = _dereq_('../shapes/Shape');
  3086. var AABB = _dereq_('../collision/AABB');
  3087. /**
  3088. * A line with a start and end point that is used to intersect shapes. For an example, see {{#crossLink "World/raycast:method"}}World.raycast{{/crossLink}}
  3089. * @class Ray
  3090. * @constructor
  3091. * @param {object} [options]
  3092. * @param {array} [options.from]
  3093. * @param {array} [options.to]
  3094. * @param {boolean} [options.checkCollisionResponse=true]
  3095. * @param {boolean} [options.skipBackfaces=false]
  3096. * @param {number} [options.collisionMask=-1]
  3097. * @param {number} [options.collisionGroup=-1]
  3098. * @param {number} [options.mode=Ray.ANY]
  3099. * @param {number} [options.callback]
  3100. */
  3101. function Ray(options){
  3102. options = options || {};
  3103. /**
  3104. * Ray start point.
  3105. * @property {array} from
  3106. */
  3107. this.from = options.from ? vec2.fromValues(options.from[0], options.from[1]) : vec2.create();
  3108. /**
  3109. * Ray end point
  3110. * @property {array} to
  3111. */
  3112. this.to = options.to ? vec2.fromValues(options.to[0], options.to[1]) : vec2.create();
  3113. /**
  3114. * Set to true if you want the Ray to take .collisionResponse flags into account on bodies and shapes.
  3115. * @property {Boolean} checkCollisionResponse
  3116. */
  3117. this.checkCollisionResponse = options.checkCollisionResponse !== undefined ? options.checkCollisionResponse : true;
  3118. /**
  3119. * If set to true, the ray skips any hits with normal.dot(rayDirection) < 0.
  3120. * @property {Boolean} skipBackfaces
  3121. */
  3122. this.skipBackfaces = !!options.skipBackfaces;
  3123. /**
  3124. * @property {number} collisionMask
  3125. * @default -1
  3126. */
  3127. this.collisionMask = options.collisionMask !== undefined ? options.collisionMask : -1;
  3128. /**
  3129. * @property {number} collisionGroup
  3130. * @default -1
  3131. */
  3132. this.collisionGroup = options.collisionGroup !== undefined ? options.collisionGroup : -1;
  3133. /**
  3134. * The intersection mode. Should be {{#crossLink "Ray/ANY:property"}}Ray.ANY{{/crossLink}}, {{#crossLink "Ray/ALL:property"}}Ray.ALL{{/crossLink}} or {{#crossLink "Ray/CLOSEST:property"}}Ray.CLOSEST{{/crossLink}}.
  3135. * @property {number} mode
  3136. */
  3137. this.mode = options.mode !== undefined ? options.mode : Ray.ANY;
  3138. /**
  3139. * Current, user-provided result callback. Will be used if mode is Ray.ALL.
  3140. * @property {Function} callback
  3141. */
  3142. this.callback = options.callback || function(result){};
  3143. /**
  3144. * @readOnly
  3145. * @property {array} direction
  3146. */
  3147. this.direction = vec2.create();
  3148. /**
  3149. * Length of the ray
  3150. * @readOnly
  3151. * @property {number} length
  3152. */
  3153. this.length = 1;
  3154. this.update();
  3155. }
  3156. Ray.prototype.constructor = Ray;
  3157. /**
  3158. * This raycasting mode will make the Ray traverse through all intersection points and only return the closest one.
  3159. * @static
  3160. * @property {Number} CLOSEST
  3161. */
  3162. Ray.CLOSEST = 1;
  3163. /**
  3164. * This raycasting mode will make the Ray stop when it finds the first intersection point.
  3165. * @static
  3166. * @property {Number} ANY
  3167. */
  3168. Ray.ANY = 2;
  3169. /**
  3170. * This raycasting mode will traverse all intersection points and executes a callback for each one.
  3171. * @static
  3172. * @property {Number} ALL
  3173. */
  3174. Ray.ALL = 4;
  3175. /**
  3176. * Should be called if you change the from or to point.
  3177. * @method update
  3178. */
  3179. Ray.prototype.update = function(){
  3180. // Update .direction and .length
  3181. var d = this.direction;
  3182. vec2.sub(d, this.to, this.from);
  3183. this.length = vec2.length(d);
  3184. vec2.normalize(d, d);
  3185. };
  3186. /**
  3187. * @method intersectBodies
  3188. * @param {Array} bodies An array of Body objects.
  3189. */
  3190. Ray.prototype.intersectBodies = function (result, bodies) {
  3191. for (var i = 0, l = bodies.length; !result.shouldStop(this) && i < l; i++) {
  3192. var body = bodies[i];
  3193. var aabb = body.getAABB();
  3194. if(aabb.overlapsRay(this) >= 0 || aabb.containsPoint(this.from)){
  3195. this.intersectBody(result, body);
  3196. }
  3197. }
  3198. };
  3199. var intersectBody_worldPosition = vec2.create();
  3200. /**
  3201. * Shoot a ray at a body, get back information about the hit.
  3202. * @method intersectBody
  3203. * @private
  3204. * @param {Body} body
  3205. */
  3206. Ray.prototype.intersectBody = function (result, body) {
  3207. var checkCollisionResponse = this.checkCollisionResponse;
  3208. if(checkCollisionResponse && !body.collisionResponse){
  3209. return;
  3210. }
  3211. var worldPosition = intersectBody_worldPosition;
  3212. for (var i = 0, N = body.shapes.length; i < N; i++) {
  3213. var shape = body.shapes[i];
  3214. if(checkCollisionResponse && !shape.collisionResponse){
  3215. continue; // Skip
  3216. }
  3217. if((this.collisionGroup & shape.collisionMask) === 0 || (shape.collisionGroup & this.collisionMask) === 0){
  3218. continue;
  3219. }
  3220. // Get world angle and position of the shape
  3221. vec2.rotate(worldPosition, shape.position, body.angle);
  3222. vec2.add(worldPosition, worldPosition, body.position);
  3223. var worldAngle = shape.angle + body.angle;
  3224. this.intersectShape(
  3225. result,
  3226. shape,
  3227. worldAngle,
  3228. worldPosition,
  3229. body
  3230. );
  3231. if(result.shouldStop(this)){
  3232. break;
  3233. }
  3234. }
  3235. };
  3236. /**
  3237. * @method intersectShape
  3238. * @private
  3239. * @param {Shape} shape
  3240. * @param {number} angle
  3241. * @param {array} position
  3242. * @param {Body} body
  3243. */
  3244. Ray.prototype.intersectShape = function(result, shape, angle, position, body){
  3245. var from = this.from;
  3246. // Checking radius
  3247. var distance = distanceFromIntersectionSquared(from, this.direction, position);
  3248. if (distance > shape.boundingRadius * shape.boundingRadius) {
  3249. return;
  3250. }
  3251. this._currentBody = body;
  3252. this._currentShape = shape;
  3253. shape.raycast(result, this, position, angle);
  3254. this._currentBody = this._currentShape = null;
  3255. };
  3256. /**
  3257. * Get the AABB of the ray.
  3258. * @method getAABB
  3259. * @param {AABB} aabb
  3260. */
  3261. Ray.prototype.getAABB = function(result){
  3262. var to = this.to;
  3263. var from = this.from;
  3264. vec2.set(
  3265. result.lowerBound,
  3266. Math.min(to[0], from[0]),
  3267. Math.min(to[1], from[1])
  3268. );
  3269. vec2.set(
  3270. result.upperBound,
  3271. Math.max(to[0], from[0]),
  3272. Math.max(to[1], from[1])
  3273. );
  3274. };
  3275. var hitPointWorld = vec2.create();
  3276. /**
  3277. * @method reportIntersection
  3278. * @private
  3279. * @param {number} fraction
  3280. * @param {array} normal
  3281. * @param {number} [faceIndex=-1]
  3282. * @return {boolean} True if the intersections should continue
  3283. */
  3284. Ray.prototype.reportIntersection = function(result, fraction, normal, faceIndex){
  3285. var from = this.from;
  3286. var to = this.to;
  3287. var shape = this._currentShape;
  3288. var body = this._currentBody;
  3289. // Skip back faces?
  3290. if(this.skipBackfaces && vec2.dot(normal, this.direction) > 0){
  3291. return;
  3292. }
  3293. switch(this.mode){
  3294. case Ray.ALL:
  3295. result.set(
  3296. normal,
  3297. shape,
  3298. body,
  3299. fraction,
  3300. faceIndex
  3301. );
  3302. this.callback(result);
  3303. break;
  3304. case Ray.CLOSEST:
  3305. // Store if closer than current closest
  3306. if(fraction < result.fraction || !result.hasHit()){
  3307. result.set(
  3308. normal,
  3309. shape,
  3310. body,
  3311. fraction,
  3312. faceIndex
  3313. );
  3314. }
  3315. break;
  3316. case Ray.ANY:
  3317. // Report and stop.
  3318. result.set(
  3319. normal,
  3320. shape,
  3321. body,
  3322. fraction,
  3323. faceIndex
  3324. );
  3325. break;
  3326. }
  3327. };
  3328. var v0 = vec2.create(),
  3329. intersect = vec2.create();
  3330. function distanceFromIntersectionSquared(from, direction, position) {
  3331. // v0 is vector from from to position
  3332. vec2.sub(v0, position, from);
  3333. var dot = vec2.dot(v0, direction);
  3334. // intersect = direction * dot + from
  3335. vec2.scale(intersect, direction, dot);
  3336. vec2.add(intersect, intersect, from);
  3337. return vec2.squaredDistance(position, intersect);
  3338. }
  3339. },{"../collision/AABB":7,"../collision/RaycastResult":12,"../math/vec2":30,"../shapes/Shape":45}],12:[function(_dereq_,module,exports){
  3340. var vec2 = _dereq_('../math/vec2');
  3341. var Ray = _dereq_('../collision/Ray');
  3342. module.exports = RaycastResult;
  3343. /**
  3344. * Storage for Ray casting hit data.
  3345. * @class RaycastResult
  3346. * @constructor
  3347. */
  3348. function RaycastResult(){
  3349. /**
  3350. * The normal of the hit, oriented in world space.
  3351. * @property {array} normal
  3352. */
  3353. this.normal = vec2.create();
  3354. /**
  3355. * The hit shape, or null.
  3356. * @property {Shape} shape
  3357. */
  3358. this.shape = null;
  3359. /**
  3360. * The hit body, or null.
  3361. * @property {Body} body
  3362. */
  3363. this.body = null;
  3364. /**
  3365. * The index of the hit triangle, if the hit shape was indexable.
  3366. * @property {number} faceIndex
  3367. * @default -1
  3368. */
  3369. this.faceIndex = -1;
  3370. /**
  3371. * Distance to the hit, as a fraction. 0 is at the "from" point, 1 is at the "to" point. Will be set to -1 if there was no hit yet.
  3372. * @property {number} fraction
  3373. * @default -1
  3374. */
  3375. this.fraction = -1;
  3376. /**
  3377. * If the ray should stop traversing.
  3378. * @readonly
  3379. * @property {Boolean} isStopped
  3380. */
  3381. this.isStopped = false;
  3382. }
  3383. /**
  3384. * Reset all result data. Must be done before re-using the result object.
  3385. * @method reset
  3386. */
  3387. RaycastResult.prototype.reset = function () {
  3388. vec2.set(this.normal, 0, 0);
  3389. this.shape = null;
  3390. this.body = null;
  3391. this.faceIndex = -1;
  3392. this.fraction = -1;
  3393. this.isStopped = false;
  3394. };
  3395. /**
  3396. * Get the distance to the hit point.
  3397. * @method getHitDistance
  3398. * @param {Ray} ray
  3399. */
  3400. RaycastResult.prototype.getHitDistance = function (ray) {
  3401. return vec2.distance(ray.from, ray.to) * this.fraction;
  3402. };
  3403. /**
  3404. * Returns true if the ray hit something since the last reset().
  3405. * @method hasHit
  3406. */
  3407. RaycastResult.prototype.hasHit = function () {
  3408. return this.fraction !== -1;
  3409. };
  3410. /**
  3411. * Get world hit point.
  3412. * @method getHitPoint
  3413. * @param {array} out
  3414. * @param {Ray} ray
  3415. */
  3416. RaycastResult.prototype.getHitPoint = function (out, ray) {
  3417. vec2.lerp(out, ray.from, ray.to, this.fraction);
  3418. };
  3419. /**
  3420. * Can be called while iterating over hits to stop searching for hit points.
  3421. * @method stop
  3422. */
  3423. RaycastResult.prototype.stop = function(){
  3424. this.isStopped = true;
  3425. };
  3426. /**
  3427. * @method shouldStop
  3428. * @private
  3429. * @param {Ray} ray
  3430. * @return {boolean}
  3431. */
  3432. RaycastResult.prototype.shouldStop = function(ray){
  3433. return this.isStopped || (this.fraction !== -1 && ray.mode === Ray.ANY);
  3434. };
  3435. /**
  3436. * @method set
  3437. * @private
  3438. * @param {array} normal
  3439. * @param {Shape} shape
  3440. * @param {Body} body
  3441. * @param {number} fraction
  3442. */
  3443. RaycastResult.prototype.set = function(
  3444. normal,
  3445. shape,
  3446. body,
  3447. fraction,
  3448. faceIndex
  3449. ){
  3450. vec2.copy(this.normal, normal);
  3451. this.shape = shape;
  3452. this.body = body;
  3453. this.fraction = fraction;
  3454. this.faceIndex = faceIndex;
  3455. };
  3456. },{"../collision/Ray":11,"../math/vec2":30}],13:[function(_dereq_,module,exports){
  3457. var Utils = _dereq_('../utils/Utils')
  3458. , Broadphase = _dereq_('../collision/Broadphase');
  3459. module.exports = SAPBroadphase;
  3460. /**
  3461. * Sweep and prune broadphase along one axis.
  3462. *
  3463. * @class SAPBroadphase
  3464. * @constructor
  3465. * @extends Broadphase
  3466. */
  3467. function SAPBroadphase(){
  3468. Broadphase.call(this,Broadphase.SAP);
  3469. /**
  3470. * List of bodies currently in the broadphase.
  3471. * @property axisList
  3472. * @type {Array}
  3473. */
  3474. this.axisList = [];
  3475. /**
  3476. * The axis to sort along. 0 means x-axis and 1 y-axis. If your bodies are more spread out over the X axis, set axisIndex to 0, and you will gain some performance.
  3477. * @property axisIndex
  3478. * @type {Number}
  3479. */
  3480. this.axisIndex = 0;
  3481. var that = this;
  3482. this._addBodyHandler = function(e){
  3483. that.axisList.push(e.body);
  3484. };
  3485. this._removeBodyHandler = function(e){
  3486. // Remove from list
  3487. var idx = that.axisList.indexOf(e.body);
  3488. if(idx !== -1){
  3489. that.axisList.splice(idx,1);
  3490. }
  3491. };
  3492. }
  3493. SAPBroadphase.prototype = new Broadphase();
  3494. SAPBroadphase.prototype.constructor = SAPBroadphase;
  3495. /**
  3496. * Change the world
  3497. * @method setWorld
  3498. * @param {World} world
  3499. */
  3500. SAPBroadphase.prototype.setWorld = function(world){
  3501. // Clear the old axis array
  3502. this.axisList.length = 0;
  3503. // Add all bodies from the new world
  3504. Utils.appendArray(this.axisList, world.bodies);
  3505. // Remove old handlers, if any
  3506. world
  3507. .off("addBody",this._addBodyHandler)
  3508. .off("removeBody",this._removeBodyHandler);
  3509. // Add handlers to update the list of bodies.
  3510. world.on("addBody",this._addBodyHandler).on("removeBody",this._removeBodyHandler);
  3511. this.world = world;
  3512. };
  3513. /**
  3514. * Sorts bodies along an axis.
  3515. * @method sortAxisList
  3516. * @param {Array} a
  3517. * @param {number} axisIndex
  3518. * @return {Array}
  3519. */
  3520. SAPBroadphase.sortAxisList = function(a, axisIndex){
  3521. axisIndex = axisIndex|0;
  3522. for(var i=1,l=a.length; i<l; i++) {
  3523. var v = a[i];
  3524. for(var j=i - 1;j>=0;j--) {
  3525. if(a[j].aabb.lowerBound[axisIndex] <= v.aabb.lowerBound[axisIndex]){
  3526. break;
  3527. }
  3528. a[j+1] = a[j];
  3529. }
  3530. a[j+1] = v;
  3531. }
  3532. return a;
  3533. };
  3534. SAPBroadphase.prototype.sortList = function(){
  3535. var bodies = this.axisList,
  3536. axisIndex = this.axisIndex;
  3537. // Sort the lists
  3538. SAPBroadphase.sortAxisList(bodies, axisIndex);
  3539. };
  3540. /**
  3541. * Get the colliding pairs
  3542. * @method getCollisionPairs
  3543. * @param {World} world
  3544. * @return {Array}
  3545. */
  3546. SAPBroadphase.prototype.getCollisionPairs = function(world){
  3547. var bodies = this.axisList,
  3548. result = this.result,
  3549. axisIndex = this.axisIndex;
  3550. result.length = 0;
  3551. // Update all AABBs if needed
  3552. var l = bodies.length;
  3553. while(l--){
  3554. var b = bodies[l];
  3555. if(b.aabbNeedsUpdate){
  3556. b.updateAABB();
  3557. }
  3558. }
  3559. // Sort the lists
  3560. this.sortList();
  3561. // Look through the X list
  3562. for(var i=0, N=bodies.length|0; i!==N; i++){
  3563. var bi = bodies[i];
  3564. for(var j=i+1; j<N; j++){
  3565. var bj = bodies[j];
  3566. // Bounds overlap?
  3567. var overlaps = (bj.aabb.lowerBound[axisIndex] <= bi.aabb.upperBound[axisIndex]);
  3568. if(!overlaps){
  3569. break;
  3570. }
  3571. if(Broadphase.canCollide(bi,bj) && this.boundingVolumeCheck(bi,bj)){
  3572. result.push(bi,bj);
  3573. }
  3574. }
  3575. }
  3576. return result;
  3577. };
  3578. /**
  3579. * Returns all the bodies within an AABB.
  3580. * @method aabbQuery
  3581. * @param {World} world
  3582. * @param {AABB} aabb
  3583. * @param {array} result An array to store resulting bodies in.
  3584. * @return {array}
  3585. */
  3586. SAPBroadphase.prototype.aabbQuery = function(world, aabb, result){
  3587. result = result || [];
  3588. this.sortList();
  3589. var axisIndex = this.axisIndex;
  3590. var axis = 'x';
  3591. if(axisIndex === 1){ axis = 'y'; }
  3592. if(axisIndex === 2){ axis = 'z'; }
  3593. var axisList = this.axisList;
  3594. var lower = aabb.lowerBound[axis];
  3595. var upper = aabb.upperBound[axis];
  3596. for(var i = 0; i < axisList.length; i++){
  3597. var b = axisList[i];
  3598. if(b.aabbNeedsUpdate){
  3599. b.updateAABB();
  3600. }
  3601. if(b.aabb.overlaps(aabb)){
  3602. result.push(b);
  3603. }
  3604. }
  3605. return result;
  3606. };
  3607. },{"../collision/Broadphase":8,"../utils/Utils":57}],14:[function(_dereq_,module,exports){
  3608. module.exports = Constraint;
  3609. var Utils = _dereq_('../utils/Utils');
  3610. /**
  3611. * Base constraint class.
  3612. *
  3613. * @class Constraint
  3614. * @constructor
  3615. * @author schteppe
  3616. * @param {Body} bodyA
  3617. * @param {Body} bodyB
  3618. * @param {Number} type
  3619. * @param {Object} [options]
  3620. * @param {Object} [options.collideConnected=true]
  3621. */
  3622. function Constraint(bodyA, bodyB, type, options){
  3623. /**
  3624. * The type of constraint. May be one of Constraint.DISTANCE, Constraint.GEAR, Constraint.LOCK, Constraint.PRISMATIC or Constraint.REVOLUTE.
  3625. * @property {number} type
  3626. */
  3627. this.type = type;
  3628. options = Utils.defaults(options,{
  3629. collideConnected : true,
  3630. wakeUpBodies : true,
  3631. });
  3632. /**
  3633. * Equations to be solved in this constraint
  3634. *
  3635. * @property equations
  3636. * @type {Array}
  3637. */
  3638. this.equations = [];
  3639. /**
  3640. * First body participating in the constraint.
  3641. * @property bodyA
  3642. * @type {Body}
  3643. */
  3644. this.bodyA = bodyA;
  3645. /**
  3646. * Second body participating in the constraint.
  3647. * @property bodyB
  3648. * @type {Body}
  3649. */
  3650. this.bodyB = bodyB;
  3651. /**
  3652. * Set to true if you want the connected bodies to collide.
  3653. * @property collideConnected
  3654. * @type {Boolean}
  3655. * @default true
  3656. */
  3657. this.collideConnected = options.collideConnected;
  3658. // Wake up bodies when connected
  3659. if(options.wakeUpBodies){
  3660. if(bodyA){
  3661. bodyA.wakeUp();
  3662. }
  3663. if(bodyB){
  3664. bodyB.wakeUp();
  3665. }
  3666. }
  3667. }
  3668. /**
  3669. * Updates the internal constraint parameters before solve.
  3670. * @method update
  3671. */
  3672. Constraint.prototype.update = function(){
  3673. throw new Error("method update() not implmemented in this Constraint subclass!");
  3674. };
  3675. /**
  3676. * @static
  3677. * @property {number} DISTANCE
  3678. */
  3679. Constraint.DISTANCE = 1;
  3680. /**
  3681. * @static
  3682. * @property {number} GEAR
  3683. */
  3684. Constraint.GEAR = 2;
  3685. /**
  3686. * @static
  3687. * @property {number} LOCK
  3688. */
  3689. Constraint.LOCK = 3;
  3690. /**
  3691. * @static
  3692. * @property {number} PRISMATIC
  3693. */
  3694. Constraint.PRISMATIC = 4;
  3695. /**
  3696. * @static
  3697. * @property {number} REVOLUTE
  3698. */
  3699. Constraint.REVOLUTE = 5;
  3700. /**
  3701. * Set stiffness for this constraint.
  3702. * @method setStiffness
  3703. * @param {Number} stiffness
  3704. */
  3705. Constraint.prototype.setStiffness = function(stiffness){
  3706. var eqs = this.equations;
  3707. for(var i=0; i !== eqs.length; i++){
  3708. var eq = eqs[i];
  3709. eq.stiffness = stiffness;
  3710. eq.needsUpdate = true;
  3711. }
  3712. };
  3713. /**
  3714. * Set relaxation for this constraint.
  3715. * @method setRelaxation
  3716. * @param {Number} relaxation
  3717. */
  3718. Constraint.prototype.setRelaxation = function(relaxation){
  3719. var eqs = this.equations;
  3720. for(var i=0; i !== eqs.length; i++){
  3721. var eq = eqs[i];
  3722. eq.relaxation = relaxation;
  3723. eq.needsUpdate = true;
  3724. }
  3725. };
  3726. },{"../utils/Utils":57}],15:[function(_dereq_,module,exports){
  3727. var Constraint = _dereq_('./Constraint')
  3728. , Equation = _dereq_('../equations/Equation')
  3729. , vec2 = _dereq_('../math/vec2')
  3730. , Utils = _dereq_('../utils/Utils');
  3731. module.exports = DistanceConstraint;
  3732. /**
  3733. * Constraint that tries to keep the distance between two bodies constant.
  3734. *
  3735. * @class DistanceConstraint
  3736. * @constructor
  3737. * @author schteppe
  3738. * @param {Body} bodyA
  3739. * @param {Body} bodyB
  3740. * @param {object} [options]
  3741. * @param {number} [options.distance] The distance to keep between the anchor points. Defaults to the current distance between the bodies.
  3742. * @param {Array} [options.localAnchorA] The anchor point for bodyA, defined locally in bodyA frame. Defaults to [0,0].
  3743. * @param {Array} [options.localAnchorB] The anchor point for bodyB, defined locally in bodyB frame. Defaults to [0,0].
  3744. * @param {object} [options.maxForce=Number.MAX_VALUE] Maximum force to apply.
  3745. * @extends Constraint
  3746. *
  3747. * @example
  3748. * // If distance is not given as an option, then the current distance between the bodies is used.
  3749. * // In this example, the bodies will be constrained to have a distance of 2 between their centers.
  3750. * var bodyA = new Body({ mass: 1, position: [-1, 0] });
  3751. * var bodyB = new Body({ mass: 1, position: [1, 0] });
  3752. * var constraint = new DistanceConstraint(bodyA, bodyB);
  3753. * world.addConstraint(constraint);
  3754. *
  3755. * @example
  3756. * // Manually set the distance and anchors
  3757. * var constraint = new DistanceConstraint(bodyA, bodyB, {
  3758. * distance: 1, // Distance to keep between the points
  3759. * localAnchorA: [1, 0], // Point on bodyA
  3760. * localAnchorB: [-1, 0] // Point on bodyB
  3761. * });
  3762. * world.addConstraint(constraint);
  3763. */
  3764. function DistanceConstraint(bodyA,bodyB,options){
  3765. options = Utils.defaults(options,{
  3766. localAnchorA:[0,0],
  3767. localAnchorB:[0,0]
  3768. });
  3769. Constraint.call(this,bodyA,bodyB,Constraint.DISTANCE,options);
  3770. /**
  3771. * Local anchor in body A.
  3772. * @property localAnchorA
  3773. * @type {Array}
  3774. */
  3775. this.localAnchorA = vec2.fromValues(options.localAnchorA[0], options.localAnchorA[1]);
  3776. /**
  3777. * Local anchor in body B.
  3778. * @property localAnchorB
  3779. * @type {Array}
  3780. */
  3781. this.localAnchorB = vec2.fromValues(options.localAnchorB[0], options.localAnchorB[1]);
  3782. var localAnchorA = this.localAnchorA;
  3783. var localAnchorB = this.localAnchorB;
  3784. /**
  3785. * The distance to keep.
  3786. * @property distance
  3787. * @type {Number}
  3788. */
  3789. this.distance = 0;
  3790. if(typeof(options.distance) === 'number'){
  3791. this.distance = options.distance;
  3792. } else {
  3793. // Use the current world distance between the world anchor points.
  3794. var worldAnchorA = vec2.create(),
  3795. worldAnchorB = vec2.create(),
  3796. r = vec2.create();
  3797. // Transform local anchors to world
  3798. vec2.rotate(worldAnchorA, localAnchorA, bodyA.angle);
  3799. vec2.rotate(worldAnchorB, localAnchorB, bodyB.angle);
  3800. vec2.add(r, bodyB.position, worldAnchorB);
  3801. vec2.sub(r, r, worldAnchorA);
  3802. vec2.sub(r, r, bodyA.position);
  3803. this.distance = vec2.length(r);
  3804. }
  3805. var maxForce;
  3806. if(typeof(options.maxForce)==="undefined" ){
  3807. maxForce = Number.MAX_VALUE;
  3808. } else {
  3809. maxForce = options.maxForce;
  3810. }
  3811. var normal = new Equation(bodyA,bodyB,-maxForce,maxForce); // Just in the normal direction
  3812. this.equations = [ normal ];
  3813. /**
  3814. * Max force to apply.
  3815. * @property {number} maxForce
  3816. */
  3817. this.maxForce = maxForce;
  3818. // g = (xi - xj).dot(n)
  3819. // dg/dt = (vi - vj).dot(n) = G*W = [n 0 -n 0] * [vi wi vj wj]'
  3820. // ...and if we were to include offset points:
  3821. // g =
  3822. // (xj + rj - xi - ri).dot(n) - distance
  3823. //
  3824. // dg/dt =
  3825. // (vj + wj x rj - vi - wi x ri).dot(n) =
  3826. // { term 2 is near zero } =
  3827. // [-n -ri x n n rj x n] * [vi wi vj wj]' =
  3828. // G * W
  3829. //
  3830. // => G = [-n -rixn n rjxn]
  3831. var r = vec2.create();
  3832. var ri = vec2.create(); // worldAnchorA
  3833. var rj = vec2.create(); // worldAnchorB
  3834. var that = this;
  3835. normal.computeGq = function(){
  3836. var bodyA = this.bodyA,
  3837. bodyB = this.bodyB,
  3838. xi = bodyA.position,
  3839. xj = bodyB.position;
  3840. // Transform local anchors to world
  3841. vec2.rotate(ri, localAnchorA, bodyA.angle);
  3842. vec2.rotate(rj, localAnchorB, bodyB.angle);
  3843. vec2.add(r, xj, rj);
  3844. vec2.sub(r, r, ri);
  3845. vec2.sub(r, r, xi);
  3846. //vec2.sub(r, bodyB.position, bodyA.position);
  3847. return vec2.length(r) - that.distance;
  3848. };
  3849. // Make the contact constraint bilateral
  3850. this.setMaxForce(maxForce);
  3851. /**
  3852. * If the upper limit is enabled or not.
  3853. * @property {Boolean} upperLimitEnabled
  3854. */
  3855. this.upperLimitEnabled = false;
  3856. /**
  3857. * The upper constraint limit.
  3858. * @property {number} upperLimit
  3859. */
  3860. this.upperLimit = 1;
  3861. /**
  3862. * If the lower limit is enabled or not.
  3863. * @property {Boolean} lowerLimitEnabled
  3864. */
  3865. this.lowerLimitEnabled = false;
  3866. /**
  3867. * The lower constraint limit.
  3868. * @property {number} lowerLimit
  3869. */
  3870. this.lowerLimit = 0;
  3871. /**
  3872. * Current constraint position. This is equal to the current distance between the world anchor points.
  3873. * @property {number} position
  3874. */
  3875. this.position = 0;
  3876. }
  3877. DistanceConstraint.prototype = new Constraint();
  3878. DistanceConstraint.prototype.constructor = DistanceConstraint;
  3879. /**
  3880. * Update the constraint equations. Should be done if any of the bodies changed position, before solving.
  3881. * @method update
  3882. */
  3883. var n = vec2.create();
  3884. var ri = vec2.create(); // worldAnchorA
  3885. var rj = vec2.create(); // worldAnchorB
  3886. DistanceConstraint.prototype.update = function(){
  3887. var normal = this.equations[0],
  3888. bodyA = this.bodyA,
  3889. bodyB = this.bodyB,
  3890. distance = this.distance,
  3891. xi = bodyA.position,
  3892. xj = bodyB.position,
  3893. normalEquation = this.equations[0],
  3894. G = normal.G;
  3895. // Transform local anchors to world
  3896. vec2.rotate(ri, this.localAnchorA, bodyA.angle);
  3897. vec2.rotate(rj, this.localAnchorB, bodyB.angle);
  3898. // Get world anchor points and normal
  3899. vec2.add(n, xj, rj);
  3900. vec2.sub(n, n, ri);
  3901. vec2.sub(n, n, xi);
  3902. this.position = vec2.length(n);
  3903. var violating = false;
  3904. if(this.upperLimitEnabled){
  3905. if(this.position > this.upperLimit){
  3906. normalEquation.maxForce = 0;
  3907. normalEquation.minForce = -this.maxForce;
  3908. this.distance = this.upperLimit;
  3909. violating = true;
  3910. }
  3911. }
  3912. if(this.lowerLimitEnabled){
  3913. if(this.position < this.lowerLimit){
  3914. normalEquation.maxForce = this.maxForce;
  3915. normalEquation.minForce = 0;
  3916. this.distance = this.lowerLimit;
  3917. violating = true;
  3918. }
  3919. }
  3920. if((this.lowerLimitEnabled || this.upperLimitEnabled) && !violating){
  3921. // No constraint needed.
  3922. normalEquation.enabled = false;
  3923. return;
  3924. }
  3925. normalEquation.enabled = true;
  3926. vec2.normalize(n,n);
  3927. // Caluclate cross products
  3928. var rixn = vec2.crossLength(ri, n),
  3929. rjxn = vec2.crossLength(rj, n);
  3930. // G = [-n -rixn n rjxn]
  3931. G[0] = -n[0];
  3932. G[1] = -n[1];
  3933. G[2] = -rixn;
  3934. G[3] = n[0];
  3935. G[4] = n[1];
  3936. G[5] = rjxn;
  3937. };
  3938. /**
  3939. * Set the max force to be used
  3940. * @method setMaxForce
  3941. * @param {Number} maxForce
  3942. */
  3943. DistanceConstraint.prototype.setMaxForce = function(maxForce){
  3944. var normal = this.equations[0];
  3945. normal.minForce = -maxForce;
  3946. normal.maxForce = maxForce;
  3947. };
  3948. /**
  3949. * Get the max force
  3950. * @method getMaxForce
  3951. * @return {Number}
  3952. */
  3953. DistanceConstraint.prototype.getMaxForce = function(){
  3954. var normal = this.equations[0];
  3955. return normal.maxForce;
  3956. };
  3957. },{"../equations/Equation":22,"../math/vec2":30,"../utils/Utils":57,"./Constraint":14}],16:[function(_dereq_,module,exports){
  3958. var Constraint = _dereq_('./Constraint')
  3959. , Equation = _dereq_('../equations/Equation')
  3960. , AngleLockEquation = _dereq_('../equations/AngleLockEquation')
  3961. , vec2 = _dereq_('../math/vec2');
  3962. module.exports = GearConstraint;
  3963. /**
  3964. * Constrains the angle of two bodies to each other to be equal. If a gear ratio is not one, the angle of bodyA must be a multiple of the angle of bodyB.
  3965. * @class GearConstraint
  3966. * @constructor
  3967. * @author schteppe
  3968. * @param {Body} bodyA
  3969. * @param {Body} bodyB
  3970. * @param {Object} [options]
  3971. * @param {Number} [options.angle=0] Relative angle between the bodies. Will be set to the current angle between the bodies (the gear ratio is accounted for).
  3972. * @param {Number} [options.ratio=1] Gear ratio.
  3973. * @param {Number} [options.maxTorque] Maximum torque to apply.
  3974. * @extends Constraint
  3975. *
  3976. * @example
  3977. * var constraint = new GearConstraint(bodyA, bodyB);
  3978. * world.addConstraint(constraint);
  3979. *
  3980. * @example
  3981. * var constraint = new GearConstraint(bodyA, bodyB, {
  3982. * ratio: 2,
  3983. * maxTorque: 1000
  3984. * });
  3985. * world.addConstraint(constraint);
  3986. */
  3987. function GearConstraint(bodyA, bodyB, options){
  3988. options = options || {};
  3989. Constraint.call(this, bodyA, bodyB, Constraint.GEAR, options);
  3990. /**
  3991. * The gear ratio.
  3992. * @property ratio
  3993. * @type {Number}
  3994. */
  3995. this.ratio = options.ratio !== undefined ? options.ratio : 1;
  3996. /**
  3997. * The relative angle
  3998. * @property angle
  3999. * @type {Number}
  4000. */
  4001. this.angle = options.angle !== undefined ? options.angle : bodyB.angle - this.ratio * bodyA.angle;
  4002. // Send same parameters to the equation
  4003. options.angle = this.angle;
  4004. options.ratio = this.ratio;
  4005. this.equations = [
  4006. new AngleLockEquation(bodyA,bodyB,options),
  4007. ];
  4008. // Set max torque
  4009. if(options.maxTorque !== undefined){
  4010. this.setMaxTorque(options.maxTorque);
  4011. }
  4012. }
  4013. GearConstraint.prototype = new Constraint();
  4014. GearConstraint.prototype.constructor = GearConstraint;
  4015. GearConstraint.prototype.update = function(){
  4016. var eq = this.equations[0];
  4017. if(eq.ratio !== this.ratio){
  4018. eq.setRatio(this.ratio);
  4019. }
  4020. eq.angle = this.angle;
  4021. };
  4022. /**
  4023. * Set the max torque for the constraint.
  4024. * @method setMaxTorque
  4025. * @param {Number} torque
  4026. */
  4027. GearConstraint.prototype.setMaxTorque = function(torque){
  4028. this.equations[0].setMaxTorque(torque);
  4029. };
  4030. /**
  4031. * Get the max torque for the constraint.
  4032. * @method getMaxTorque
  4033. * @return {Number}
  4034. */
  4035. GearConstraint.prototype.getMaxTorque = function(torque){
  4036. return this.equations[0].maxForce;
  4037. };
  4038. },{"../equations/AngleLockEquation":20,"../equations/Equation":22,"../math/vec2":30,"./Constraint":14}],17:[function(_dereq_,module,exports){
  4039. var Constraint = _dereq_('./Constraint')
  4040. , vec2 = _dereq_('../math/vec2')
  4041. , Equation = _dereq_('../equations/Equation');
  4042. module.exports = LockConstraint;
  4043. /**
  4044. * Locks the relative position and rotation between two bodies.
  4045. *
  4046. * @class LockConstraint
  4047. * @constructor
  4048. * @author schteppe
  4049. * @param {Body} bodyA
  4050. * @param {Body} bodyB
  4051. * @param {Object} [options]
  4052. * @param {Array} [options.localOffsetB] The offset of bodyB in bodyA's frame. If not given the offset is computed from current positions.
  4053. * @param {number} [options.localAngleB] The angle of bodyB in bodyA's frame. If not given, the angle is computed from current angles.
  4054. * @param {number} [options.maxForce]
  4055. * @extends Constraint
  4056. *
  4057. * @example
  4058. * // Locks the relative position and rotation between bodyA and bodyB
  4059. * var constraint = new LockConstraint(bodyA, bodyB);
  4060. * world.addConstraint(constraint);
  4061. */
  4062. function LockConstraint(bodyA, bodyB, options){
  4063. options = options || {};
  4064. Constraint.call(this,bodyA,bodyB,Constraint.LOCK,options);
  4065. var maxForce = ( typeof(options.maxForce)==="undefined" ? Number.MAX_VALUE : options.maxForce );
  4066. var localAngleB = options.localAngleB || 0;
  4067. // Use 3 equations:
  4068. // gx = (xj - xi - l) * xhat = 0
  4069. // gy = (xj - xi - l) * yhat = 0
  4070. // gr = (xi - xj + r) * that = 0
  4071. //
  4072. // ...where:
  4073. // l is the localOffsetB vector rotated to world in bodyA frame
  4074. // r is the same vector but reversed and rotated from bodyB frame
  4075. // xhat, yhat are world axis vectors
  4076. // that is the tangent of r
  4077. //
  4078. // For the first two constraints, we get
  4079. // G*W = (vj - vi - ldot ) * xhat
  4080. // = (vj - vi - wi x l) * xhat
  4081. //
  4082. // Since (wi x l) * xhat = (l x xhat) * wi, we get
  4083. // G*W = [ -1 0 (-l x xhat) 1 0 0] * [vi wi vj wj]
  4084. //
  4085. // The last constraint gives
  4086. // GW = (vi - vj + wj x r) * that
  4087. // = [ that 0 -that (r x t) ]
  4088. var x = new Equation(bodyA,bodyB,-maxForce,maxForce),
  4089. y = new Equation(bodyA,bodyB,-maxForce,maxForce),
  4090. rot = new Equation(bodyA,bodyB,-maxForce,maxForce);
  4091. var l = vec2.create(),
  4092. g = vec2.create(),
  4093. that = this;
  4094. x.computeGq = function(){
  4095. vec2.rotate(l, that.localOffsetB, bodyA.angle);
  4096. vec2.sub(g, bodyB.position, bodyA.position);
  4097. vec2.sub(g, g, l);
  4098. return g[0];
  4099. };
  4100. y.computeGq = function(){
  4101. vec2.rotate(l, that.localOffsetB, bodyA.angle);
  4102. vec2.sub(g, bodyB.position, bodyA.position);
  4103. vec2.sub(g, g, l);
  4104. return g[1];
  4105. };
  4106. var r = vec2.create(),
  4107. t = vec2.create();
  4108. rot.computeGq = function(){
  4109. vec2.rotate(r, that.localOffsetB, bodyB.angle - that.localAngleB);
  4110. vec2.scale(r,r,-1);
  4111. vec2.sub(g,bodyA.position,bodyB.position);
  4112. vec2.add(g,g,r);
  4113. vec2.rotate(t,r,-Math.PI/2);
  4114. vec2.normalize(t,t);
  4115. return vec2.dot(g,t);
  4116. };
  4117. /**
  4118. * The offset of bodyB in bodyA's frame.
  4119. * @property {Array} localOffsetB
  4120. */
  4121. this.localOffsetB = vec2.create();
  4122. if(options.localOffsetB){
  4123. vec2.copy(this.localOffsetB, options.localOffsetB);
  4124. } else {
  4125. // Construct from current positions
  4126. vec2.sub(this.localOffsetB, bodyB.position, bodyA.position);
  4127. vec2.rotate(this.localOffsetB, this.localOffsetB, -bodyA.angle);
  4128. }
  4129. /**
  4130. * The offset angle of bodyB in bodyA's frame.
  4131. * @property {Number} localAngleB
  4132. */
  4133. this.localAngleB = 0;
  4134. if(typeof(options.localAngleB) === 'number'){
  4135. this.localAngleB = options.localAngleB;
  4136. } else {
  4137. // Construct
  4138. this.localAngleB = bodyB.angle - bodyA.angle;
  4139. }
  4140. this.equations.push(x, y, rot);
  4141. this.setMaxForce(maxForce);
  4142. }
  4143. LockConstraint.prototype = new Constraint();
  4144. LockConstraint.prototype.constructor = LockConstraint;
  4145. /**
  4146. * Set the maximum force to be applied.
  4147. * @method setMaxForce
  4148. * @param {Number} force
  4149. */
  4150. LockConstraint.prototype.setMaxForce = function(force){
  4151. var eqs = this.equations;
  4152. for(var i=0; i<this.equations.length; i++){
  4153. eqs[i].maxForce = force;
  4154. eqs[i].minForce = -force;
  4155. }
  4156. };
  4157. /**
  4158. * Get the max force.
  4159. * @method getMaxForce
  4160. * @return {Number}
  4161. */
  4162. LockConstraint.prototype.getMaxForce = function(){
  4163. return this.equations[0].maxForce;
  4164. };
  4165. var l = vec2.create();
  4166. var r = vec2.create();
  4167. var t = vec2.create();
  4168. var xAxis = vec2.fromValues(1,0);
  4169. var yAxis = vec2.fromValues(0,1);
  4170. LockConstraint.prototype.update = function(){
  4171. var x = this.equations[0],
  4172. y = this.equations[1],
  4173. rot = this.equations[2],
  4174. bodyA = this.bodyA,
  4175. bodyB = this.bodyB;
  4176. vec2.rotate(l,this.localOffsetB,bodyA.angle);
  4177. vec2.rotate(r,this.localOffsetB,bodyB.angle - this.localAngleB);
  4178. vec2.scale(r,r,-1);
  4179. vec2.rotate(t,r,Math.PI/2);
  4180. vec2.normalize(t,t);
  4181. x.G[0] = -1;
  4182. x.G[1] = 0;
  4183. x.G[2] = -vec2.crossLength(l,xAxis);
  4184. x.G[3] = 1;
  4185. y.G[0] = 0;
  4186. y.G[1] = -1;
  4187. y.G[2] = -vec2.crossLength(l,yAxis);
  4188. y.G[4] = 1;
  4189. rot.G[0] = -t[0];
  4190. rot.G[1] = -t[1];
  4191. rot.G[3] = t[0];
  4192. rot.G[4] = t[1];
  4193. rot.G[5] = vec2.crossLength(r,t);
  4194. };
  4195. },{"../equations/Equation":22,"../math/vec2":30,"./Constraint":14}],18:[function(_dereq_,module,exports){
  4196. var Constraint = _dereq_('./Constraint')
  4197. , ContactEquation = _dereq_('../equations/ContactEquation')
  4198. , Equation = _dereq_('../equations/Equation')
  4199. , vec2 = _dereq_('../math/vec2')
  4200. , RotationalLockEquation = _dereq_('../equations/RotationalLockEquation');
  4201. module.exports = PrismaticConstraint;
  4202. /**
  4203. * Constraint that only allows bodies to move along a line, relative to each other. See <a href="http://www.iforce2d.net/b2dtut/joints-prismatic">this tutorial</a>. Also called "slider constraint".
  4204. *
  4205. * @class PrismaticConstraint
  4206. * @constructor
  4207. * @extends Constraint
  4208. * @author schteppe
  4209. * @param {Body} bodyA
  4210. * @param {Body} bodyB
  4211. * @param {Object} [options]
  4212. * @param {Number} [options.maxForce] Max force to be applied by the constraint
  4213. * @param {Array} [options.localAnchorA] Body A's anchor point, defined in its own local frame.
  4214. * @param {Array} [options.localAnchorB] Body B's anchor point, defined in its own local frame.
  4215. * @param {Array} [options.localAxisA] An axis, defined in body A frame, that body B's anchor point may slide along.
  4216. * @param {Boolean} [options.disableRotationalLock] If set to true, bodyB will be free to rotate around its anchor point.
  4217. * @param {Number} [options.upperLimit]
  4218. * @param {Number} [options.lowerLimit]
  4219. * @todo Ability to create using only a point and a worldAxis
  4220. */
  4221. function PrismaticConstraint(bodyA, bodyB, options){
  4222. options = options || {};
  4223. Constraint.call(this,bodyA,bodyB,Constraint.PRISMATIC,options);
  4224. // Get anchors
  4225. var localAnchorA = vec2.fromValues(0,0),
  4226. localAxisA = vec2.fromValues(1,0),
  4227. localAnchorB = vec2.fromValues(0,0);
  4228. if(options.localAnchorA){ vec2.copy(localAnchorA, options.localAnchorA); }
  4229. if(options.localAxisA){ vec2.copy(localAxisA, options.localAxisA); }
  4230. if(options.localAnchorB){ vec2.copy(localAnchorB, options.localAnchorB); }
  4231. /**
  4232. * @property localAnchorA
  4233. * @type {Array}
  4234. */
  4235. this.localAnchorA = localAnchorA;
  4236. /**
  4237. * @property localAnchorB
  4238. * @type {Array}
  4239. */
  4240. this.localAnchorB = localAnchorB;
  4241. /**
  4242. * @property localAxisA
  4243. * @type {Array}
  4244. */
  4245. this.localAxisA = localAxisA;
  4246. /*
  4247. The constraint violation for the common axis point is
  4248. g = ( xj + rj - xi - ri ) * t := gg*t
  4249. where r are body-local anchor points, and t is a tangent to the constraint axis defined in body i frame.
  4250. gdot = ( vj + wj x rj - vi - wi x ri ) * t + ( xj + rj - xi - ri ) * ( wi x t )
  4251. Note the use of the chain rule. Now we identify the jacobian
  4252. G*W = [ -t -ri x t + t x gg t rj x t ] * [vi wi vj wj]
  4253. The rotational part is just a rotation lock.
  4254. */
  4255. var maxForce = this.maxForce = typeof(options.maxForce)!=="undefined" ? options.maxForce : Number.MAX_VALUE;
  4256. // Translational part
  4257. var trans = new Equation(bodyA,bodyB,-maxForce,maxForce);
  4258. var ri = new vec2.create(),
  4259. rj = new vec2.create(),
  4260. gg = new vec2.create(),
  4261. t = new vec2.create();
  4262. trans.computeGq = function(){
  4263. // g = ( xj + rj - xi - ri ) * t
  4264. return vec2.dot(gg,t);
  4265. };
  4266. trans.updateJacobian = function(){
  4267. var G = this.G,
  4268. xi = bodyA.position,
  4269. xj = bodyB.position;
  4270. vec2.rotate(ri,localAnchorA,bodyA.angle);
  4271. vec2.rotate(rj,localAnchorB,bodyB.angle);
  4272. vec2.add(gg,xj,rj);
  4273. vec2.sub(gg,gg,xi);
  4274. vec2.sub(gg,gg,ri);
  4275. vec2.rotate(t,localAxisA,bodyA.angle+Math.PI/2);
  4276. G[0] = -t[0];
  4277. G[1] = -t[1];
  4278. G[2] = -vec2.crossLength(ri,t) + vec2.crossLength(t,gg);
  4279. G[3] = t[0];
  4280. G[4] = t[1];
  4281. G[5] = vec2.crossLength(rj,t);
  4282. };
  4283. this.equations.push(trans);
  4284. // Rotational part
  4285. if(!options.disableRotationalLock){
  4286. var rot = new RotationalLockEquation(bodyA,bodyB,-maxForce,maxForce);
  4287. this.equations.push(rot);
  4288. }
  4289. /**
  4290. * The position of anchor A relative to anchor B, along the constraint axis.
  4291. * @property position
  4292. * @type {Number}
  4293. */
  4294. this.position = 0;
  4295. // Is this one used at all?
  4296. this.velocity = 0;
  4297. /**
  4298. * Set to true to enable lower limit.
  4299. * @property lowerLimitEnabled
  4300. * @type {Boolean}
  4301. */
  4302. this.lowerLimitEnabled = typeof(options.lowerLimit)!=="undefined" ? true : false;
  4303. /**
  4304. * Set to true to enable upper limit.
  4305. * @property upperLimitEnabled
  4306. * @type {Boolean}
  4307. */
  4308. this.upperLimitEnabled = typeof(options.upperLimit)!=="undefined" ? true : false;
  4309. /**
  4310. * Lower constraint limit. The constraint position is forced to be larger than this value.
  4311. * @property lowerLimit
  4312. * @type {Number}
  4313. */
  4314. this.lowerLimit = typeof(options.lowerLimit)!=="undefined" ? options.lowerLimit : 0;
  4315. /**
  4316. * Upper constraint limit. The constraint position is forced to be smaller than this value.
  4317. * @property upperLimit
  4318. * @type {Number}
  4319. */
  4320. this.upperLimit = typeof(options.upperLimit)!=="undefined" ? options.upperLimit : 1;
  4321. // Equations used for limits
  4322. this.upperLimitEquation = new ContactEquation(bodyA,bodyB);
  4323. this.lowerLimitEquation = new ContactEquation(bodyA,bodyB);
  4324. // Set max/min forces
  4325. this.upperLimitEquation.minForce = this.lowerLimitEquation.minForce = 0;
  4326. this.upperLimitEquation.maxForce = this.lowerLimitEquation.maxForce = maxForce;
  4327. /**
  4328. * Equation used for the motor.
  4329. * @property motorEquation
  4330. * @type {Equation}
  4331. */
  4332. this.motorEquation = new Equation(bodyA,bodyB);
  4333. /**
  4334. * The current motor state. Enable or disable the motor using .enableMotor
  4335. * @property motorEnabled
  4336. * @type {Boolean}
  4337. */
  4338. this.motorEnabled = false;
  4339. /**
  4340. * Set the target speed for the motor.
  4341. * @property motorSpeed
  4342. * @type {Number}
  4343. */
  4344. this.motorSpeed = 0;
  4345. var that = this;
  4346. var motorEquation = this.motorEquation;
  4347. var old = motorEquation.computeGW;
  4348. motorEquation.computeGq = function(){ return 0; };
  4349. motorEquation.computeGW = function(){
  4350. var G = this.G,
  4351. bi = this.bodyA,
  4352. bj = this.bodyB,
  4353. vi = bi.velocity,
  4354. vj = bj.velocity,
  4355. wi = bi.angularVelocity,
  4356. wj = bj.angularVelocity;
  4357. return this.gmult(G,vi,wi,vj,wj) + that.motorSpeed;
  4358. };
  4359. }
  4360. PrismaticConstraint.prototype = new Constraint();
  4361. PrismaticConstraint.prototype.constructor = PrismaticConstraint;
  4362. var worldAxisA = vec2.create(),
  4363. worldAnchorA = vec2.create(),
  4364. worldAnchorB = vec2.create(),
  4365. orientedAnchorA = vec2.create(),
  4366. orientedAnchorB = vec2.create(),
  4367. tmp = vec2.create();
  4368. /**
  4369. * Update the constraint equations. Should be done if any of the bodies changed position, before solving.
  4370. * @method update
  4371. */
  4372. PrismaticConstraint.prototype.update = function(){
  4373. var eqs = this.equations,
  4374. trans = eqs[0],
  4375. upperLimit = this.upperLimit,
  4376. lowerLimit = this.lowerLimit,
  4377. upperLimitEquation = this.upperLimitEquation,
  4378. lowerLimitEquation = this.lowerLimitEquation,
  4379. bodyA = this.bodyA,
  4380. bodyB = this.bodyB,
  4381. localAxisA = this.localAxisA,
  4382. localAnchorA = this.localAnchorA,
  4383. localAnchorB = this.localAnchorB;
  4384. trans.updateJacobian();
  4385. // Transform local things to world
  4386. vec2.rotate(worldAxisA, localAxisA, bodyA.angle);
  4387. vec2.rotate(orientedAnchorA, localAnchorA, bodyA.angle);
  4388. vec2.add(worldAnchorA, orientedAnchorA, bodyA.position);
  4389. vec2.rotate(orientedAnchorB, localAnchorB, bodyB.angle);
  4390. vec2.add(worldAnchorB, orientedAnchorB, bodyB.position);
  4391. var relPosition = this.position = vec2.dot(worldAnchorB,worldAxisA) - vec2.dot(worldAnchorA,worldAxisA);
  4392. // Motor
  4393. if(this.motorEnabled){
  4394. // G = [ a a x ri -a -a x rj ]
  4395. var G = this.motorEquation.G;
  4396. G[0] = worldAxisA[0];
  4397. G[1] = worldAxisA[1];
  4398. G[2] = vec2.crossLength(worldAxisA,orientedAnchorB);
  4399. G[3] = -worldAxisA[0];
  4400. G[4] = -worldAxisA[1];
  4401. G[5] = -vec2.crossLength(worldAxisA,orientedAnchorA);
  4402. }
  4403. /*
  4404. Limits strategy:
  4405. Add contact equation, with normal along the constraint axis.
  4406. min/maxForce is set so the constraint is repulsive in the correct direction.
  4407. Some offset is added to either equation.contactPointA or .contactPointB to get the correct upper/lower limit.
  4408. ^
  4409. |
  4410. upperLimit x
  4411. | ------
  4412. anchorB x<---| B |
  4413. | | |
  4414. ------ | ------
  4415. | | |
  4416. | A |-->x anchorA
  4417. ------ |
  4418. x lowerLimit
  4419. |
  4420. axis
  4421. */
  4422. if(this.upperLimitEnabled && relPosition > upperLimit){
  4423. // Update contact constraint normal, etc
  4424. vec2.scale(upperLimitEquation.normalA, worldAxisA, -1);
  4425. vec2.sub(upperLimitEquation.contactPointA, worldAnchorA, bodyA.position);
  4426. vec2.sub(upperLimitEquation.contactPointB, worldAnchorB, bodyB.position);
  4427. vec2.scale(tmp,worldAxisA,upperLimit);
  4428. vec2.add(upperLimitEquation.contactPointA,upperLimitEquation.contactPointA,tmp);
  4429. if(eqs.indexOf(upperLimitEquation) === -1){
  4430. eqs.push(upperLimitEquation);
  4431. }
  4432. } else {
  4433. var idx = eqs.indexOf(upperLimitEquation);
  4434. if(idx !== -1){
  4435. eqs.splice(idx,1);
  4436. }
  4437. }
  4438. if(this.lowerLimitEnabled && relPosition < lowerLimit){
  4439. // Update contact constraint normal, etc
  4440. vec2.scale(lowerLimitEquation.normalA, worldAxisA, 1);
  4441. vec2.sub(lowerLimitEquation.contactPointA, worldAnchorA, bodyA.position);
  4442. vec2.sub(lowerLimitEquation.contactPointB, worldAnchorB, bodyB.position);
  4443. vec2.scale(tmp,worldAxisA,lowerLimit);
  4444. vec2.sub(lowerLimitEquation.contactPointB,lowerLimitEquation.contactPointB,tmp);
  4445. if(eqs.indexOf(lowerLimitEquation) === -1){
  4446. eqs.push(lowerLimitEquation);
  4447. }
  4448. } else {
  4449. var idx = eqs.indexOf(lowerLimitEquation);
  4450. if(idx !== -1){
  4451. eqs.splice(idx,1);
  4452. }
  4453. }
  4454. };
  4455. /**
  4456. * Enable the motor
  4457. * @method enableMotor
  4458. */
  4459. PrismaticConstraint.prototype.enableMotor = function(){
  4460. if(this.motorEnabled){
  4461. return;
  4462. }
  4463. this.equations.push(this.motorEquation);
  4464. this.motorEnabled = true;
  4465. };
  4466. /**
  4467. * Disable the rotational motor
  4468. * @method disableMotor
  4469. */
  4470. PrismaticConstraint.prototype.disableMotor = function(){
  4471. if(!this.motorEnabled){
  4472. return;
  4473. }
  4474. var i = this.equations.indexOf(this.motorEquation);
  4475. this.equations.splice(i,1);
  4476. this.motorEnabled = false;
  4477. };
  4478. /**
  4479. * Set the constraint limits.
  4480. * @method setLimits
  4481. * @param {number} lower Lower limit.
  4482. * @param {number} upper Upper limit.
  4483. */
  4484. PrismaticConstraint.prototype.setLimits = function (lower, upper) {
  4485. if(typeof(lower) === 'number'){
  4486. this.lowerLimit = lower;
  4487. this.lowerLimitEnabled = true;
  4488. } else {
  4489. this.lowerLimit = lower;
  4490. this.lowerLimitEnabled = false;
  4491. }
  4492. if(typeof(upper) === 'number'){
  4493. this.upperLimit = upper;
  4494. this.upperLimitEnabled = true;
  4495. } else {
  4496. this.upperLimit = upper;
  4497. this.upperLimitEnabled = false;
  4498. }
  4499. };
  4500. },{"../equations/ContactEquation":21,"../equations/Equation":22,"../equations/RotationalLockEquation":24,"../math/vec2":30,"./Constraint":14}],19:[function(_dereq_,module,exports){
  4501. var Constraint = _dereq_('./Constraint')
  4502. , Equation = _dereq_('../equations/Equation')
  4503. , RotationalVelocityEquation = _dereq_('../equations/RotationalVelocityEquation')
  4504. , RotationalLockEquation = _dereq_('../equations/RotationalLockEquation')
  4505. , vec2 = _dereq_('../math/vec2');
  4506. module.exports = RevoluteConstraint;
  4507. var worldPivotA = vec2.create(),
  4508. worldPivotB = vec2.create(),
  4509. xAxis = vec2.fromValues(1,0),
  4510. yAxis = vec2.fromValues(0,1),
  4511. g = vec2.create();
  4512. /**
  4513. * Connects two bodies at given offset points, letting them rotate relative to each other around this point.
  4514. * @class RevoluteConstraint
  4515. * @constructor
  4516. * @author schteppe
  4517. * @param {Body} bodyA
  4518. * @param {Body} bodyB
  4519. * @param {Object} [options]
  4520. * @param {Array} [options.worldPivot] A pivot point given in world coordinates. If specified, localPivotA and localPivotB are automatically computed from this value.
  4521. * @param {Array} [options.localPivotA] The point relative to the center of mass of bodyA which bodyA is constrained to.
  4522. * @param {Array} [options.localPivotB] See localPivotA.
  4523. * @param {Number} [options.maxForce] The maximum force that should be applied to constrain the bodies.
  4524. * @extends Constraint
  4525. *
  4526. * @example
  4527. * // This will create a revolute constraint between two bodies with pivot point in between them.
  4528. * var bodyA = new Body({ mass: 1, position: [-1, 0] });
  4529. * var bodyB = new Body({ mass: 1, position: [1, 0] });
  4530. * var constraint = new RevoluteConstraint(bodyA, bodyB, {
  4531. * worldPivot: [0, 0]
  4532. * });
  4533. * world.addConstraint(constraint);
  4534. *
  4535. * // Using body-local pivot points, the constraint could have been constructed like this:
  4536. * var constraint = new RevoluteConstraint(bodyA, bodyB, {
  4537. * localPivotA: [1, 0],
  4538. * localPivotB: [-1, 0]
  4539. * });
  4540. */
  4541. function RevoluteConstraint(bodyA, bodyB, options){
  4542. options = options || {};
  4543. Constraint.call(this,bodyA,bodyB,Constraint.REVOLUTE,options);
  4544. var maxForce = this.maxForce = typeof(options.maxForce) !== "undefined" ? options.maxForce : Number.MAX_VALUE;
  4545. /**
  4546. * @property {Array} pivotA
  4547. */
  4548. this.pivotA = vec2.create();
  4549. /**
  4550. * @property {Array} pivotB
  4551. */
  4552. this.pivotB = vec2.create();
  4553. if(options.worldPivot){
  4554. // Compute pivotA and pivotB
  4555. vec2.sub(this.pivotA, options.worldPivot, bodyA.position);
  4556. vec2.sub(this.pivotB, options.worldPivot, bodyB.position);
  4557. // Rotate to local coordinate system
  4558. vec2.rotate(this.pivotA, this.pivotA, -bodyA.angle);
  4559. vec2.rotate(this.pivotB, this.pivotB, -bodyB.angle);
  4560. } else {
  4561. // Get pivotA and pivotB
  4562. vec2.copy(this.pivotA, options.localPivotA);
  4563. vec2.copy(this.pivotB, options.localPivotB);
  4564. }
  4565. // Equations to be fed to the solver
  4566. var eqs = this.equations = [
  4567. new Equation(bodyA,bodyB,-maxForce,maxForce),
  4568. new Equation(bodyA,bodyB,-maxForce,maxForce),
  4569. ];
  4570. var x = eqs[0];
  4571. var y = eqs[1];
  4572. var that = this;
  4573. x.computeGq = function(){
  4574. vec2.rotate(worldPivotA, that.pivotA, bodyA.angle);
  4575. vec2.rotate(worldPivotB, that.pivotB, bodyB.angle);
  4576. vec2.add(g, bodyB.position, worldPivotB);
  4577. vec2.sub(g, g, bodyA.position);
  4578. vec2.sub(g, g, worldPivotA);
  4579. return vec2.dot(g,xAxis);
  4580. };
  4581. y.computeGq = function(){
  4582. vec2.rotate(worldPivotA, that.pivotA, bodyA.angle);
  4583. vec2.rotate(worldPivotB, that.pivotB, bodyB.angle);
  4584. vec2.add(g, bodyB.position, worldPivotB);
  4585. vec2.sub(g, g, bodyA.position);
  4586. vec2.sub(g, g, worldPivotA);
  4587. return vec2.dot(g,yAxis);
  4588. };
  4589. y.minForce = x.minForce = -maxForce;
  4590. y.maxForce = x.maxForce = maxForce;
  4591. this.motorEquation = new RotationalVelocityEquation(bodyA,bodyB);
  4592. /**
  4593. * Indicates whether the motor is enabled. Use .enableMotor() to enable the constraint motor.
  4594. * @property {Boolean} motorEnabled
  4595. * @readOnly
  4596. */
  4597. this.motorEnabled = false;
  4598. /**
  4599. * The constraint position.
  4600. * @property angle
  4601. * @type {Number}
  4602. * @readOnly
  4603. */
  4604. this.angle = 0;
  4605. /**
  4606. * Set to true to enable lower limit
  4607. * @property lowerLimitEnabled
  4608. * @type {Boolean}
  4609. */
  4610. this.lowerLimitEnabled = false;
  4611. /**
  4612. * Set to true to enable upper limit
  4613. * @property upperLimitEnabled
  4614. * @type {Boolean}
  4615. */
  4616. this.upperLimitEnabled = false;
  4617. /**
  4618. * The lower limit on the constraint angle.
  4619. * @property lowerLimit
  4620. * @type {Boolean}
  4621. */
  4622. this.lowerLimit = 0;
  4623. /**
  4624. * The upper limit on the constraint angle.
  4625. * @property upperLimit
  4626. * @type {Boolean}
  4627. */
  4628. this.upperLimit = 0;
  4629. this.upperLimitEquation = new RotationalLockEquation(bodyA,bodyB);
  4630. this.lowerLimitEquation = new RotationalLockEquation(bodyA,bodyB);
  4631. this.upperLimitEquation.minForce = 0;
  4632. this.lowerLimitEquation.maxForce = 0;
  4633. }
  4634. RevoluteConstraint.prototype = new Constraint();
  4635. RevoluteConstraint.prototype.constructor = RevoluteConstraint;
  4636. /**
  4637. * Set the constraint angle limits.
  4638. * @method setLimits
  4639. * @param {number} lower Lower angle limit.
  4640. * @param {number} upper Upper angle limit.
  4641. */
  4642. RevoluteConstraint.prototype.setLimits = function (lower, upper) {
  4643. if(typeof(lower) === 'number'){
  4644. this.lowerLimit = lower;
  4645. this.lowerLimitEnabled = true;
  4646. } else {
  4647. this.lowerLimit = lower;
  4648. this.lowerLimitEnabled = false;
  4649. }
  4650. if(typeof(upper) === 'number'){
  4651. this.upperLimit = upper;
  4652. this.upperLimitEnabled = true;
  4653. } else {
  4654. this.upperLimit = upper;
  4655. this.upperLimitEnabled = false;
  4656. }
  4657. };
  4658. RevoluteConstraint.prototype.update = function(){
  4659. var bodyA = this.bodyA,
  4660. bodyB = this.bodyB,
  4661. pivotA = this.pivotA,
  4662. pivotB = this.pivotB,
  4663. eqs = this.equations,
  4664. normal = eqs[0],
  4665. tangent= eqs[1],
  4666. x = eqs[0],
  4667. y = eqs[1],
  4668. upperLimit = this.upperLimit,
  4669. lowerLimit = this.lowerLimit,
  4670. upperLimitEquation = this.upperLimitEquation,
  4671. lowerLimitEquation = this.lowerLimitEquation;
  4672. var relAngle = this.angle = bodyB.angle - bodyA.angle;
  4673. if(this.upperLimitEnabled && relAngle > upperLimit){
  4674. upperLimitEquation.angle = upperLimit;
  4675. if(eqs.indexOf(upperLimitEquation) === -1){
  4676. eqs.push(upperLimitEquation);
  4677. }
  4678. } else {
  4679. var idx = eqs.indexOf(upperLimitEquation);
  4680. if(idx !== -1){
  4681. eqs.splice(idx,1);
  4682. }
  4683. }
  4684. if(this.lowerLimitEnabled && relAngle < lowerLimit){
  4685. lowerLimitEquation.angle = lowerLimit;
  4686. if(eqs.indexOf(lowerLimitEquation) === -1){
  4687. eqs.push(lowerLimitEquation);
  4688. }
  4689. } else {
  4690. var idx = eqs.indexOf(lowerLimitEquation);
  4691. if(idx !== -1){
  4692. eqs.splice(idx,1);
  4693. }
  4694. }
  4695. /*
  4696. The constraint violation is
  4697. g = xj + rj - xi - ri
  4698. ...where xi and xj are the body positions and ri and rj world-oriented offset vectors. Differentiate:
  4699. gdot = vj + wj x rj - vi - wi x ri
  4700. We split this into x and y directions. (let x and y be unit vectors along the respective axes)
  4701. gdot * x = ( vj + wj x rj - vi - wi x ri ) * x
  4702. = ( vj*x + (wj x rj)*x -vi*x -(wi x ri)*x
  4703. = ( vj*x + (rj x x)*wj -vi*x -(ri x x)*wi
  4704. = [ -x -(ri x x) x (rj x x)] * [vi wi vj wj]
  4705. = G*W
  4706. ...and similar for y. We have then identified the jacobian entries for x and y directions:
  4707. Gx = [ x (rj x x) -x -(ri x x)]
  4708. Gy = [ y (rj x y) -y -(ri x y)]
  4709. */
  4710. vec2.rotate(worldPivotA, pivotA, bodyA.angle);
  4711. vec2.rotate(worldPivotB, pivotB, bodyB.angle);
  4712. // todo: these are a bit sparse. We could save some computations on making custom eq.computeGW functions, etc
  4713. x.G[0] = -1;
  4714. x.G[1] = 0;
  4715. x.G[2] = -vec2.crossLength(worldPivotA,xAxis);
  4716. x.G[3] = 1;
  4717. x.G[4] = 0;
  4718. x.G[5] = vec2.crossLength(worldPivotB,xAxis);
  4719. y.G[0] = 0;
  4720. y.G[1] = -1;
  4721. y.G[2] = -vec2.crossLength(worldPivotA,yAxis);
  4722. y.G[3] = 0;
  4723. y.G[4] = 1;
  4724. y.G[5] = vec2.crossLength(worldPivotB,yAxis);
  4725. };
  4726. /**
  4727. * Enable the rotational motor
  4728. * @method enableMotor
  4729. */
  4730. RevoluteConstraint.prototype.enableMotor = function(){
  4731. if(this.motorEnabled){
  4732. return;
  4733. }
  4734. this.equations.push(this.motorEquation);
  4735. this.motorEnabled = true;
  4736. };
  4737. /**
  4738. * Disable the rotational motor
  4739. * @method disableMotor
  4740. */
  4741. RevoluteConstraint.prototype.disableMotor = function(){
  4742. if(!this.motorEnabled){
  4743. return;
  4744. }
  4745. var i = this.equations.indexOf(this.motorEquation);
  4746. this.equations.splice(i,1);
  4747. this.motorEnabled = false;
  4748. };
  4749. /**
  4750. * Check if the motor is enabled.
  4751. * @method motorIsEnabled
  4752. * @deprecated use property motorEnabled instead.
  4753. * @return {Boolean}
  4754. */
  4755. RevoluteConstraint.prototype.motorIsEnabled = function(){
  4756. return !!this.motorEnabled;
  4757. };
  4758. /**
  4759. * Set the speed of the rotational constraint motor
  4760. * @method setMotorSpeed
  4761. * @param {Number} speed
  4762. */
  4763. RevoluteConstraint.prototype.setMotorSpeed = function(speed){
  4764. if(!this.motorEnabled){
  4765. return;
  4766. }
  4767. var i = this.equations.indexOf(this.motorEquation);
  4768. this.equations[i].relativeVelocity = speed;
  4769. };
  4770. /**
  4771. * Get the speed of the rotational constraint motor
  4772. * @method getMotorSpeed
  4773. * @return {Number} The current speed, or false if the motor is not enabled.
  4774. */
  4775. RevoluteConstraint.prototype.getMotorSpeed = function(){
  4776. if(!this.motorEnabled){
  4777. return false;
  4778. }
  4779. return this.motorEquation.relativeVelocity;
  4780. };
  4781. },{"../equations/Equation":22,"../equations/RotationalLockEquation":24,"../equations/RotationalVelocityEquation":25,"../math/vec2":30,"./Constraint":14}],20:[function(_dereq_,module,exports){
  4782. var Equation = _dereq_("./Equation"),
  4783. vec2 = _dereq_('../math/vec2');
  4784. module.exports = AngleLockEquation;
  4785. /**
  4786. * Locks the relative angle between two bodies. The constraint tries to keep the dot product between two vectors, local in each body, to zero. The local angle in body i is a parameter.
  4787. *
  4788. * @class AngleLockEquation
  4789. * @constructor
  4790. * @extends Equation
  4791. * @param {Body} bodyA
  4792. * @param {Body} bodyB
  4793. * @param {Object} [options]
  4794. * @param {Number} [options.angle] Angle to add to the local vector in body A.
  4795. * @param {Number} [options.ratio] Gear ratio
  4796. */
  4797. function AngleLockEquation(bodyA, bodyB, options){
  4798. options = options || {};
  4799. Equation.call(this,bodyA,bodyB,-Number.MAX_VALUE,Number.MAX_VALUE);
  4800. this.angle = options.angle || 0;
  4801. /**
  4802. * The gear ratio.
  4803. * @property {Number} ratio
  4804. * @private
  4805. * @see setRatio
  4806. */
  4807. this.ratio = typeof(options.ratio)==="number" ? options.ratio : 1;
  4808. this.setRatio(this.ratio);
  4809. }
  4810. AngleLockEquation.prototype = new Equation();
  4811. AngleLockEquation.prototype.constructor = AngleLockEquation;
  4812. AngleLockEquation.prototype.computeGq = function(){
  4813. return this.ratio * this.bodyA.angle - this.bodyB.angle + this.angle;
  4814. };
  4815. /**
  4816. * Set the gear ratio for this equation
  4817. * @method setRatio
  4818. * @param {Number} ratio
  4819. */
  4820. AngleLockEquation.prototype.setRatio = function(ratio){
  4821. var G = this.G;
  4822. G[2] = ratio;
  4823. G[5] = -1;
  4824. this.ratio = ratio;
  4825. };
  4826. /**
  4827. * Set the max force for the equation.
  4828. * @method setMaxTorque
  4829. * @param {Number} torque
  4830. */
  4831. AngleLockEquation.prototype.setMaxTorque = function(torque){
  4832. this.maxForce = torque;
  4833. this.minForce = -torque;
  4834. };
  4835. },{"../math/vec2":30,"./Equation":22}],21:[function(_dereq_,module,exports){
  4836. var Equation = _dereq_("./Equation"),
  4837. vec2 = _dereq_('../math/vec2');
  4838. module.exports = ContactEquation;
  4839. /**
  4840. * Non-penetration constraint equation. Tries to make the contactPointA and contactPointB vectors coincide, while keeping the applied force repulsive.
  4841. *
  4842. * @class ContactEquation
  4843. * @constructor
  4844. * @extends Equation
  4845. * @param {Body} bodyA
  4846. * @param {Body} bodyB
  4847. */
  4848. function ContactEquation(bodyA, bodyB){
  4849. Equation.call(this, bodyA, bodyB, 0, Number.MAX_VALUE);
  4850. /**
  4851. * Vector from body i center of mass to the contact point.
  4852. * @property contactPointA
  4853. * @type {Array}
  4854. */
  4855. this.contactPointA = vec2.create();
  4856. this.penetrationVec = vec2.create();
  4857. /**
  4858. * World-oriented vector from body A center of mass to the contact point.
  4859. * @property contactPointB
  4860. * @type {Array}
  4861. */
  4862. this.contactPointB = vec2.create();
  4863. /**
  4864. * The normal vector, pointing out of body i
  4865. * @property normalA
  4866. * @type {Array}
  4867. */
  4868. this.normalA = vec2.create();
  4869. /**
  4870. * The restitution to use (0=no bounciness, 1=max bounciness).
  4871. * @property restitution
  4872. * @type {Number}
  4873. */
  4874. this.restitution = 0;
  4875. /**
  4876. * This property is set to true if this is the first impact between the bodies (not persistant contact).
  4877. * @property firstImpact
  4878. * @type {Boolean}
  4879. * @readOnly
  4880. */
  4881. this.firstImpact = false;
  4882. /**
  4883. * The shape in body i that triggered this contact.
  4884. * @property shapeA
  4885. * @type {Shape}
  4886. */
  4887. this.shapeA = null;
  4888. /**
  4889. * The shape in body j that triggered this contact.
  4890. * @property shapeB
  4891. * @type {Shape}
  4892. */
  4893. this.shapeB = null;
  4894. }
  4895. ContactEquation.prototype = new Equation();
  4896. ContactEquation.prototype.constructor = ContactEquation;
  4897. ContactEquation.prototype.computeB = function(a,b,h){
  4898. var bi = this.bodyA,
  4899. bj = this.bodyB,
  4900. ri = this.contactPointA,
  4901. rj = this.contactPointB,
  4902. xi = bi.position,
  4903. xj = bj.position;
  4904. var penetrationVec = this.penetrationVec,
  4905. n = this.normalA,
  4906. G = this.G;
  4907. // Caluclate cross products
  4908. var rixn = vec2.crossLength(ri,n),
  4909. rjxn = vec2.crossLength(rj,n);
  4910. // G = [-n -rixn n rjxn]
  4911. G[0] = -n[0];
  4912. G[1] = -n[1];
  4913. G[2] = -rixn;
  4914. G[3] = n[0];
  4915. G[4] = n[1];
  4916. G[5] = rjxn;
  4917. // Calculate q = xj+rj -(xi+ri) i.e. the penetration vector
  4918. vec2.add(penetrationVec,xj,rj);
  4919. vec2.sub(penetrationVec,penetrationVec,xi);
  4920. vec2.sub(penetrationVec,penetrationVec,ri);
  4921. // Compute iteration
  4922. var GW, Gq;
  4923. if(this.firstImpact && this.restitution !== 0){
  4924. Gq = 0;
  4925. GW = (1/b)*(1+this.restitution) * this.computeGW();
  4926. } else {
  4927. Gq = vec2.dot(n,penetrationVec) + this.offset;
  4928. GW = this.computeGW();
  4929. }
  4930. var GiMf = this.computeGiMf();
  4931. var B = - Gq * a - GW * b - h*GiMf;
  4932. return B;
  4933. };
  4934. },{"../math/vec2":30,"./Equation":22}],22:[function(_dereq_,module,exports){
  4935. module.exports = Equation;
  4936. var vec2 = _dereq_('../math/vec2'),
  4937. Utils = _dereq_('../utils/Utils'),
  4938. Body = _dereq_('../objects/Body');
  4939. /**
  4940. * Base class for constraint equations.
  4941. * @class Equation
  4942. * @constructor
  4943. * @param {Body} bodyA First body participating in the equation
  4944. * @param {Body} bodyB Second body participating in the equation
  4945. * @param {number} minForce Minimum force to apply. Default: -Number.MAX_VALUE
  4946. * @param {number} maxForce Maximum force to apply. Default: Number.MAX_VALUE
  4947. */
  4948. function Equation(bodyA, bodyB, minForce, maxForce){
  4949. /**
  4950. * Minimum force to apply when solving.
  4951. * @property minForce
  4952. * @type {Number}
  4953. */
  4954. this.minForce = typeof(minForce)==="undefined" ? -Number.MAX_VALUE : minForce;
  4955. /**
  4956. * Max force to apply when solving.
  4957. * @property maxForce
  4958. * @type {Number}
  4959. */
  4960. this.maxForce = typeof(maxForce)==="undefined" ? Number.MAX_VALUE : maxForce;
  4961. /**
  4962. * First body participating in the constraint
  4963. * @property bodyA
  4964. * @type {Body}
  4965. */
  4966. this.bodyA = bodyA;
  4967. /**
  4968. * Second body participating in the constraint
  4969. * @property bodyB
  4970. * @type {Body}
  4971. */
  4972. this.bodyB = bodyB;
  4973. /**
  4974. * The stiffness of this equation. Typically chosen to a large number (~1e7), but can be chosen somewhat freely to get a stable simulation.
  4975. * @property stiffness
  4976. * @type {Number}
  4977. */
  4978. this.stiffness = Equation.DEFAULT_STIFFNESS;
  4979. /**
  4980. * The number of time steps needed to stabilize the constraint equation. Typically between 3 and 5 time steps.
  4981. * @property relaxation
  4982. * @type {Number}
  4983. */
  4984. this.relaxation = Equation.DEFAULT_RELAXATION;
  4985. /**
  4986. * The Jacobian entry of this equation. 6 numbers, 3 per body (x,y,angle).
  4987. * @property G
  4988. * @type {Array}
  4989. */
  4990. this.G = new Utils.ARRAY_TYPE(6);
  4991. for(var i=0; i<6; i++){
  4992. this.G[i]=0;
  4993. }
  4994. this.offset = 0;
  4995. this.a = 0;
  4996. this.b = 0;
  4997. this.epsilon = 0;
  4998. this.timeStep = 1/60;
  4999. /**
  5000. * Indicates if stiffness or relaxation was changed.
  5001. * @property {Boolean} needsUpdate
  5002. */
  5003. this.needsUpdate = true;
  5004. /**
  5005. * The resulting constraint multiplier from the last solve. This is mostly equivalent to the force produced by the constraint.
  5006. * @property multiplier
  5007. * @type {Number}
  5008. */
  5009. this.multiplier = 0;
  5010. /**
  5011. * Relative velocity.
  5012. * @property {Number} relativeVelocity
  5013. */
  5014. this.relativeVelocity = 0;
  5015. /**
  5016. * Whether this equation is enabled or not. If true, it will be added to the solver.
  5017. * @property {Boolean} enabled
  5018. */
  5019. this.enabled = true;
  5020. }
  5021. Equation.prototype.constructor = Equation;
  5022. /**
  5023. * The default stiffness when creating a new Equation.
  5024. * @static
  5025. * @property {Number} DEFAULT_STIFFNESS
  5026. * @default 1e6
  5027. */
  5028. Equation.DEFAULT_STIFFNESS = 1e6;
  5029. /**
  5030. * The default relaxation when creating a new Equation.
  5031. * @static
  5032. * @property {Number} DEFAULT_RELAXATION
  5033. * @default 4
  5034. */
  5035. Equation.DEFAULT_RELAXATION = 4;
  5036. /**
  5037. * Compute SPOOK parameters .a, .b and .epsilon according to the current parameters. See equations 9, 10 and 11 in the <a href="http://www8.cs.umu.se/kurser/5DV058/VT09/lectures/spooknotes.pdf">SPOOK notes</a>.
  5038. * @method update
  5039. */
  5040. Equation.prototype.update = function(){
  5041. var k = this.stiffness,
  5042. d = this.relaxation,
  5043. h = this.timeStep;
  5044. this.a = 4.0 / (h * (1 + 4 * d));
  5045. this.b = (4.0 * d) / (1 + 4 * d);
  5046. this.epsilon = 4.0 / (h * h * k * (1 + 4 * d));
  5047. this.needsUpdate = false;
  5048. };
  5049. /**
  5050. * Multiply a jacobian entry with corresponding positions or velocities
  5051. * @method gmult
  5052. * @return {Number}
  5053. */
  5054. Equation.prototype.gmult = function(G,vi,wi,vj,wj){
  5055. return G[0] * vi[0] +
  5056. G[1] * vi[1] +
  5057. G[2] * wi +
  5058. G[3] * vj[0] +
  5059. G[4] * vj[1] +
  5060. G[5] * wj;
  5061. };
  5062. /**
  5063. * Computes the RHS of the SPOOK equation
  5064. * @method computeB
  5065. * @return {Number}
  5066. */
  5067. Equation.prototype.computeB = function(a,b,h){
  5068. var GW = this.computeGW();
  5069. var Gq = this.computeGq();
  5070. var GiMf = this.computeGiMf();
  5071. return - Gq * a - GW * b - GiMf*h;
  5072. };
  5073. /**
  5074. * Computes G\*q, where q are the generalized body coordinates
  5075. * @method computeGq
  5076. * @return {Number}
  5077. */
  5078. var qi = vec2.create(),
  5079. qj = vec2.create();
  5080. Equation.prototype.computeGq = function(){
  5081. var G = this.G,
  5082. bi = this.bodyA,
  5083. bj = this.bodyB,
  5084. xi = bi.position,
  5085. xj = bj.position,
  5086. ai = bi.angle,
  5087. aj = bj.angle;
  5088. return this.gmult(G, qi, ai, qj, aj) + this.offset;
  5089. };
  5090. /**
  5091. * Computes G\*W, where W are the body velocities
  5092. * @method computeGW
  5093. * @return {Number}
  5094. */
  5095. Equation.prototype.computeGW = function(){
  5096. var G = this.G,
  5097. bi = this.bodyA,
  5098. bj = this.bodyB,
  5099. vi = bi.velocity,
  5100. vj = bj.velocity,
  5101. wi = bi.angularVelocity,
  5102. wj = bj.angularVelocity;
  5103. return this.gmult(G,vi,wi,vj,wj) + this.relativeVelocity;
  5104. };
  5105. /**
  5106. * Computes G\*Wlambda, where W are the body velocities
  5107. * @method computeGWlambda
  5108. * @return {Number}
  5109. */
  5110. Equation.prototype.computeGWlambda = function(){
  5111. var G = this.G,
  5112. bi = this.bodyA,
  5113. bj = this.bodyB,
  5114. vi = bi.vlambda,
  5115. vj = bj.vlambda,
  5116. wi = bi.wlambda,
  5117. wj = bj.wlambda;
  5118. return this.gmult(G,vi,wi,vj,wj);
  5119. };
  5120. /**
  5121. * Computes G\*inv(M)\*f, where M is the mass matrix with diagonal blocks for each body, and f are the forces on the bodies.
  5122. * @method computeGiMf
  5123. * @return {Number}
  5124. */
  5125. var iMfi = vec2.create(),
  5126. iMfj = vec2.create();
  5127. Equation.prototype.computeGiMf = function(){
  5128. var bi = this.bodyA,
  5129. bj = this.bodyB,
  5130. fi = bi.force,
  5131. ti = bi.angularForce,
  5132. fj = bj.force,
  5133. tj = bj.angularForce,
  5134. invMassi = bi.invMassSolve,
  5135. invMassj = bj.invMassSolve,
  5136. invIi = bi.invInertiaSolve,
  5137. invIj = bj.invInertiaSolve,
  5138. G = this.G;
  5139. vec2.scale(iMfi, fi, invMassi);
  5140. vec2.multiply(iMfi, bi.massMultiplier, iMfi);
  5141. vec2.scale(iMfj, fj,invMassj);
  5142. vec2.multiply(iMfj, bj.massMultiplier, iMfj);
  5143. return this.gmult(G,iMfi,ti*invIi,iMfj,tj*invIj);
  5144. };
  5145. /**
  5146. * Computes G\*inv(M)\*G'
  5147. * @method computeGiMGt
  5148. * @return {Number}
  5149. */
  5150. Equation.prototype.computeGiMGt = function(){
  5151. var bi = this.bodyA,
  5152. bj = this.bodyB,
  5153. invMassi = bi.invMassSolve,
  5154. invMassj = bj.invMassSolve,
  5155. invIi = bi.invInertiaSolve,
  5156. invIj = bj.invInertiaSolve,
  5157. G = this.G;
  5158. return G[0] * G[0] * invMassi * bi.massMultiplier[0] +
  5159. G[1] * G[1] * invMassi * bi.massMultiplier[1] +
  5160. G[2] * G[2] * invIi +
  5161. G[3] * G[3] * invMassj * bj.massMultiplier[0] +
  5162. G[4] * G[4] * invMassj * bj.massMultiplier[1] +
  5163. G[5] * G[5] * invIj;
  5164. };
  5165. var addToWlambda_temp = vec2.create(),
  5166. addToWlambda_Gi = vec2.create(),
  5167. addToWlambda_Gj = vec2.create(),
  5168. addToWlambda_ri = vec2.create(),
  5169. addToWlambda_rj = vec2.create(),
  5170. addToWlambda_Mdiag = vec2.create();
  5171. /**
  5172. * Add constraint velocity to the bodies.
  5173. * @method addToWlambda
  5174. * @param {Number} deltalambda
  5175. */
  5176. Equation.prototype.addToWlambda = function(deltalambda){
  5177. var bi = this.bodyA,
  5178. bj = this.bodyB,
  5179. temp = addToWlambda_temp,
  5180. Gi = addToWlambda_Gi,
  5181. Gj = addToWlambda_Gj,
  5182. ri = addToWlambda_ri,
  5183. rj = addToWlambda_rj,
  5184. invMassi = bi.invMassSolve,
  5185. invMassj = bj.invMassSolve,
  5186. invIi = bi.invInertiaSolve,
  5187. invIj = bj.invInertiaSolve,
  5188. Mdiag = addToWlambda_Mdiag,
  5189. G = this.G;
  5190. Gi[0] = G[0];
  5191. Gi[1] = G[1];
  5192. Gj[0] = G[3];
  5193. Gj[1] = G[4];
  5194. // Add to linear velocity
  5195. // v_lambda += inv(M) * delta_lamba * G
  5196. vec2.scale(temp, Gi, invMassi*deltalambda);
  5197. vec2.multiply(temp, temp, bi.massMultiplier);
  5198. vec2.add( bi.vlambda, bi.vlambda, temp);
  5199. // This impulse is in the offset frame
  5200. // Also add contribution to angular
  5201. //bi.wlambda -= vec2.crossLength(temp,ri);
  5202. bi.wlambda += invIi * G[2] * deltalambda;
  5203. vec2.scale(temp, Gj, invMassj*deltalambda);
  5204. vec2.multiply(temp, temp, bj.massMultiplier);
  5205. vec2.add( bj.vlambda, bj.vlambda, temp);
  5206. //bj.wlambda -= vec2.crossLength(temp,rj);
  5207. bj.wlambda += invIj * G[5] * deltalambda;
  5208. };
  5209. /**
  5210. * Compute the denominator part of the SPOOK equation: C = G\*inv(M)\*G' + eps
  5211. * @method computeInvC
  5212. * @param {Number} eps
  5213. * @return {Number}
  5214. */
  5215. Equation.prototype.computeInvC = function(eps){
  5216. return 1.0 / (this.computeGiMGt() + eps);
  5217. };
  5218. },{"../math/vec2":30,"../objects/Body":31,"../utils/Utils":57}],23:[function(_dereq_,module,exports){
  5219. var vec2 = _dereq_('../math/vec2')
  5220. , Equation = _dereq_('./Equation')
  5221. , Utils = _dereq_('../utils/Utils');
  5222. module.exports = FrictionEquation;
  5223. /**
  5224. * Constrains the slipping in a contact along a tangent
  5225. *
  5226. * @class FrictionEquation
  5227. * @constructor
  5228. * @param {Body} bodyA
  5229. * @param {Body} bodyB
  5230. * @param {Number} slipForce
  5231. * @extends Equation
  5232. */
  5233. function FrictionEquation(bodyA, bodyB, slipForce){
  5234. Equation.call(this, bodyA, bodyB, -slipForce, slipForce);
  5235. /**
  5236. * Relative vector from center of body A to the contact point, world oriented.
  5237. * @property contactPointA
  5238. * @type {Array}
  5239. */
  5240. this.contactPointA = vec2.create();
  5241. /**
  5242. * Relative vector from center of body B to the contact point, world oriented.
  5243. * @property contactPointB
  5244. * @type {Array}
  5245. */
  5246. this.contactPointB = vec2.create();
  5247. /**
  5248. * Tangent vector that the friction force will act along. World oriented.
  5249. * @property t
  5250. * @type {Array}
  5251. */
  5252. this.t = vec2.create();
  5253. /**
  5254. * ContactEquations connected to this friction equation. The contact equations can be used to rescale the max force for the friction. If more than one contact equation is given, then the max force can be set to the average.
  5255. * @property contactEquations
  5256. * @type {ContactEquation}
  5257. */
  5258. this.contactEquations = [];
  5259. /**
  5260. * The shape in body i that triggered this friction.
  5261. * @property shapeA
  5262. * @type {Shape}
  5263. * @todo Needed? The shape can be looked up via contactEquation.shapeA...
  5264. */
  5265. this.shapeA = null;
  5266. /**
  5267. * The shape in body j that triggered this friction.
  5268. * @property shapeB
  5269. * @type {Shape}
  5270. * @todo Needed? The shape can be looked up via contactEquation.shapeB...
  5271. */
  5272. this.shapeB = null;
  5273. /**
  5274. * The friction coefficient to use.
  5275. * @property frictionCoefficient
  5276. * @type {Number}
  5277. */
  5278. this.frictionCoefficient = 0.3;
  5279. }
  5280. FrictionEquation.prototype = new Equation();
  5281. FrictionEquation.prototype.constructor = FrictionEquation;
  5282. /**
  5283. * Set the slipping condition for the constraint. The friction force cannot be
  5284. * larger than this value.
  5285. * @method setSlipForce
  5286. * @param {Number} slipForce
  5287. */
  5288. FrictionEquation.prototype.setSlipForce = function(slipForce){
  5289. this.maxForce = slipForce;
  5290. this.minForce = -slipForce;
  5291. };
  5292. /**
  5293. * Get the max force for the constraint.
  5294. * @method getSlipForce
  5295. * @return {Number}
  5296. */
  5297. FrictionEquation.prototype.getSlipForce = function(){
  5298. return this.maxForce;
  5299. };
  5300. FrictionEquation.prototype.computeB = function(a,b,h){
  5301. var bi = this.bodyA,
  5302. bj = this.bodyB,
  5303. ri = this.contactPointA,
  5304. rj = this.contactPointB,
  5305. t = this.t,
  5306. G = this.G;
  5307. // G = [-t -rixt t rjxt]
  5308. // And remember, this is a pure velocity constraint, g is always zero!
  5309. G[0] = -t[0];
  5310. G[1] = -t[1];
  5311. G[2] = -vec2.crossLength(ri,t);
  5312. G[3] = t[0];
  5313. G[4] = t[1];
  5314. G[5] = vec2.crossLength(rj,t);
  5315. var GW = this.computeGW(),
  5316. GiMf = this.computeGiMf();
  5317. var B = /* - g * a */ - GW * b - h*GiMf;
  5318. return B;
  5319. };
  5320. },{"../math/vec2":30,"../utils/Utils":57,"./Equation":22}],24:[function(_dereq_,module,exports){
  5321. var Equation = _dereq_("./Equation"),
  5322. vec2 = _dereq_('../math/vec2');
  5323. module.exports = RotationalLockEquation;
  5324. /**
  5325. * Locks the relative angle between two bodies. The constraint tries to keep the dot product between two vectors, local in each body, to zero. The local angle in body i is a parameter.
  5326. *
  5327. * @class RotationalLockEquation
  5328. * @constructor
  5329. * @extends Equation
  5330. * @param {Body} bodyA
  5331. * @param {Body} bodyB
  5332. * @param {Object} [options]
  5333. * @param {Number} [options.angle] Angle to add to the local vector in bodyA.
  5334. */
  5335. function RotationalLockEquation(bodyA, bodyB, options){
  5336. options = options || {};
  5337. Equation.call(this, bodyA, bodyB, -Number.MAX_VALUE, Number.MAX_VALUE);
  5338. /**
  5339. * @property {number} angle
  5340. */
  5341. this.angle = options.angle || 0;
  5342. var G = this.G;
  5343. G[2] = 1;
  5344. G[5] = -1;
  5345. }
  5346. RotationalLockEquation.prototype = new Equation();
  5347. RotationalLockEquation.prototype.constructor = RotationalLockEquation;
  5348. var worldVectorA = vec2.create(),
  5349. worldVectorB = vec2.create(),
  5350. xAxis = vec2.fromValues(1,0),
  5351. yAxis = vec2.fromValues(0,1);
  5352. RotationalLockEquation.prototype.computeGq = function(){
  5353. vec2.rotate(worldVectorA,xAxis,this.bodyA.angle+this.angle);
  5354. vec2.rotate(worldVectorB,yAxis,this.bodyB.angle);
  5355. return vec2.dot(worldVectorA,worldVectorB);
  5356. };
  5357. },{"../math/vec2":30,"./Equation":22}],25:[function(_dereq_,module,exports){
  5358. var Equation = _dereq_("./Equation"),
  5359. vec2 = _dereq_('../math/vec2');
  5360. module.exports = RotationalVelocityEquation;
  5361. /**
  5362. * Syncs rotational velocity of two bodies, or sets a relative velocity (motor).
  5363. *
  5364. * @class RotationalVelocityEquation
  5365. * @constructor
  5366. * @extends Equation
  5367. * @param {Body} bodyA
  5368. * @param {Body} bodyB
  5369. */
  5370. function RotationalVelocityEquation(bodyA, bodyB){
  5371. Equation.call(this, bodyA, bodyB, -Number.MAX_VALUE, Number.MAX_VALUE);
  5372. this.relativeVelocity = 1;
  5373. this.ratio = 1;
  5374. }
  5375. RotationalVelocityEquation.prototype = new Equation();
  5376. RotationalVelocityEquation.prototype.constructor = RotationalVelocityEquation;
  5377. RotationalVelocityEquation.prototype.computeB = function(a,b,h){
  5378. var G = this.G;
  5379. G[2] = -1;
  5380. G[5] = this.ratio;
  5381. var GiMf = this.computeGiMf();
  5382. var GW = this.computeGW();
  5383. var B = - GW * b - h*GiMf;
  5384. return B;
  5385. };
  5386. },{"../math/vec2":30,"./Equation":22}],26:[function(_dereq_,module,exports){
  5387. /**
  5388. * Base class for objects that dispatches events.
  5389. * @class EventEmitter
  5390. * @constructor
  5391. */
  5392. var EventEmitter = function () {};
  5393. module.exports = EventEmitter;
  5394. EventEmitter.prototype = {
  5395. constructor: EventEmitter,
  5396. /**
  5397. * Add an event listener
  5398. * @method on
  5399. * @param {String} type
  5400. * @param {Function} listener
  5401. * @return {EventEmitter} The self object, for chainability.
  5402. */
  5403. on: function ( type, listener, context ) {
  5404. listener.context = context || this;
  5405. if ( this._listeners === undefined ){
  5406. this._listeners = {};
  5407. }
  5408. var listeners = this._listeners;
  5409. if ( listeners[ type ] === undefined ) {
  5410. listeners[ type ] = [];
  5411. }
  5412. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  5413. listeners[ type ].push( listener );
  5414. }
  5415. return this;
  5416. },
  5417. /**
  5418. * Check if an event listener is added
  5419. * @method has
  5420. * @param {String} type
  5421. * @param {Function} listener
  5422. * @return {Boolean}
  5423. */
  5424. has: function ( type, listener ) {
  5425. if ( this._listeners === undefined ){
  5426. return false;
  5427. }
  5428. var listeners = this._listeners;
  5429. if(listener){
  5430. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  5431. return true;
  5432. }
  5433. } else {
  5434. if ( listeners[ type ] !== undefined ) {
  5435. return true;
  5436. }
  5437. }
  5438. return false;
  5439. },
  5440. /**
  5441. * Remove an event listener
  5442. * @method off
  5443. * @param {String} type
  5444. * @param {Function} listener
  5445. * @return {EventEmitter} The self object, for chainability.
  5446. */
  5447. off: function ( type, listener ) {
  5448. if ( this._listeners === undefined ){
  5449. return this;
  5450. }
  5451. var listeners = this._listeners;
  5452. var index = listeners[ type ].indexOf( listener );
  5453. if ( index !== - 1 ) {
  5454. listeners[ type ].splice( index, 1 );
  5455. }
  5456. return this;
  5457. },
  5458. /**
  5459. * Emit an event.
  5460. * @method emit
  5461. * @param {Object} event
  5462. * @param {String} event.type
  5463. * @return {EventEmitter} The self object, for chainability.
  5464. */
  5465. emit: function ( event ) {
  5466. if ( this._listeners === undefined ){
  5467. return this;
  5468. }
  5469. var listeners = this._listeners;
  5470. var listenerArray = listeners[ event.type ];
  5471. if ( listenerArray !== undefined ) {
  5472. event.target = this;
  5473. for ( var i = 0, l = listenerArray.length; i < l; i ++ ) {
  5474. var listener = listenerArray[ i ];
  5475. listener.call( listener.context, event );
  5476. }
  5477. }
  5478. return this;
  5479. }
  5480. };
  5481. },{}],27:[function(_dereq_,module,exports){
  5482. var Material = _dereq_('./Material');
  5483. var Equation = _dereq_('../equations/Equation');
  5484. module.exports = ContactMaterial;
  5485. /**
  5486. * Defines what happens when two materials meet, such as what friction coefficient to use. You can also set other things such as restitution, surface velocity and constraint parameters.
  5487. * @class ContactMaterial
  5488. * @constructor
  5489. * @param {Material} materialA
  5490. * @param {Material} materialB
  5491. * @param {Object} [options]
  5492. * @param {Number} [options.friction=0.3] Friction coefficient.
  5493. * @param {Number} [options.restitution=0] Restitution coefficient aka "bounciness".
  5494. * @param {Number} [options.stiffness] ContactEquation stiffness.
  5495. * @param {Number} [options.relaxation] ContactEquation relaxation.
  5496. * @param {Number} [options.frictionStiffness] FrictionEquation stiffness.
  5497. * @param {Number} [options.frictionRelaxation] FrictionEquation relaxation.
  5498. * @param {Number} [options.surfaceVelocity=0] Surface velocity.
  5499. * @author schteppe
  5500. */
  5501. function ContactMaterial(materialA, materialB, options){
  5502. options = options || {};
  5503. if(!(materialA instanceof Material) || !(materialB instanceof Material)){
  5504. throw new Error("First two arguments must be Material instances.");
  5505. }
  5506. /**
  5507. * The contact material identifier
  5508. * @property id
  5509. * @type {Number}
  5510. */
  5511. this.id = ContactMaterial.idCounter++;
  5512. /**
  5513. * First material participating in the contact material
  5514. * @property materialA
  5515. * @type {Material}
  5516. */
  5517. this.materialA = materialA;
  5518. /**
  5519. * Second material participating in the contact material
  5520. * @property materialB
  5521. * @type {Material}
  5522. */
  5523. this.materialB = materialB;
  5524. /**
  5525. * Friction to use in the contact of these two materials
  5526. * @property friction
  5527. * @type {Number}
  5528. */
  5529. this.friction = typeof(options.friction) !== "undefined" ? Number(options.friction) : 0.3;
  5530. /**
  5531. * Restitution to use in the contact of these two materials
  5532. * @property restitution
  5533. * @type {Number}
  5534. */
  5535. this.restitution = typeof(options.restitution) !== "undefined" ? Number(options.restitution) : 0.0;
  5536. /**
  5537. * Stiffness of the resulting ContactEquation that this ContactMaterial generate
  5538. * @property stiffness
  5539. * @type {Number}
  5540. */
  5541. this.stiffness = typeof(options.stiffness) !== "undefined" ? Number(options.stiffness) : Equation.DEFAULT_STIFFNESS;
  5542. /**
  5543. * Relaxation of the resulting ContactEquation that this ContactMaterial generate
  5544. * @property relaxation
  5545. * @type {Number}
  5546. */
  5547. this.relaxation = typeof(options.relaxation) !== "undefined" ? Number(options.relaxation) : Equation.DEFAULT_RELAXATION;
  5548. /**
  5549. * Stiffness of the resulting FrictionEquation that this ContactMaterial generate
  5550. * @property frictionStiffness
  5551. * @type {Number}
  5552. */
  5553. this.frictionStiffness = typeof(options.frictionStiffness) !== "undefined" ? Number(options.frictionStiffness) : Equation.DEFAULT_STIFFNESS;
  5554. /**
  5555. * Relaxation of the resulting FrictionEquation that this ContactMaterial generate
  5556. * @property frictionRelaxation
  5557. * @type {Number}
  5558. */
  5559. this.frictionRelaxation = typeof(options.frictionRelaxation) !== "undefined" ? Number(options.frictionRelaxation) : Equation.DEFAULT_RELAXATION;
  5560. /**
  5561. * Will add surface velocity to this material. If bodyA rests on top if bodyB, and the surface velocity is positive, bodyA will slide to the right.
  5562. * @property {Number} surfaceVelocity
  5563. */
  5564. this.surfaceVelocity = typeof(options.surfaceVelocity) !== "undefined" ? Number(options.surfaceVelocity) : 0;
  5565. /**
  5566. * Offset to be set on ContactEquations. A positive value will make the bodies penetrate more into each other. Can be useful in scenes where contacts need to be more persistent, for example when stacking. Aka "cure for nervous contacts".
  5567. * @property contactSkinSize
  5568. * @type {Number}
  5569. */
  5570. this.contactSkinSize = 0.005;
  5571. }
  5572. ContactMaterial.idCounter = 0;
  5573. },{"../equations/Equation":22,"./Material":28}],28:[function(_dereq_,module,exports){
  5574. module.exports = Material;
  5575. /**
  5576. * Defines a physics material.
  5577. * @class Material
  5578. * @constructor
  5579. * @param {number} id Material identifier
  5580. * @author schteppe
  5581. */
  5582. function Material(id){
  5583. /**
  5584. * The material identifier
  5585. * @property id
  5586. * @type {Number}
  5587. */
  5588. this.id = id || Material.idCounter++;
  5589. }
  5590. Material.idCounter = 0;
  5591. },{}],29:[function(_dereq_,module,exports){
  5592. /*
  5593. PolyK library
  5594. url: http://polyk.ivank.net
  5595. Released under MIT licence.
  5596. Copyright (c) 2012 Ivan Kuckir
  5597. Permission is hereby granted, free of charge, to any person
  5598. obtaining a copy of this software and associated documentation
  5599. files (the "Software"), to deal in the Software without
  5600. restriction, including without limitation the rights to use,
  5601. copy, modify, merge, publish, distribute, sublicense, and/or sell
  5602. copies of the Software, and to permit persons to whom the
  5603. Software is furnished to do so, subject to the following
  5604. conditions:
  5605. The above copyright notice and this permission notice shall be
  5606. included in all copies or substantial portions of the Software.
  5607. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  5608. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  5609. OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  5610. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  5611. HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  5612. WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  5613. FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  5614. OTHER DEALINGS IN THE SOFTWARE.
  5615. */
  5616. var PolyK = {};
  5617. /*
  5618. Is Polygon self-intersecting?
  5619. O(n^2)
  5620. */
  5621. /*
  5622. PolyK.IsSimple = function(p)
  5623. {
  5624. var n = p.length>>1;
  5625. if(n<4) return true;
  5626. var a1 = new PolyK._P(), a2 = new PolyK._P();
  5627. var b1 = new PolyK._P(), b2 = new PolyK._P();
  5628. var c = new PolyK._P();
  5629. for(var i=0; i<n; i++)
  5630. {
  5631. a1.x = p[2*i ];
  5632. a1.y = p[2*i+1];
  5633. if(i==n-1) { a2.x = p[0 ]; a2.y = p[1 ]; }
  5634. else { a2.x = p[2*i+2]; a2.y = p[2*i+3]; }
  5635. for(var j=0; j<n; j++)
  5636. {
  5637. if(Math.abs(i-j) < 2) continue;
  5638. if(j==n-1 && i==0) continue;
  5639. if(i==n-1 && j==0) continue;
  5640. b1.x = p[2*j ];
  5641. b1.y = p[2*j+1];
  5642. if(j==n-1) { b2.x = p[0 ]; b2.y = p[1 ]; }
  5643. else { b2.x = p[2*j+2]; b2.y = p[2*j+3]; }
  5644. if(PolyK._GetLineIntersection(a1,a2,b1,b2,c) != null) return false;
  5645. }
  5646. }
  5647. return true;
  5648. }
  5649. PolyK.IsConvex = function(p)
  5650. {
  5651. if(p.length<6) return true;
  5652. var l = p.length - 4;
  5653. for(var i=0; i<l; i+=2)
  5654. if(!PolyK._convex(p[i], p[i+1], p[i+2], p[i+3], p[i+4], p[i+5])) return false;
  5655. if(!PolyK._convex(p[l ], p[l+1], p[l+2], p[l+3], p[0], p[1])) return false;
  5656. if(!PolyK._convex(p[l+2], p[l+3], p[0 ], p[1 ], p[2], p[3])) return false;
  5657. return true;
  5658. }
  5659. */
  5660. PolyK.GetArea = function(p)
  5661. {
  5662. if(p.length <6) return 0;
  5663. var l = p.length - 2;
  5664. var sum = 0;
  5665. for(var i=0; i<l; i+=2)
  5666. sum += (p[i+2]-p[i]) * (p[i+1]+p[i+3]);
  5667. sum += (p[0]-p[l]) * (p[l+1]+p[1]);
  5668. return - sum * 0.5;
  5669. }
  5670. /*
  5671. PolyK.GetAABB = function(p)
  5672. {
  5673. var minx = Infinity;
  5674. var miny = Infinity;
  5675. var maxx = -minx;
  5676. var maxy = -miny;
  5677. for(var i=0; i<p.length; i+=2)
  5678. {
  5679. minx = Math.min(minx, p[i ]);
  5680. maxx = Math.max(maxx, p[i ]);
  5681. miny = Math.min(miny, p[i+1]);
  5682. maxy = Math.max(maxy, p[i+1]);
  5683. }
  5684. return {x:minx, y:miny, width:maxx-minx, height:maxy-miny};
  5685. }
  5686. */
  5687. PolyK.Triangulate = function(p)
  5688. {
  5689. var n = p.length>>1;
  5690. if(n<3) return [];
  5691. var tgs = [];
  5692. var avl = [];
  5693. for(var i=0; i<n; i++) avl.push(i);
  5694. var i = 0;
  5695. var al = n;
  5696. while(al > 3)
  5697. {
  5698. var i0 = avl[(i+0)%al];
  5699. var i1 = avl[(i+1)%al];
  5700. var i2 = avl[(i+2)%al];
  5701. var ax = p[2*i0], ay = p[2*i0+1];
  5702. var bx = p[2*i1], by = p[2*i1+1];
  5703. var cx = p[2*i2], cy = p[2*i2+1];
  5704. var earFound = false;
  5705. if(PolyK._convex(ax, ay, bx, by, cx, cy))
  5706. {
  5707. earFound = true;
  5708. for(var j=0; j<al; j++)
  5709. {
  5710. var vi = avl[j];
  5711. if(vi==i0 || vi==i1 || vi==i2) continue;
  5712. if(PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) {earFound = false; break;}
  5713. }
  5714. }
  5715. if(earFound)
  5716. {
  5717. tgs.push(i0, i1, i2);
  5718. avl.splice((i+1)%al, 1);
  5719. al--;
  5720. i= 0;
  5721. }
  5722. else if(i++ > 3*al) break; // no convex angles :(
  5723. }
  5724. tgs.push(avl[0], avl[1], avl[2]);
  5725. return tgs;
  5726. }
  5727. /*
  5728. PolyK.ContainsPoint = function(p, px, py)
  5729. {
  5730. var n = p.length>>1;
  5731. var ax, ay, bx = p[2*n-2]-px, by = p[2*n-1]-py;
  5732. var depth = 0;
  5733. for(var i=0; i<n; i++)
  5734. {
  5735. ax = bx; ay = by;
  5736. bx = p[2*i ] - px;
  5737. by = p[2*i+1] - py;
  5738. if(ay< 0 && by< 0) continue; // both "up" or both "donw"
  5739. if(ay>=0 && by>=0) continue; // both "up" or both "donw"
  5740. if(ax< 0 && bx< 0) continue;
  5741. var lx = ax + (bx-ax)*(-ay)/(by-ay);
  5742. if(lx>0) depth++;
  5743. }
  5744. return (depth & 1) == 1;
  5745. }
  5746. PolyK.Slice = function(p, ax, ay, bx, by)
  5747. {
  5748. if(PolyK.ContainsPoint(p, ax, ay) || PolyK.ContainsPoint(p, bx, by)) return [p.slice(0)];
  5749. var a = new PolyK._P(ax, ay);
  5750. var b = new PolyK._P(bx, by);
  5751. var iscs = []; // intersections
  5752. var ps = []; // points
  5753. for(var i=0; i<p.length; i+=2) ps.push(new PolyK._P(p[i], p[i+1]));
  5754. for(var i=0; i<ps.length; i++)
  5755. {
  5756. var isc = new PolyK._P(0,0);
  5757. isc = PolyK._GetLineIntersection(a, b, ps[i], ps[(i+1)%ps.length], isc);
  5758. if(isc)
  5759. {
  5760. isc.flag = true;
  5761. iscs.push(isc);
  5762. ps.splice(i+1,0,isc);
  5763. i++;
  5764. }
  5765. }
  5766. if(iscs.length == 0) return [p.slice(0)];
  5767. var comp = function(u,v) {return PolyK._P.dist(a,u) - PolyK._P.dist(a,v); }
  5768. iscs.sort(comp);
  5769. var pgs = [];
  5770. var dir = 0;
  5771. while(iscs.length > 0)
  5772. {
  5773. var n = ps.length;
  5774. var i0 = iscs[0];
  5775. var i1 = iscs[1];
  5776. var ind0 = ps.indexOf(i0);
  5777. var ind1 = ps.indexOf(i1);
  5778. var solved = false;
  5779. if(PolyK._firstWithFlag(ps, ind0) == ind1) solved = true;
  5780. else
  5781. {
  5782. i0 = iscs[1];
  5783. i1 = iscs[0];
  5784. ind0 = ps.indexOf(i0);
  5785. ind1 = ps.indexOf(i1);
  5786. if(PolyK._firstWithFlag(ps, ind0) == ind1) solved = true;
  5787. }
  5788. if(solved)
  5789. {
  5790. dir--;
  5791. var pgn = PolyK._getPoints(ps, ind0, ind1);
  5792. pgs.push(pgn);
  5793. ps = PolyK._getPoints(ps, ind1, ind0);
  5794. i0.flag = i1.flag = false;
  5795. iscs.splice(0,2);
  5796. if(iscs.length == 0) pgs.push(ps);
  5797. }
  5798. else { dir++; iscs.reverse(); }
  5799. if(dir>1) break;
  5800. }
  5801. var result = [];
  5802. for(var i=0; i<pgs.length; i++)
  5803. {
  5804. var pg = pgs[i];
  5805. var npg = [];
  5806. for(var j=0; j<pg.length; j++) npg.push(pg[j].x, pg[j].y);
  5807. result.push(npg);
  5808. }
  5809. return result;
  5810. }
  5811. PolyK.Raycast = function(p, x, y, dx, dy, isc)
  5812. {
  5813. var l = p.length - 2;
  5814. var tp = PolyK._tp;
  5815. var a1 = tp[0], a2 = tp[1],
  5816. b1 = tp[2], b2 = tp[3], c = tp[4];
  5817. a1.x = x; a1.y = y;
  5818. a2.x = x+dx; a2.y = y+dy;
  5819. if(isc==null) isc = {dist:0, edge:0, norm:{x:0, y:0}, refl:{x:0, y:0}};
  5820. isc.dist = Infinity;
  5821. for(var i=0; i<l; i+=2)
  5822. {
  5823. b1.x = p[i ]; b1.y = p[i+1];
  5824. b2.x = p[i+2]; b2.y = p[i+3];
  5825. var nisc = PolyK._RayLineIntersection(a1, a2, b1, b2, c);
  5826. if(nisc) PolyK._updateISC(dx, dy, a1, b1, b2, c, i/2, isc);
  5827. }
  5828. b1.x = b2.x; b1.y = b2.y;
  5829. b2.x = p[0]; b2.y = p[1];
  5830. var nisc = PolyK._RayLineIntersection(a1, a2, b1, b2, c);
  5831. if(nisc) PolyK._updateISC(dx, dy, a1, b1, b2, c, p.length/2, isc);
  5832. return (isc.dist != Infinity) ? isc : null;
  5833. }
  5834. PolyK.ClosestEdge = function(p, x, y, isc)
  5835. {
  5836. var l = p.length - 2;
  5837. var tp = PolyK._tp;
  5838. var a1 = tp[0],
  5839. b1 = tp[2], b2 = tp[3], c = tp[4];
  5840. a1.x = x; a1.y = y;
  5841. if(isc==null) isc = {dist:0, edge:0, point:{x:0, y:0}, norm:{x:0, y:0}};
  5842. isc.dist = Infinity;
  5843. for(var i=0; i<l; i+=2)
  5844. {
  5845. b1.x = p[i ]; b1.y = p[i+1];
  5846. b2.x = p[i+2]; b2.y = p[i+3];
  5847. PolyK._pointLineDist(a1, b1, b2, i>>1, isc);
  5848. }
  5849. b1.x = b2.x; b1.y = b2.y;
  5850. b2.x = p[0]; b2.y = p[1];
  5851. PolyK._pointLineDist(a1, b1, b2, l>>1, isc);
  5852. var idst = 1/isc.dist;
  5853. isc.norm.x = (x-isc.point.x)*idst;
  5854. isc.norm.y = (y-isc.point.y)*idst;
  5855. return isc;
  5856. }
  5857. PolyK._pointLineDist = function(p, a, b, edge, isc)
  5858. {
  5859. var x = p.x, y = p.y, x1 = a.x, y1 = a.y, x2 = b.x, y2 = b.y;
  5860. var A = x - x1;
  5861. var B = y - y1;
  5862. var C = x2 - x1;
  5863. var D = y2 - y1;
  5864. var dot = A * C + B * D;
  5865. var len_sq = C * C + D * D;
  5866. var param = dot / len_sq;
  5867. var xx, yy;
  5868. if (param < 0 || (x1 == x2 && y1 == y2)) {
  5869. xx = x1;
  5870. yy = y1;
  5871. }
  5872. else if (param > 1) {
  5873. xx = x2;
  5874. yy = y2;
  5875. }
  5876. else {
  5877. xx = x1 + param * C;
  5878. yy = y1 + param * D;
  5879. }
  5880. var dx = x - xx;
  5881. var dy = y - yy;
  5882. var dst = Math.sqrt(dx * dx + dy * dy);
  5883. if(dst<isc.dist)
  5884. {
  5885. isc.dist = dst;
  5886. isc.edge = edge;
  5887. isc.point.x = xx;
  5888. isc.point.y = yy;
  5889. }
  5890. }
  5891. PolyK._updateISC = function(dx, dy, a1, b1, b2, c, edge, isc)
  5892. {
  5893. var nrl = PolyK._P.dist(a1, c);
  5894. if(nrl<isc.dist)
  5895. {
  5896. var ibl = 1/PolyK._P.dist(b1, b2);
  5897. var nx = -(b2.y-b1.y)*ibl;
  5898. var ny = (b2.x-b1.x)*ibl;
  5899. var ddot = 2*(dx*nx+dy*ny);
  5900. isc.dist = nrl;
  5901. isc.norm.x = nx;
  5902. isc.norm.y = ny;
  5903. isc.refl.x = -ddot*nx+dx;
  5904. isc.refl.y = -ddot*ny+dy;
  5905. isc.edge = edge;
  5906. }
  5907. }
  5908. PolyK._getPoints = function(ps, ind0, ind1)
  5909. {
  5910. var n = ps.length;
  5911. var nps = [];
  5912. if(ind1<ind0) ind1 += n;
  5913. for(var i=ind0; i<= ind1; i++) nps.push(ps[i%n]);
  5914. return nps;
  5915. }
  5916. PolyK._firstWithFlag = function(ps, ind)
  5917. {
  5918. var n = ps.length;
  5919. while(true)
  5920. {
  5921. ind = (ind+1)%n;
  5922. if(ps[ind].flag) return ind;
  5923. }
  5924. }
  5925. */
  5926. PolyK._PointInTriangle = function(px, py, ax, ay, bx, by, cx, cy)
  5927. {
  5928. var v0x = cx-ax;
  5929. var v0y = cy-ay;
  5930. var v1x = bx-ax;
  5931. var v1y = by-ay;
  5932. var v2x = px-ax;
  5933. var v2y = py-ay;
  5934. var dot00 = v0x*v0x+v0y*v0y;
  5935. var dot01 = v0x*v1x+v0y*v1y;
  5936. var dot02 = v0x*v2x+v0y*v2y;
  5937. var dot11 = v1x*v1x+v1y*v1y;
  5938. var dot12 = v1x*v2x+v1y*v2y;
  5939. var invDenom = 1 / (dot00 * dot11 - dot01 * dot01);
  5940. var u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  5941. var v = (dot00 * dot12 - dot01 * dot02) * invDenom;
  5942. // Check if point is in triangle
  5943. return (u >= 0) && (v >= 0) && (u + v < 1);
  5944. }
  5945. /*
  5946. PolyK._RayLineIntersection = function(a1, a2, b1, b2, c)
  5947. {
  5948. var dax = (a1.x-a2.x), dbx = (b1.x-b2.x);
  5949. var day = (a1.y-a2.y), dby = (b1.y-b2.y);
  5950. var Den = dax*dby - day*dbx;
  5951. if (Den == 0) return null; // parallel
  5952. var A = (a1.x * a2.y - a1.y * a2.x);
  5953. var B = (b1.x * b2.y - b1.y * b2.x);
  5954. var I = c;
  5955. var iDen = 1/Den;
  5956. I.x = ( A*dbx - dax*B ) * iDen;
  5957. I.y = ( A*dby - day*B ) * iDen;
  5958. if(!PolyK._InRect(I, b1, b2)) return null;
  5959. if((day>0 && I.y>a1.y) || (day<0 && I.y<a1.y)) return null;
  5960. if((dax>0 && I.x>a1.x) || (dax<0 && I.x<a1.x)) return null;
  5961. return I;
  5962. }
  5963. PolyK._GetLineIntersection = function(a1, a2, b1, b2, c)
  5964. {
  5965. var dax = (a1.x-a2.x), dbx = (b1.x-b2.x);
  5966. var day = (a1.y-a2.y), dby = (b1.y-b2.y);
  5967. var Den = dax*dby - day*dbx;
  5968. if (Den == 0) return null; // parallel
  5969. var A = (a1.x * a2.y - a1.y * a2.x);
  5970. var B = (b1.x * b2.y - b1.y * b2.x);
  5971. var I = c;
  5972. I.x = ( A*dbx - dax*B ) / Den;
  5973. I.y = ( A*dby - day*B ) / Den;
  5974. if(PolyK._InRect(I, a1, a2) && PolyK._InRect(I, b1, b2)) return I;
  5975. return null;
  5976. }
  5977. PolyK._InRect = function(a, b, c)
  5978. {
  5979. if (b.x == c.x) return (a.y>=Math.min(b.y, c.y) && a.y<=Math.max(b.y, c.y));
  5980. if (b.y == c.y) return (a.x>=Math.min(b.x, c.x) && a.x<=Math.max(b.x, c.x));
  5981. if(a.x >= Math.min(b.x, c.x) && a.x <= Math.max(b.x, c.x)
  5982. && a.y >= Math.min(b.y, c.y) && a.y <= Math.max(b.y, c.y))
  5983. return true;
  5984. return false;
  5985. }
  5986. */
  5987. PolyK._convex = function(ax, ay, bx, by, cx, cy)
  5988. {
  5989. return (ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0;
  5990. }
  5991. /*
  5992. PolyK._P = function(x,y)
  5993. {
  5994. this.x = x;
  5995. this.y = y;
  5996. this.flag = false;
  5997. }
  5998. PolyK._P.prototype.toString = function()
  5999. {
  6000. return "Point ["+this.x+", "+this.y+"]";
  6001. }
  6002. PolyK._P.dist = function(a,b)
  6003. {
  6004. var dx = b.x-a.x;
  6005. var dy = b.y-a.y;
  6006. return Math.sqrt(dx*dx + dy*dy);
  6007. }
  6008. PolyK._tp = [];
  6009. for(var i=0; i<10; i++) PolyK._tp.push(new PolyK._P(0,0));
  6010. */
  6011. module.exports = PolyK;
  6012. },{}],30:[function(_dereq_,module,exports){
  6013. /* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved.
  6014. Redistribution and use in source and binary forms, with or without modification,
  6015. are permitted provided that the following conditions are met:
  6016. * Redistributions of source code must retain the above copyright notice, this
  6017. list of conditions and the following disclaimer.
  6018. * Redistributions in binary form must reproduce the above copyright notice,
  6019. this list of conditions and the following disclaimer in the documentation
  6020. and/or other materials provided with the distribution.
  6021. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  6022. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  6023. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  6024. DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
  6025. ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  6026. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  6027. LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
  6028. ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  6029. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  6030. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
  6031. /**
  6032. * The vec2 object from glMatrix, with some extensions and some removed methods. See http://glmatrix.net.
  6033. * @class vec2
  6034. */
  6035. var vec2 = module.exports = {};
  6036. var Utils = _dereq_('../utils/Utils');
  6037. /**
  6038. * Make a cross product and only return the z component
  6039. * @method crossLength
  6040. * @static
  6041. * @param {Array} a
  6042. * @param {Array} b
  6043. * @return {Number}
  6044. */
  6045. vec2.crossLength = function(a,b){
  6046. return a[0] * b[1] - a[1] * b[0];
  6047. };
  6048. /**
  6049. * Cross product between a vector and the Z component of a vector
  6050. * @method crossVZ
  6051. * @static
  6052. * @param {Array} out
  6053. * @param {Array} vec
  6054. * @param {Number} zcomp
  6055. * @return {Number}
  6056. */
  6057. vec2.crossVZ = function(out, vec, zcomp){
  6058. vec2.rotate(out,vec,-Math.PI/2);// Rotate according to the right hand rule
  6059. vec2.scale(out,out,zcomp); // Scale with z
  6060. return out;
  6061. };
  6062. /**
  6063. * Cross product between a vector and the Z component of a vector
  6064. * @method crossZV
  6065. * @static
  6066. * @param {Array} out
  6067. * @param {Number} zcomp
  6068. * @param {Array} vec
  6069. * @return {Number}
  6070. */
  6071. vec2.crossZV = function(out, zcomp, vec){
  6072. vec2.rotate(out,vec,Math.PI/2); // Rotate according to the right hand rule
  6073. vec2.scale(out,out,zcomp); // Scale with z
  6074. return out;
  6075. };
  6076. /**
  6077. * Rotate a vector by an angle
  6078. * @method rotate
  6079. * @static
  6080. * @param {Array} out
  6081. * @param {Array} a
  6082. * @param {Number} angle
  6083. */
  6084. vec2.rotate = function(out,a,angle){
  6085. if(angle !== 0){
  6086. var c = Math.cos(angle),
  6087. s = Math.sin(angle),
  6088. x = a[0],
  6089. y = a[1];
  6090. out[0] = c*x -s*y;
  6091. out[1] = s*x +c*y;
  6092. } else {
  6093. out[0] = a[0];
  6094. out[1] = a[1];
  6095. }
  6096. };
  6097. /**
  6098. * Rotate a vector 90 degrees clockwise
  6099. * @method rotate90cw
  6100. * @static
  6101. * @param {Array} out
  6102. * @param {Array} a
  6103. * @param {Number} angle
  6104. */
  6105. vec2.rotate90cw = function(out, a) {
  6106. var x = a[0];
  6107. var y = a[1];
  6108. out[0] = y;
  6109. out[1] = -x;
  6110. };
  6111. /**
  6112. * Transform a point position to local frame.
  6113. * @method toLocalFrame
  6114. * @param {Array} out
  6115. * @param {Array} worldPoint
  6116. * @param {Array} framePosition
  6117. * @param {Number} frameAngle
  6118. */
  6119. vec2.toLocalFrame = function(out, worldPoint, framePosition, frameAngle){
  6120. vec2.copy(out, worldPoint);
  6121. vec2.sub(out, out, framePosition);
  6122. vec2.rotate(out, out, -frameAngle);
  6123. };
  6124. /**
  6125. * Transform a point position to global frame.
  6126. * @method toGlobalFrame
  6127. * @param {Array} out
  6128. * @param {Array} localPoint
  6129. * @param {Array} framePosition
  6130. * @param {Number} frameAngle
  6131. */
  6132. vec2.toGlobalFrame = function(out, localPoint, framePosition, frameAngle){
  6133. vec2.copy(out, localPoint);
  6134. vec2.rotate(out, out, frameAngle);
  6135. vec2.add(out, out, framePosition);
  6136. };
  6137. /**
  6138. * Transform a vector to local frame.
  6139. * @method vectorToLocalFrame
  6140. * @param {Array} out
  6141. * @param {Array} worldVector
  6142. * @param {Number} frameAngle
  6143. */
  6144. vec2.vectorToLocalFrame = function(out, worldVector, frameAngle){
  6145. vec2.rotate(out, worldVector, -frameAngle);
  6146. };
  6147. /**
  6148. * Transform a point position to global frame.
  6149. * @method toGlobalFrame
  6150. * @param {Array} out
  6151. * @param {Array} localVector
  6152. * @param {Number} frameAngle
  6153. */
  6154. vec2.vectorToGlobalFrame = function(out, localVector, frameAngle){
  6155. vec2.rotate(out, localVector, frameAngle);
  6156. };
  6157. /**
  6158. * Compute centroid of a triangle spanned by vectors a,b,c. See http://easycalculation.com/analytical/learn-centroid.php
  6159. * @method centroid
  6160. * @static
  6161. * @param {Array} out
  6162. * @param {Array} a
  6163. * @param {Array} b
  6164. * @param {Array} c
  6165. * @return {Array} The out object
  6166. */
  6167. vec2.centroid = function(out, a, b, c){
  6168. vec2.add(out, a, b);
  6169. vec2.add(out, out, c);
  6170. vec2.scale(out, out, 1/3);
  6171. return out;
  6172. };
  6173. /**
  6174. * Creates a new, empty vec2
  6175. * @static
  6176. * @method create
  6177. * @return {Array} a new 2D vector
  6178. */
  6179. vec2.create = function() {
  6180. var out = new Utils.ARRAY_TYPE(2);
  6181. out[0] = 0;
  6182. out[1] = 0;
  6183. return out;
  6184. };
  6185. /**
  6186. * Creates a new vec2 initialized with values from an existing vector
  6187. * @static
  6188. * @method clone
  6189. * @param {Array} a vector to clone
  6190. * @return {Array} a new 2D vector
  6191. */
  6192. vec2.clone = function(a) {
  6193. var out = new Utils.ARRAY_TYPE(2);
  6194. out[0] = a[0];
  6195. out[1] = a[1];
  6196. return out;
  6197. };
  6198. /**
  6199. * Creates a new vec2 initialized with the given values
  6200. * @static
  6201. * @method fromValues
  6202. * @param {Number} x X component
  6203. * @param {Number} y Y component
  6204. * @return {Array} a new 2D vector
  6205. */
  6206. vec2.fromValues = function(x, y) {
  6207. var out = new Utils.ARRAY_TYPE(2);
  6208. out[0] = x;
  6209. out[1] = y;
  6210. return out;
  6211. };
  6212. /**
  6213. * Copy the values from one vec2 to another
  6214. * @static
  6215. * @method copy
  6216. * @param {Array} out the receiving vector
  6217. * @param {Array} a the source vector
  6218. * @return {Array} out
  6219. */
  6220. vec2.copy = function(out, a) {
  6221. out[0] = a[0];
  6222. out[1] = a[1];
  6223. return out;
  6224. };
  6225. /**
  6226. * Set the components of a vec2 to the given values
  6227. * @static
  6228. * @method set
  6229. * @param {Array} out the receiving vector
  6230. * @param {Number} x X component
  6231. * @param {Number} y Y component
  6232. * @return {Array} out
  6233. */
  6234. vec2.set = function(out, x, y) {
  6235. out[0] = x;
  6236. out[1] = y;
  6237. return out;
  6238. };
  6239. /**
  6240. * Adds two vec2's
  6241. * @static
  6242. * @method add
  6243. * @param {Array} out the receiving vector
  6244. * @param {Array} a the first operand
  6245. * @param {Array} b the second operand
  6246. * @return {Array} out
  6247. */
  6248. vec2.add = function(out, a, b) {
  6249. out[0] = a[0] + b[0];
  6250. out[1] = a[1] + b[1];
  6251. return out;
  6252. };
  6253. /**
  6254. * Subtracts two vec2's
  6255. * @static
  6256. * @method subtract
  6257. * @param {Array} out the receiving vector
  6258. * @param {Array} a the first operand
  6259. * @param {Array} b the second operand
  6260. * @return {Array} out
  6261. */
  6262. vec2.subtract = function(out, a, b) {
  6263. out[0] = a[0] - b[0];
  6264. out[1] = a[1] - b[1];
  6265. return out;
  6266. };
  6267. /**
  6268. * Alias for vec2.subtract
  6269. * @static
  6270. * @method sub
  6271. */
  6272. vec2.sub = vec2.subtract;
  6273. /**
  6274. * Multiplies two vec2's
  6275. * @static
  6276. * @method multiply
  6277. * @param {Array} out the receiving vector
  6278. * @param {Array} a the first operand
  6279. * @param {Array} b the second operand
  6280. * @return {Array} out
  6281. */
  6282. vec2.multiply = function(out, a, b) {
  6283. out[0] = a[0] * b[0];
  6284. out[1] = a[1] * b[1];
  6285. return out;
  6286. };
  6287. /**
  6288. * Alias for vec2.multiply
  6289. * @static
  6290. * @method mul
  6291. */
  6292. vec2.mul = vec2.multiply;
  6293. /**
  6294. * Divides two vec2's
  6295. * @static
  6296. * @method divide
  6297. * @param {Array} out the receiving vector
  6298. * @param {Array} a the first operand
  6299. * @param {Array} b the second operand
  6300. * @return {Array} out
  6301. */
  6302. vec2.divide = function(out, a, b) {
  6303. out[0] = a[0] / b[0];
  6304. out[1] = a[1] / b[1];
  6305. return out;
  6306. };
  6307. /**
  6308. * Alias for vec2.divide
  6309. * @static
  6310. * @method div
  6311. */
  6312. vec2.div = vec2.divide;
  6313. /**
  6314. * Scales a vec2 by a scalar number
  6315. * @static
  6316. * @method scale
  6317. * @param {Array} out the receiving vector
  6318. * @param {Array} a the vector to scale
  6319. * @param {Number} b amount to scale the vector by
  6320. * @return {Array} out
  6321. */
  6322. vec2.scale = function(out, a, b) {
  6323. out[0] = a[0] * b;
  6324. out[1] = a[1] * b;
  6325. return out;
  6326. };
  6327. /**
  6328. * Calculates the euclidian distance between two vec2's
  6329. * @static
  6330. * @method distance
  6331. * @param {Array} a the first operand
  6332. * @param {Array} b the second operand
  6333. * @return {Number} distance between a and b
  6334. */
  6335. vec2.distance = function(a, b) {
  6336. var x = b[0] - a[0],
  6337. y = b[1] - a[1];
  6338. return Math.sqrt(x*x + y*y);
  6339. };
  6340. /**
  6341. * Alias for vec2.distance
  6342. * @static
  6343. * @method dist
  6344. */
  6345. vec2.dist = vec2.distance;
  6346. /**
  6347. * Calculates the squared euclidian distance between two vec2's
  6348. * @static
  6349. * @method squaredDistance
  6350. * @param {Array} a the first operand
  6351. * @param {Array} b the second operand
  6352. * @return {Number} squared distance between a and b
  6353. */
  6354. vec2.squaredDistance = function(a, b) {
  6355. var x = b[0] - a[0],
  6356. y = b[1] - a[1];
  6357. return x*x + y*y;
  6358. };
  6359. /**
  6360. * Alias for vec2.squaredDistance
  6361. * @static
  6362. * @method sqrDist
  6363. */
  6364. vec2.sqrDist = vec2.squaredDistance;
  6365. /**
  6366. * Calculates the length of a vec2
  6367. * @static
  6368. * @method length
  6369. * @param {Array} a vector to calculate length of
  6370. * @return {Number} length of a
  6371. */
  6372. vec2.length = function (a) {
  6373. var x = a[0],
  6374. y = a[1];
  6375. return Math.sqrt(x*x + y*y);
  6376. };
  6377. /**
  6378. * Alias for vec2.length
  6379. * @method len
  6380. * @static
  6381. */
  6382. vec2.len = vec2.length;
  6383. /**
  6384. * Calculates the squared length of a vec2
  6385. * @static
  6386. * @method squaredLength
  6387. * @param {Array} a vector to calculate squared length of
  6388. * @return {Number} squared length of a
  6389. */
  6390. vec2.squaredLength = function (a) {
  6391. var x = a[0],
  6392. y = a[1];
  6393. return x*x + y*y;
  6394. };
  6395. /**
  6396. * Alias for vec2.squaredLength
  6397. * @static
  6398. * @method sqrLen
  6399. */
  6400. vec2.sqrLen = vec2.squaredLength;
  6401. /**
  6402. * Negates the components of a vec2
  6403. * @static
  6404. * @method negate
  6405. * @param {Array} out the receiving vector
  6406. * @param {Array} a vector to negate
  6407. * @return {Array} out
  6408. */
  6409. vec2.negate = function(out, a) {
  6410. out[0] = -a[0];
  6411. out[1] = -a[1];
  6412. return out;
  6413. };
  6414. /**
  6415. * Normalize a vec2
  6416. * @static
  6417. * @method normalize
  6418. * @param {Array} out the receiving vector
  6419. * @param {Array} a vector to normalize
  6420. * @return {Array} out
  6421. */
  6422. vec2.normalize = function(out, a) {
  6423. var x = a[0],
  6424. y = a[1];
  6425. var len = x*x + y*y;
  6426. if (len > 0) {
  6427. //TODO: evaluate use of glm_invsqrt here?
  6428. len = 1 / Math.sqrt(len);
  6429. out[0] = a[0] * len;
  6430. out[1] = a[1] * len;
  6431. }
  6432. return out;
  6433. };
  6434. /**
  6435. * Calculates the dot product of two vec2's
  6436. * @static
  6437. * @method dot
  6438. * @param {Array} a the first operand
  6439. * @param {Array} b the second operand
  6440. * @return {Number} dot product of a and b
  6441. */
  6442. vec2.dot = function (a, b) {
  6443. return a[0] * b[0] + a[1] * b[1];
  6444. };
  6445. /**
  6446. * Returns a string representation of a vector
  6447. * @static
  6448. * @method str
  6449. * @param {Array} vec vector to represent as a string
  6450. * @return {String} string representation of the vector
  6451. */
  6452. vec2.str = function (a) {
  6453. return 'vec2(' + a[0] + ', ' + a[1] + ')';
  6454. };
  6455. /**
  6456. * Linearly interpolate/mix two vectors.
  6457. * @static
  6458. * @method lerp
  6459. * @param {Array} out
  6460. * @param {Array} a First vector
  6461. * @param {Array} b Second vector
  6462. * @param {number} t Lerp factor
  6463. */
  6464. vec2.lerp = function (out, a, b, t) {
  6465. var ax = a[0],
  6466. ay = a[1];
  6467. out[0] = ax + t * (b[0] - ax);
  6468. out[1] = ay + t * (b[1] - ay);
  6469. return out;
  6470. };
  6471. /**
  6472. * Reflect a vector along a normal.
  6473. * @static
  6474. * @method reflect
  6475. * @param {Array} out
  6476. * @param {Array} vector
  6477. * @param {Array} normal
  6478. */
  6479. vec2.reflect = function(out, vector, normal){
  6480. var dot = vector[0] * normal[0] + vector[1] * normal[1];
  6481. out[0] = vector[0] - 2 * normal[0] * dot;
  6482. out[1] = vector[1] - 2 * normal[1] * dot;
  6483. };
  6484. /**
  6485. * Get the intersection point between two line segments.
  6486. * @static
  6487. * @method getLineSegmentsIntersection
  6488. * @param {Array} out
  6489. * @param {Array} p0
  6490. * @param {Array} p1
  6491. * @param {Array} p2
  6492. * @param {Array} p3
  6493. * @return {boolean} True if there was an intersection, otherwise false.
  6494. */
  6495. vec2.getLineSegmentsIntersection = function(out, p0, p1, p2, p3) {
  6496. var t = vec2.getLineSegmentsIntersectionFraction(p0, p1, p2, p3);
  6497. if(t < 0){
  6498. return false;
  6499. } else {
  6500. out[0] = p0[0] + (t * (p1[0] - p0[0]));
  6501. out[1] = p0[1] + (t * (p1[1] - p0[1]));
  6502. return true;
  6503. }
  6504. };
  6505. /**
  6506. * Get the intersection fraction between two line segments. If successful, the intersection is at p0 + t * (p1 - p0)
  6507. * @static
  6508. * @method getLineSegmentsIntersectionFraction
  6509. * @param {Array} p0
  6510. * @param {Array} p1
  6511. * @param {Array} p2
  6512. * @param {Array} p3
  6513. * @return {number} A number between 0 and 1 if there was an intersection, otherwise -1.
  6514. */
  6515. vec2.getLineSegmentsIntersectionFraction = function(p0, p1, p2, p3) {
  6516. var s1_x = p1[0] - p0[0];
  6517. var s1_y = p1[1] - p0[1];
  6518. var s2_x = p3[0] - p2[0];
  6519. var s2_y = p3[1] - p2[1];
  6520. var s, t;
  6521. s = (-s1_y * (p0[0] - p2[0]) + s1_x * (p0[1] - p2[1])) / (-s2_x * s1_y + s1_x * s2_y);
  6522. t = ( s2_x * (p0[1] - p2[1]) - s2_y * (p0[0] - p2[0])) / (-s2_x * s1_y + s1_x * s2_y);
  6523. if (s >= 0 && s <= 1 && t >= 0 && t <= 1) { // Collision detected
  6524. return t;
  6525. }
  6526. return -1; // No collision
  6527. };
  6528. },{"../utils/Utils":57}],31:[function(_dereq_,module,exports){
  6529. var vec2 = _dereq_('../math/vec2')
  6530. , decomp = _dereq_('poly-decomp')
  6531. , Convex = _dereq_('../shapes/Convex')
  6532. , RaycastResult = _dereq_('../collision/RaycastResult')
  6533. , Ray = _dereq_('../collision/Ray')
  6534. , AABB = _dereq_('../collision/AABB')
  6535. , EventEmitter = _dereq_('../events/EventEmitter');
  6536. module.exports = Body;
  6537. /**
  6538. * A rigid body. Has got a center of mass, position, velocity and a number of
  6539. * shapes that are used for collisions.
  6540. *
  6541. * @class Body
  6542. * @constructor
  6543. * @extends EventEmitter
  6544. * @param {Array} [options.force]
  6545. * @param {Array} [options.position]
  6546. * @param {Array} [options.velocity]
  6547. * @param {Boolean} [options.allowSleep]
  6548. * @param {Boolean} [options.collisionResponse]
  6549. * @param {Number} [options.angle=0]
  6550. * @param {Number} [options.angularForce=0]
  6551. * @param {Number} [options.angularVelocity=0]
  6552. * @param {Number} [options.ccdIterations=10]
  6553. * @param {Number} [options.ccdSpeedThreshold=-1]
  6554. * @param {Number} [options.fixedRotation=false]
  6555. * @param {Number} [options.gravityScale]
  6556. * @param {Number} [options.id]
  6557. * @param {Number} [options.mass=0] A number >= 0. If zero, the .type will be set to Body.STATIC.
  6558. * @param {Number} [options.sleepSpeedLimit]
  6559. * @param {Number} [options.sleepTimeLimit]
  6560. * @param {Object} [options]
  6561. *
  6562. * @example
  6563. *
  6564. * // Create a typical dynamic body
  6565. * var body = new Body({
  6566. * mass: 1,
  6567. * position: [0, 0],
  6568. * angle: 0,
  6569. * velocity: [0, 0],
  6570. * angularVelocity: 0
  6571. * });
  6572. *
  6573. * // Add a circular shape to the body
  6574. * body.addShape(new Circle({ radius: 1 }));
  6575. *
  6576. * // Add the body to the world
  6577. * world.addBody(body);
  6578. */
  6579. function Body(options){
  6580. options = options || {};
  6581. EventEmitter.call(this);
  6582. /**
  6583. * The body identifyer
  6584. * @property id
  6585. * @type {Number}
  6586. */
  6587. this.id = options.id || ++Body._idCounter;
  6588. /**
  6589. * The world that this body is added to. This property is set to NULL if the body is not added to any world.
  6590. * @property world
  6591. * @type {World}
  6592. */
  6593. this.world = null;
  6594. /**
  6595. * The shapes of the body.
  6596. *
  6597. * @property shapes
  6598. * @type {Array}
  6599. */
  6600. this.shapes = [];
  6601. /**
  6602. * The mass of the body.
  6603. * @property mass
  6604. * @type {number}
  6605. */
  6606. this.mass = options.mass || 0;
  6607. /**
  6608. * The inverse mass of the body.
  6609. * @property invMass
  6610. * @type {number}
  6611. */
  6612. this.invMass = 0;
  6613. /**
  6614. * The inertia of the body around the Z axis.
  6615. * @property inertia
  6616. * @type {number}
  6617. */
  6618. this.inertia = 0;
  6619. /**
  6620. * The inverse inertia of the body.
  6621. * @property invInertia
  6622. * @type {number}
  6623. */
  6624. this.invInertia = 0;
  6625. this.invMassSolve = 0;
  6626. this.invInertiaSolve = 0;
  6627. /**
  6628. * Set to true if you want to fix the rotation of the body.
  6629. * @property fixedRotation
  6630. * @type {Boolean}
  6631. */
  6632. this.fixedRotation = !!options.fixedRotation;
  6633. /**
  6634. * Set to true if you want to fix the body movement along the X axis. The body will still be able to move along Y.
  6635. * @property {Boolean} fixedX
  6636. */
  6637. this.fixedX = !!options.fixedX;
  6638. /**
  6639. * Set to true if you want to fix the body movement along the Y axis. The body will still be able to move along X.
  6640. * @property {Boolean} fixedY
  6641. */
  6642. this.fixedY = !!options.fixedY;
  6643. /**
  6644. * @private
  6645. * @property {array} massMultiplier
  6646. */
  6647. this.massMultiplier = vec2.create();
  6648. /**
  6649. * The position of the body
  6650. * @property position
  6651. * @type {Array}
  6652. */
  6653. this.position = vec2.fromValues(0,0);
  6654. if(options.position){
  6655. vec2.copy(this.position, options.position);
  6656. }
  6657. /**
  6658. * The interpolated position of the body. Use this for rendering.
  6659. * @property interpolatedPosition
  6660. * @type {Array}
  6661. */
  6662. this.interpolatedPosition = vec2.fromValues(0,0);
  6663. /**
  6664. * The interpolated angle of the body. Use this for rendering.
  6665. * @property interpolatedAngle
  6666. * @type {Number}
  6667. */
  6668. this.interpolatedAngle = 0;
  6669. /**
  6670. * The previous position of the body.
  6671. * @property previousPosition
  6672. * @type {Array}
  6673. */
  6674. this.previousPosition = vec2.fromValues(0,0);
  6675. /**
  6676. * The previous angle of the body.
  6677. * @property previousAngle
  6678. * @type {Number}
  6679. */
  6680. this.previousAngle = 0;
  6681. /**
  6682. * The current velocity of the body.
  6683. * @property velocity
  6684. * @type {Array}
  6685. */
  6686. this.velocity = vec2.fromValues(0,0);
  6687. if(options.velocity){
  6688. vec2.copy(this.velocity, options.velocity);
  6689. }
  6690. /**
  6691. * Constraint velocity that was added to the body during the last step.
  6692. * @property vlambda
  6693. * @type {Array}
  6694. */
  6695. this.vlambda = vec2.fromValues(0,0);
  6696. /**
  6697. * Angular constraint velocity that was added to the body during last step.
  6698. * @property wlambda
  6699. * @type {Array}
  6700. */
  6701. this.wlambda = 0;
  6702. /**
  6703. * The angle of the body, in radians.
  6704. * @property angle
  6705. * @type {number}
  6706. * @example
  6707. * // The angle property is not normalized to the interval 0 to 2*pi, it can be any value.
  6708. * // If you need a value between 0 and 2*pi, use the following function to normalize it.
  6709. * function normalizeAngle(angle){
  6710. * angle = angle % (2*Math.PI);
  6711. * if(angle < 0){
  6712. * angle += (2*Math.PI);
  6713. * }
  6714. * return angle;
  6715. * }
  6716. */
  6717. this.angle = options.angle || 0;
  6718. /**
  6719. * The angular velocity of the body, in radians per second.
  6720. * @property angularVelocity
  6721. * @type {number}
  6722. */
  6723. this.angularVelocity = options.angularVelocity || 0;
  6724. /**
  6725. * The force acting on the body. Since the body force (and {{#crossLink "Body/angularForce:property"}}{{/crossLink}}) will be zeroed after each step, so you need to set the force before each step.
  6726. * @property force
  6727. * @type {Array}
  6728. *
  6729. * @example
  6730. * // This produces a forcefield of 1 Newton in the positive x direction.
  6731. * for(var i=0; i<numSteps; i++){
  6732. * body.force[0] = 1;
  6733. * world.step(1/60);
  6734. * }
  6735. *
  6736. * @example
  6737. * // This will apply a rotational force on the body
  6738. * for(var i=0; i<numSteps; i++){
  6739. * body.angularForce = -3;
  6740. * world.step(1/60);
  6741. * }
  6742. */
  6743. this.force = vec2.create();
  6744. if(options.force){
  6745. vec2.copy(this.force, options.force);
  6746. }
  6747. /**
  6748. * The angular force acting on the body. See {{#crossLink "Body/force:property"}}{{/crossLink}}.
  6749. * @property angularForce
  6750. * @type {number}
  6751. */
  6752. this.angularForce = options.angularForce || 0;
  6753. /**
  6754. * The linear damping acting on the body in the velocity direction. Should be a value between 0 and 1.
  6755. * @property damping
  6756. * @type {Number}
  6757. * @default 0.1
  6758. */
  6759. this.damping = typeof(options.damping) === "number" ? options.damping : 0.1;
  6760. /**
  6761. * The angular force acting on the body. Should be a value between 0 and 1.
  6762. * @property angularDamping
  6763. * @type {Number}
  6764. * @default 0.1
  6765. */
  6766. this.angularDamping = typeof(options.angularDamping) === "number" ? options.angularDamping : 0.1;
  6767. /**
  6768. * The type of motion this body has. Should be one of: {{#crossLink "Body/STATIC:property"}}Body.STATIC{{/crossLink}}, {{#crossLink "Body/DYNAMIC:property"}}Body.DYNAMIC{{/crossLink}} and {{#crossLink "Body/KINEMATIC:property"}}Body.KINEMATIC{{/crossLink}}.
  6769. *
  6770. * * Static bodies do not move, and they do not respond to forces or collision.
  6771. * * Dynamic bodies body can move and respond to collisions and forces.
  6772. * * Kinematic bodies only moves according to its .velocity, and does not respond to collisions or force.
  6773. *
  6774. * @property type
  6775. * @type {number}
  6776. *
  6777. * @example
  6778. * // Bodies are static by default. Static bodies will never move.
  6779. * var body = new Body();
  6780. * console.log(body.type == Body.STATIC); // true
  6781. *
  6782. * @example
  6783. * // By setting the mass of a body to a nonzero number, the body
  6784. * // will become dynamic and will move and interact with other bodies.
  6785. * var dynamicBody = new Body({
  6786. * mass : 1
  6787. * });
  6788. * console.log(dynamicBody.type == Body.DYNAMIC); // true
  6789. *
  6790. * @example
  6791. * // Kinematic bodies will only move if you change their velocity.
  6792. * var kinematicBody = new Body({
  6793. * type: Body.KINEMATIC // Type can be set via the options object.
  6794. * });
  6795. */
  6796. this.type = Body.STATIC;
  6797. if(typeof(options.type) !== 'undefined'){
  6798. this.type = options.type;
  6799. } else if(!options.mass){
  6800. this.type = Body.STATIC;
  6801. } else {
  6802. this.type = Body.DYNAMIC;
  6803. }
  6804. /**
  6805. * Bounding circle radius.
  6806. * @property boundingRadius
  6807. * @type {Number}
  6808. */
  6809. this.boundingRadius = 0;
  6810. /**
  6811. * Bounding box of this body.
  6812. * @property aabb
  6813. * @type {AABB}
  6814. */
  6815. this.aabb = new AABB();
  6816. /**
  6817. * Indicates if the AABB needs update. Update it with {{#crossLink "Body/updateAABB:method"}}.updateAABB(){{/crossLink}}.
  6818. * @property aabbNeedsUpdate
  6819. * @type {Boolean}
  6820. * @see updateAABB
  6821. *
  6822. * @example
  6823. * // Force update the AABB
  6824. * body.aabbNeedsUpdate = true;
  6825. * body.updateAABB();
  6826. * console.log(body.aabbNeedsUpdate); // false
  6827. */
  6828. this.aabbNeedsUpdate = true;
  6829. /**
  6830. * If true, the body will automatically fall to sleep. Note that you need to enable sleeping in the {{#crossLink "World"}}{{/crossLink}} before anything will happen.
  6831. * @property allowSleep
  6832. * @type {Boolean}
  6833. * @default true
  6834. */
  6835. this.allowSleep = options.allowSleep !== undefined ? options.allowSleep : true;
  6836. this.wantsToSleep = false;
  6837. /**
  6838. * One of {{#crossLink "Body/AWAKE:property"}}Body.AWAKE{{/crossLink}}, {{#crossLink "Body/SLEEPY:property"}}Body.SLEEPY{{/crossLink}} and {{#crossLink "Body/SLEEPING:property"}}Body.SLEEPING{{/crossLink}}.
  6839. *
  6840. * The body is initially Body.AWAKE. If its velocity norm is below .sleepSpeedLimit, the sleepState will become Body.SLEEPY. If the body continues to be Body.SLEEPY for .sleepTimeLimit seconds, it will fall asleep (Body.SLEEPY).
  6841. *
  6842. * @property sleepState
  6843. * @type {Number}
  6844. * @default Body.AWAKE
  6845. */
  6846. this.sleepState = Body.AWAKE;
  6847. /**
  6848. * If the speed (the norm of the velocity) is smaller than this value, the body is considered sleepy.
  6849. * @property sleepSpeedLimit
  6850. * @type {Number}
  6851. * @default 0.2
  6852. */
  6853. this.sleepSpeedLimit = options.sleepSpeedLimit !== undefined ? options.sleepSpeedLimit : 0.2;
  6854. /**
  6855. * If the body has been sleepy for this sleepTimeLimit seconds, it is considered sleeping.
  6856. * @property sleepTimeLimit
  6857. * @type {Number}
  6858. * @default 1
  6859. */
  6860. this.sleepTimeLimit = options.sleepTimeLimit !== undefined ? options.sleepTimeLimit : 1;
  6861. /**
  6862. * Gravity scaling factor. If you want the body to ignore gravity, set this to zero. If you want to reverse gravity, set it to -1.
  6863. * @property {Number} gravityScale
  6864. * @default 1
  6865. */
  6866. this.gravityScale = options.gravityScale !== undefined ? options.gravityScale : 1;
  6867. /**
  6868. * Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled. That means that this body will move through other bodies, but it will still trigger contact events, etc.
  6869. * @property {Boolean} collisionResponse
  6870. */
  6871. this.collisionResponse = options.collisionResponse !== undefined ? options.collisionResponse : true;
  6872. /**
  6873. * How long the body has been sleeping.
  6874. * @property {Number} idleTime
  6875. */
  6876. this.idleTime = 0;
  6877. /**
  6878. * The last time when the body went to SLEEPY state.
  6879. * @property {Number} timeLastSleepy
  6880. * @private
  6881. */
  6882. this.timeLastSleepy = 0;
  6883. /**
  6884. * If the body speed exceeds this threshold, CCD (continuous collision detection) will be enabled. Set it to a negative number to disable CCD completely for this body.
  6885. * @property {number} ccdSpeedThreshold
  6886. * @default -1
  6887. */
  6888. this.ccdSpeedThreshold = options.ccdSpeedThreshold !== undefined ? options.ccdSpeedThreshold : -1;
  6889. /**
  6890. * The number of iterations that should be used when searching for the time of impact during CCD. A larger number will assure that there's a small penetration on CCD collision, but a small number will give more performance.
  6891. * @property {number} ccdIterations
  6892. * @default 10
  6893. */
  6894. this.ccdIterations = options.ccdIterations !== undefined ? options.ccdIterations : 10;
  6895. this.concavePath = null;
  6896. this._wakeUpAfterNarrowphase = false;
  6897. this.updateMassProperties();
  6898. }
  6899. Body.prototype = new EventEmitter();
  6900. Body.prototype.constructor = Body;
  6901. Body._idCounter = 0;
  6902. /**
  6903. * @private
  6904. * @method updateSolveMassProperties
  6905. */
  6906. Body.prototype.updateSolveMassProperties = function(){
  6907. if(this.sleepState === Body.SLEEPING || this.type === Body.KINEMATIC){
  6908. this.invMassSolve = 0;
  6909. this.invInertiaSolve = 0;
  6910. } else {
  6911. this.invMassSolve = this.invMass;
  6912. this.invInertiaSolve = this.invInertia;
  6913. }
  6914. };
  6915. /**
  6916. * Set the total density of the body
  6917. * @method setDensity
  6918. * @param {number} density
  6919. */
  6920. Body.prototype.setDensity = function(density) {
  6921. var totalArea = this.getArea();
  6922. this.mass = totalArea * density;
  6923. this.updateMassProperties();
  6924. };
  6925. /**
  6926. * Get the total area of all shapes in the body
  6927. * @method getArea
  6928. * @return {Number}
  6929. */
  6930. Body.prototype.getArea = function() {
  6931. var totalArea = 0;
  6932. for(var i=0; i<this.shapes.length; i++){
  6933. totalArea += this.shapes[i].area;
  6934. }
  6935. return totalArea;
  6936. };
  6937. /**
  6938. * Get the AABB from the body. The AABB is updated if necessary.
  6939. * @method getAABB
  6940. * @return {AABB} The AABB instance (this.aabb)
  6941. */
  6942. Body.prototype.getAABB = function(){
  6943. if(this.aabbNeedsUpdate){
  6944. this.updateAABB();
  6945. }
  6946. return this.aabb;
  6947. };
  6948. var shapeAABB = new AABB(),
  6949. tmp = vec2.create();
  6950. /**
  6951. * Updates the AABB of the Body, and set .aabbNeedsUpdate = false.
  6952. * @method updateAABB
  6953. */
  6954. Body.prototype.updateAABB = function() {
  6955. var shapes = this.shapes,
  6956. N = shapes.length,
  6957. offset = tmp,
  6958. bodyAngle = this.angle;
  6959. for(var i=0; i!==N; i++){
  6960. var shape = shapes[i],
  6961. angle = shape.angle + bodyAngle;
  6962. // Get shape world offset
  6963. vec2.rotate(offset, shape.position, bodyAngle);
  6964. vec2.add(offset, offset, this.position);
  6965. // Get shape AABB
  6966. shape.computeAABB(shapeAABB, offset, angle);
  6967. if(i===0){
  6968. this.aabb.copy(shapeAABB);
  6969. } else {
  6970. this.aabb.extend(shapeAABB);
  6971. }
  6972. }
  6973. this.aabbNeedsUpdate = false;
  6974. };
  6975. /**
  6976. * Update the bounding radius of the body (this.boundingRadius). Should be done if any of the shape dimensions or positions are changed.
  6977. * @method updateBoundingRadius
  6978. */
  6979. Body.prototype.updateBoundingRadius = function(){
  6980. var shapes = this.shapes,
  6981. N = shapes.length,
  6982. radius = 0;
  6983. for(var i=0; i!==N; i++){
  6984. var shape = shapes[i],
  6985. offset = vec2.length(shape.position),
  6986. r = shape.boundingRadius;
  6987. if(offset + r > radius){
  6988. radius = offset + r;
  6989. }
  6990. }
  6991. this.boundingRadius = radius;
  6992. };
  6993. /**
  6994. * Add a shape to the body. You can pass a local transform when adding a shape,
  6995. * so that the shape gets an offset and angle relative to the body center of mass.
  6996. * Will automatically update the mass properties and bounding radius.
  6997. *
  6998. * @method addShape
  6999. * @param {Shape} shape
  7000. * @param {Array} [offset] Local body offset of the shape.
  7001. * @param {Number} [angle] Local body angle.
  7002. *
  7003. * @example
  7004. * var body = new Body(),
  7005. * shape = new Circle({ radius: 1 });
  7006. *
  7007. * // Add the shape to the body, positioned in the center
  7008. * body.addShape(shape);
  7009. *
  7010. * // Add another shape to the body, positioned 1 unit length from the body center of mass along the local x-axis.
  7011. * body.addShape(shape,[1,0]);
  7012. *
  7013. * // Add another shape to the body, positioned 1 unit length from the body center of mass along the local y-axis, and rotated 90 degrees CCW.
  7014. * body.addShape(shape,[0,1],Math.PI/2);
  7015. */
  7016. Body.prototype.addShape = function(shape, offset, angle){
  7017. if(shape.body){
  7018. throw new Error('A shape can only be added to one body.');
  7019. }
  7020. shape.body = this;
  7021. // Copy the offset vector
  7022. if(offset){
  7023. vec2.copy(shape.position, offset);
  7024. } else {
  7025. vec2.set(shape.position, 0, 0);
  7026. }
  7027. shape.angle = angle || 0;
  7028. this.shapes.push(shape);
  7029. this.updateMassProperties();
  7030. this.updateBoundingRadius();
  7031. this.aabbNeedsUpdate = true;
  7032. };
  7033. /**
  7034. * Remove a shape
  7035. * @method removeShape
  7036. * @param {Shape} shape
  7037. * @return {Boolean} True if the shape was found and removed, else false.
  7038. */
  7039. Body.prototype.removeShape = function(shape){
  7040. var idx = this.shapes.indexOf(shape);
  7041. if(idx !== -1){
  7042. this.shapes.splice(idx,1);
  7043. this.aabbNeedsUpdate = true;
  7044. shape.body = null;
  7045. return true;
  7046. } else {
  7047. return false;
  7048. }
  7049. };
  7050. /**
  7051. * Updates .inertia, .invMass, .invInertia for this Body. Should be called when
  7052. * changing the structure or mass of the Body.
  7053. *
  7054. * @method updateMassProperties
  7055. *
  7056. * @example
  7057. * body.mass += 1;
  7058. * body.updateMassProperties();
  7059. */
  7060. Body.prototype.updateMassProperties = function(){
  7061. if(this.type === Body.STATIC || this.type === Body.KINEMATIC){
  7062. this.mass = Number.MAX_VALUE;
  7063. this.invMass = 0;
  7064. this.inertia = Number.MAX_VALUE;
  7065. this.invInertia = 0;
  7066. } else {
  7067. var shapes = this.shapes,
  7068. N = shapes.length,
  7069. m = this.mass / N,
  7070. I = 0;
  7071. if(!this.fixedRotation){
  7072. for(var i=0; i<N; i++){
  7073. var shape = shapes[i],
  7074. r2 = vec2.squaredLength(shape.position),
  7075. Icm = shape.computeMomentOfInertia(m);
  7076. I += Icm + m*r2;
  7077. }
  7078. this.inertia = I;
  7079. this.invInertia = I>0 ? 1/I : 0;
  7080. } else {
  7081. this.inertia = Number.MAX_VALUE;
  7082. this.invInertia = 0;
  7083. }
  7084. // Inverse mass properties are easy
  7085. this.invMass = 1 / this.mass;
  7086. vec2.set(
  7087. this.massMultiplier,
  7088. this.fixedX ? 0 : 1,
  7089. this.fixedY ? 0 : 1
  7090. );
  7091. }
  7092. };
  7093. var Body_applyForce_r = vec2.create();
  7094. /**
  7095. * Apply force to a point relative to the center of mass of the body. This could for example be a point on the RigidBody surface. Applying force this way will add to Body.force and Body.angularForce. If relativePoint is zero, the force will be applied directly on the center of mass, and the torque produced will be zero.
  7096. * @method applyForce
  7097. * @param {Array} force The force to add.
  7098. * @param {Array} [relativePoint] A world point to apply the force on.
  7099. */
  7100. Body.prototype.applyForce = function(force, relativePoint){
  7101. // Add linear force
  7102. vec2.add(this.force, this.force, force);
  7103. if(relativePoint){
  7104. // Compute produced rotational force
  7105. var rotForce = vec2.crossLength(relativePoint,force);
  7106. // Add rotational force
  7107. this.angularForce += rotForce;
  7108. }
  7109. };
  7110. /**
  7111. * Apply force to a body-local point.
  7112. * @method applyForceLocal
  7113. * @param {Array} localForce The force vector to add, oriented in local body space.
  7114. * @param {Array} localPoint A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be excerted on the center of mass.
  7115. */
  7116. var Body_applyForce_forceWorld = vec2.create();
  7117. var Body_applyForce_pointWorld = vec2.create();
  7118. var Body_applyForce_pointLocal = vec2.create();
  7119. Body.prototype.applyForceLocal = function(localForce, localPoint){
  7120. localPoint = localPoint || Body_applyForce_pointLocal;
  7121. var worldForce = Body_applyForce_forceWorld;
  7122. var worldPoint = Body_applyForce_pointWorld;
  7123. this.vectorToWorldFrame(worldForce, localForce);
  7124. this.vectorToWorldFrame(worldPoint, localPoint);
  7125. this.applyForce(worldForce, worldPoint);
  7126. };
  7127. /**
  7128. * Apply impulse to a point relative to the body. This could for example be a point on the Body surface. An impulse is a force added to a body during a short period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity.
  7129. * @method applyImpulse
  7130. * @param {Array} impulse The impulse vector to add, oriented in world space.
  7131. * @param {Array} [relativePoint] A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be excerted on the center of mass.
  7132. */
  7133. var Body_applyImpulse_velo = vec2.create();
  7134. Body.prototype.applyImpulse = function(impulseVector, relativePoint){
  7135. if(this.type !== Body.DYNAMIC){
  7136. return;
  7137. }
  7138. // Compute produced central impulse velocity
  7139. var velo = Body_applyImpulse_velo;
  7140. vec2.scale(velo, impulseVector, this.invMass);
  7141. vec2.multiply(velo, this.massMultiplier, velo);
  7142. // Add linear impulse
  7143. vec2.add(this.velocity, velo, this.velocity);
  7144. if(relativePoint){
  7145. // Compute produced rotational impulse velocity
  7146. var rotVelo = vec2.crossLength(relativePoint, impulseVector);
  7147. rotVelo *= this.invInertia;
  7148. // Add rotational Impulse
  7149. this.angularVelocity += rotVelo;
  7150. }
  7151. };
  7152. /**
  7153. * Apply impulse to a point relative to the body. This could for example be a point on the Body surface. An impulse is a force added to a body during a short period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity.
  7154. * @method applyImpulseLocal
  7155. * @param {Array} impulse The impulse vector to add, oriented in world space.
  7156. * @param {Array} [relativePoint] A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be excerted on the center of mass.
  7157. */
  7158. var Body_applyImpulse_impulseWorld = vec2.create();
  7159. var Body_applyImpulse_pointWorld = vec2.create();
  7160. var Body_applyImpulse_pointLocal = vec2.create();
  7161. Body.prototype.applyImpulseLocal = function(localImpulse, localPoint){
  7162. localPoint = localPoint || Body_applyImpulse_pointLocal;
  7163. var worldImpulse = Body_applyImpulse_impulseWorld;
  7164. var worldPoint = Body_applyImpulse_pointWorld;
  7165. this.vectorToWorldFrame(worldImpulse, localImpulse);
  7166. this.vectorToWorldFrame(worldPoint, localPoint);
  7167. this.applyImpulse(worldImpulse, worldPoint);
  7168. };
  7169. /**
  7170. * Transform a world point to local body frame.
  7171. * @method toLocalFrame
  7172. * @param {Array} out The vector to store the result in
  7173. * @param {Array} worldPoint The input world point
  7174. */
  7175. Body.prototype.toLocalFrame = function(out, worldPoint){
  7176. vec2.toLocalFrame(out, worldPoint, this.position, this.angle);
  7177. };
  7178. /**
  7179. * Transform a local point to world frame.
  7180. * @method toWorldFrame
  7181. * @param {Array} out The vector to store the result in
  7182. * @param {Array} localPoint The input local point
  7183. */
  7184. Body.prototype.toWorldFrame = function(out, localPoint){
  7185. vec2.toGlobalFrame(out, localPoint, this.position, this.angle);
  7186. };
  7187. /**
  7188. * Transform a world point to local body frame.
  7189. * @method vectorToLocalFrame
  7190. * @param {Array} out The vector to store the result in
  7191. * @param {Array} worldVector The input world vector
  7192. */
  7193. Body.prototype.vectorToLocalFrame = function(out, worldVector){
  7194. vec2.vectorToLocalFrame(out, worldVector, this.angle);
  7195. };
  7196. /**
  7197. * Transform a local point to world frame.
  7198. * @method vectorToWorldFrame
  7199. * @param {Array} out The vector to store the result in
  7200. * @param {Array} localVector The input local vector
  7201. */
  7202. Body.prototype.vectorToWorldFrame = function(out, localVector){
  7203. vec2.vectorToGlobalFrame(out, localVector, this.angle);
  7204. };
  7205. /**
  7206. * Reads a polygon shape path, and assembles convex shapes from that and puts them at proper offset points.
  7207. * @method fromPolygon
  7208. * @param {Array} path An array of 2d vectors, e.g. [[0,0],[0,1],...] that resembles a concave or convex polygon. The shape must be simple and without holes.
  7209. * @param {Object} [options]
  7210. * @param {Boolean} [options.optimalDecomp=false] Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices.
  7211. * @param {Boolean} [options.skipSimpleCheck=false] Set to true if you already know that the path is not intersecting itself.
  7212. * @param {Boolean|Number} [options.removeCollinearPoints=false] Set to a number (angle threshold value) to remove collinear points, or false to keep all points.
  7213. * @return {Boolean} True on success, else false.
  7214. */
  7215. Body.prototype.fromPolygon = function(path,options){
  7216. options = options || {};
  7217. // Remove all shapes
  7218. for(var i=this.shapes.length; i>=0; --i){
  7219. this.removeShape(this.shapes[i]);
  7220. }
  7221. var p = new decomp.Polygon();
  7222. p.vertices = path;
  7223. // Make it counter-clockwise
  7224. p.makeCCW();
  7225. if(typeof(options.removeCollinearPoints) === "number"){
  7226. p.removeCollinearPoints(options.removeCollinearPoints);
  7227. }
  7228. // Check if any line segment intersects the path itself
  7229. if(typeof(options.skipSimpleCheck) === "undefined"){
  7230. if(!p.isSimple()){
  7231. return false;
  7232. }
  7233. }
  7234. // Save this path for later
  7235. this.concavePath = p.vertices.slice(0);
  7236. for(var i=0; i<this.concavePath.length; i++){
  7237. var v = [0,0];
  7238. vec2.copy(v,this.concavePath[i]);
  7239. this.concavePath[i] = v;
  7240. }
  7241. // Slow or fast decomp?
  7242. var convexes;
  7243. if(options.optimalDecomp){
  7244. convexes = p.decomp();
  7245. } else {
  7246. convexes = p.quickDecomp();
  7247. }
  7248. var cm = vec2.create();
  7249. // Add convexes
  7250. for(var i=0; i!==convexes.length; i++){
  7251. // Create convex
  7252. var c = new Convex({ vertices: convexes[i].vertices });
  7253. // Move all vertices so its center of mass is in the local center of the convex
  7254. for(var j=0; j!==c.vertices.length; j++){
  7255. var v = c.vertices[j];
  7256. vec2.sub(v,v,c.centerOfMass);
  7257. }
  7258. vec2.scale(cm,c.centerOfMass,1);
  7259. c.updateTriangles();
  7260. c.updateCenterOfMass();
  7261. c.updateBoundingRadius();
  7262. // Add the shape
  7263. this.addShape(c,cm);
  7264. }
  7265. this.adjustCenterOfMass();
  7266. this.aabbNeedsUpdate = true;
  7267. return true;
  7268. };
  7269. var adjustCenterOfMass_tmp1 = vec2.fromValues(0,0),
  7270. adjustCenterOfMass_tmp2 = vec2.fromValues(0,0),
  7271. adjustCenterOfMass_tmp3 = vec2.fromValues(0,0),
  7272. adjustCenterOfMass_tmp4 = vec2.fromValues(0,0);
  7273. /**
  7274. * Moves the shape offsets so their center of mass becomes the body center of mass.
  7275. * @method adjustCenterOfMass
  7276. */
  7277. Body.prototype.adjustCenterOfMass = function(){
  7278. var offset_times_area = adjustCenterOfMass_tmp2,
  7279. sum = adjustCenterOfMass_tmp3,
  7280. cm = adjustCenterOfMass_tmp4,
  7281. totalArea = 0;
  7282. vec2.set(sum,0,0);
  7283. for(var i=0; i!==this.shapes.length; i++){
  7284. var s = this.shapes[i];
  7285. vec2.scale(offset_times_area, s.position, s.area);
  7286. vec2.add(sum, sum, offset_times_area);
  7287. totalArea += s.area;
  7288. }
  7289. vec2.scale(cm,sum,1/totalArea);
  7290. // Now move all shapes
  7291. for(var i=0; i!==this.shapes.length; i++){
  7292. var s = this.shapes[i];
  7293. vec2.sub(s.position, s.position, cm);
  7294. }
  7295. // Move the body position too
  7296. vec2.add(this.position,this.position,cm);
  7297. // And concave path
  7298. for(var i=0; this.concavePath && i<this.concavePath.length; i++){
  7299. vec2.sub(this.concavePath[i], this.concavePath[i], cm);
  7300. }
  7301. this.updateMassProperties();
  7302. this.updateBoundingRadius();
  7303. };
  7304. /**
  7305. * Sets the force on the body to zero.
  7306. * @method setZeroForce
  7307. */
  7308. Body.prototype.setZeroForce = function(){
  7309. vec2.set(this.force,0.0,0.0);
  7310. this.angularForce = 0.0;
  7311. };
  7312. Body.prototype.resetConstraintVelocity = function(){
  7313. var b = this,
  7314. vlambda = b.vlambda;
  7315. vec2.set(vlambda,0,0);
  7316. b.wlambda = 0;
  7317. };
  7318. Body.prototype.addConstraintVelocity = function(){
  7319. var b = this,
  7320. v = b.velocity;
  7321. vec2.add( v, v, b.vlambda);
  7322. b.angularVelocity += b.wlambda;
  7323. };
  7324. /**
  7325. * Apply damping, see <a href="http://code.google.com/p/bullet/issues/detail?id=74">this</a> for details.
  7326. * @method applyDamping
  7327. * @param {number} dt Current time step
  7328. */
  7329. Body.prototype.applyDamping = function(dt){
  7330. if(this.type === Body.DYNAMIC){ // Only for dynamic bodies
  7331. var v = this.velocity;
  7332. vec2.scale(v, v, Math.pow(1.0 - this.damping,dt));
  7333. this.angularVelocity *= Math.pow(1.0 - this.angularDamping,dt);
  7334. }
  7335. };
  7336. /**
  7337. * Wake the body up. Normally you should not need this, as the body is automatically awoken at events such as collisions.
  7338. * Sets the sleepState to {{#crossLink "Body/AWAKE:property"}}Body.AWAKE{{/crossLink}} and emits the wakeUp event if the body wasn't awake before.
  7339. * @method wakeUp
  7340. */
  7341. Body.prototype.wakeUp = function(){
  7342. var s = this.sleepState;
  7343. this.sleepState = Body.AWAKE;
  7344. this.idleTime = 0;
  7345. if(s !== Body.AWAKE){
  7346. this.emit(Body.wakeUpEvent);
  7347. }
  7348. };
  7349. /**
  7350. * Force body sleep
  7351. * @method sleep
  7352. */
  7353. Body.prototype.sleep = function(){
  7354. this.sleepState = Body.SLEEPING;
  7355. this.angularVelocity = 0;
  7356. this.angularForce = 0;
  7357. vec2.set(this.velocity,0,0);
  7358. vec2.set(this.force,0,0);
  7359. this.emit(Body.sleepEvent);
  7360. };
  7361. /**
  7362. * Called every timestep to update internal sleep timer and change sleep state if needed.
  7363. * @method sleepTick
  7364. * @param {number} time The world time in seconds
  7365. * @param {boolean} dontSleep
  7366. * @param {number} dt
  7367. */
  7368. Body.prototype.sleepTick = function(time, dontSleep, dt){
  7369. if(!this.allowSleep || this.type === Body.SLEEPING){
  7370. return;
  7371. }
  7372. this.wantsToSleep = false;
  7373. var sleepState = this.sleepState,
  7374. speedSquared = vec2.squaredLength(this.velocity) + Math.pow(this.angularVelocity,2),
  7375. speedLimitSquared = Math.pow(this.sleepSpeedLimit,2);
  7376. // Add to idle time
  7377. if(speedSquared >= speedLimitSquared){
  7378. this.idleTime = 0;
  7379. this.sleepState = Body.AWAKE;
  7380. } else {
  7381. this.idleTime += dt;
  7382. this.sleepState = Body.SLEEPY;
  7383. }
  7384. if(this.idleTime > this.sleepTimeLimit){
  7385. if(!dontSleep){
  7386. this.sleep();
  7387. } else {
  7388. this.wantsToSleep = true;
  7389. }
  7390. }
  7391. };
  7392. /**
  7393. * Check if the body is overlapping another body. Note that this method only works if the body was added to a World and if at least one step was taken.
  7394. * @method overlaps
  7395. * @param {Body} body
  7396. * @return {boolean}
  7397. */
  7398. Body.prototype.overlaps = function(body){
  7399. return this.world.overlapKeeper.bodiesAreOverlapping(this, body);
  7400. };
  7401. var integrate_fhMinv = vec2.create();
  7402. var integrate_velodt = vec2.create();
  7403. /**
  7404. * Move the body forward in time given its current velocity.
  7405. * @method integrate
  7406. * @param {Number} dt
  7407. */
  7408. Body.prototype.integrate = function(dt){
  7409. var minv = this.invMass,
  7410. f = this.force,
  7411. pos = this.position,
  7412. velo = this.velocity;
  7413. // Save old position
  7414. vec2.copy(this.previousPosition, this.position);
  7415. this.previousAngle = this.angle;
  7416. // Velocity update
  7417. if(!this.fixedRotation){
  7418. this.angularVelocity += this.angularForce * this.invInertia * dt;
  7419. }
  7420. vec2.scale(integrate_fhMinv, f, dt * minv);
  7421. vec2.multiply(integrate_fhMinv, this.massMultiplier, integrate_fhMinv);
  7422. vec2.add(velo, integrate_fhMinv, velo);
  7423. // CCD
  7424. if(!this.integrateToTimeOfImpact(dt)){
  7425. // Regular position update
  7426. vec2.scale(integrate_velodt, velo, dt);
  7427. vec2.add(pos, pos, integrate_velodt);
  7428. if(!this.fixedRotation){
  7429. this.angle += this.angularVelocity * dt;
  7430. }
  7431. }
  7432. this.aabbNeedsUpdate = true;
  7433. };
  7434. var result = new RaycastResult();
  7435. var ray = new Ray({
  7436. mode: Ray.ALL
  7437. });
  7438. var direction = vec2.create();
  7439. var end = vec2.create();
  7440. var startToEnd = vec2.create();
  7441. var rememberPosition = vec2.create();
  7442. Body.prototype.integrateToTimeOfImpact = function(dt){
  7443. if(this.ccdSpeedThreshold < 0 || vec2.squaredLength(this.velocity) < Math.pow(this.ccdSpeedThreshold, 2)){
  7444. return false;
  7445. }
  7446. vec2.normalize(direction, this.velocity);
  7447. vec2.scale(end, this.velocity, dt);
  7448. vec2.add(end, end, this.position);
  7449. vec2.sub(startToEnd, end, this.position);
  7450. var startToEndAngle = this.angularVelocity * dt;
  7451. var len = vec2.length(startToEnd);
  7452. var timeOfImpact = 1;
  7453. var hit;
  7454. var that = this;
  7455. result.reset();
  7456. ray.callback = function (result) {
  7457. if(result.body === that){
  7458. return;
  7459. }
  7460. hit = result.body;
  7461. result.getHitPoint(end, ray);
  7462. vec2.sub(startToEnd, end, that.position);
  7463. timeOfImpact = vec2.length(startToEnd) / len;
  7464. result.stop();
  7465. };
  7466. vec2.copy(ray.from, this.position);
  7467. vec2.copy(ray.to, end);
  7468. ray.update();
  7469. this.world.raycast(result, ray);
  7470. if(!hit){
  7471. return false;
  7472. }
  7473. var rememberAngle = this.angle;
  7474. vec2.copy(rememberPosition, this.position);
  7475. // Got a start and end point. Approximate time of impact using binary search
  7476. var iter = 0;
  7477. var tmin = 0;
  7478. var tmid = 0;
  7479. var tmax = timeOfImpact;
  7480. while (tmax >= tmin && iter < this.ccdIterations) {
  7481. iter++;
  7482. // calculate the midpoint
  7483. tmid = (tmax - tmin) / 2;
  7484. // Move the body to that point
  7485. vec2.scale(integrate_velodt, startToEnd, timeOfImpact);
  7486. vec2.add(this.position, rememberPosition, integrate_velodt);
  7487. this.angle = rememberAngle + startToEndAngle * timeOfImpact;
  7488. this.updateAABB();
  7489. // check overlap
  7490. var overlaps = this.aabb.overlaps(hit.aabb) && this.world.narrowphase.bodiesOverlap(this, hit);
  7491. if (overlaps) {
  7492. // change min to search upper interval
  7493. tmin = tmid;
  7494. } else {
  7495. // change max to search lower interval
  7496. tmax = tmid;
  7497. }
  7498. }
  7499. timeOfImpact = tmid;
  7500. vec2.copy(this.position, rememberPosition);
  7501. this.angle = rememberAngle;
  7502. // move to TOI
  7503. vec2.scale(integrate_velodt, startToEnd, timeOfImpact);
  7504. vec2.add(this.position, this.position, integrate_velodt);
  7505. if(!this.fixedRotation){
  7506. this.angle += startToEndAngle * timeOfImpact;
  7507. }
  7508. return true;
  7509. };
  7510. /**
  7511. * Get velocity of a point in the body.
  7512. * @method getVelocityAtPoint
  7513. * @param {Array} result A vector to store the result in
  7514. * @param {Array} relativePoint A world oriented vector, indicating the position of the point to get the velocity from
  7515. * @return {Array} The result vector
  7516. */
  7517. Body.prototype.getVelocityAtPoint = function(result, relativePoint){
  7518. vec2.crossVZ(result, relativePoint, this.angularVelocity);
  7519. vec2.subtract(result, this.velocity, result);
  7520. return result;
  7521. };
  7522. /**
  7523. * @event sleepy
  7524. */
  7525. Body.sleepyEvent = {
  7526. type: "sleepy"
  7527. };
  7528. /**
  7529. * @event sleep
  7530. */
  7531. Body.sleepEvent = {
  7532. type: "sleep"
  7533. };
  7534. /**
  7535. * @event wakeup
  7536. */
  7537. Body.wakeUpEvent = {
  7538. type: "wakeup"
  7539. };
  7540. /**
  7541. * Dynamic body.
  7542. * @property DYNAMIC
  7543. * @type {Number}
  7544. * @static
  7545. */
  7546. Body.DYNAMIC = 1;
  7547. /**
  7548. * Static body.
  7549. * @property STATIC
  7550. * @type {Number}
  7551. * @static
  7552. */
  7553. Body.STATIC = 2;
  7554. /**
  7555. * Kinematic body.
  7556. * @property KINEMATIC
  7557. * @type {Number}
  7558. * @static
  7559. */
  7560. Body.KINEMATIC = 4;
  7561. /**
  7562. * @property AWAKE
  7563. * @type {Number}
  7564. * @static
  7565. */
  7566. Body.AWAKE = 0;
  7567. /**
  7568. * @property SLEEPY
  7569. * @type {Number}
  7570. * @static
  7571. */
  7572. Body.SLEEPY = 1;
  7573. /**
  7574. * @property SLEEPING
  7575. * @type {Number}
  7576. * @static
  7577. */
  7578. Body.SLEEPING = 2;
  7579. },{"../collision/AABB":7,"../collision/Ray":11,"../collision/RaycastResult":12,"../events/EventEmitter":26,"../math/vec2":30,"../shapes/Convex":40,"poly-decomp":5}],32:[function(_dereq_,module,exports){
  7580. var vec2 = _dereq_('../math/vec2');
  7581. var Spring = _dereq_('./Spring');
  7582. var Utils = _dereq_('../utils/Utils');
  7583. module.exports = LinearSpring;
  7584. /**
  7585. * A spring, connecting two bodies.
  7586. *
  7587. * The Spring explicitly adds force and angularForce to the bodies.
  7588. *
  7589. * @class LinearSpring
  7590. * @extends Spring
  7591. * @constructor
  7592. * @param {Body} bodyA
  7593. * @param {Body} bodyB
  7594. * @param {Object} [options]
  7595. * @param {number} [options.restLength] A number > 0. Default is the current distance between the world anchor points.
  7596. * @param {number} [options.stiffness=100] Spring constant (see Hookes Law). A number >= 0.
  7597. * @param {number} [options.damping=1] A number >= 0. Default: 1
  7598. * @param {Array} [options.worldAnchorA] Where to hook the spring to body A, in world coordinates. Overrides the option "localAnchorA" if given.
  7599. * @param {Array} [options.worldAnchorB]
  7600. * @param {Array} [options.localAnchorA] Where to hook the spring to body A, in local body coordinates. Defaults to the body center.
  7601. * @param {Array} [options.localAnchorB]
  7602. */
  7603. function LinearSpring(bodyA,bodyB,options){
  7604. options = options || {};
  7605. Spring.call(this, bodyA, bodyB, options);
  7606. /**
  7607. * Anchor for bodyA in local bodyA coordinates.
  7608. * @property localAnchorA
  7609. * @type {Array}
  7610. */
  7611. this.localAnchorA = vec2.fromValues(0,0);
  7612. /**
  7613. * Anchor for bodyB in local bodyB coordinates.
  7614. * @property localAnchorB
  7615. * @type {Array}
  7616. */
  7617. this.localAnchorB = vec2.fromValues(0,0);
  7618. if(options.localAnchorA){ vec2.copy(this.localAnchorA, options.localAnchorA); }
  7619. if(options.localAnchorB){ vec2.copy(this.localAnchorB, options.localAnchorB); }
  7620. if(options.worldAnchorA){ this.setWorldAnchorA(options.worldAnchorA); }
  7621. if(options.worldAnchorB){ this.setWorldAnchorB(options.worldAnchorB); }
  7622. var worldAnchorA = vec2.create();
  7623. var worldAnchorB = vec2.create();
  7624. this.getWorldAnchorA(worldAnchorA);
  7625. this.getWorldAnchorB(worldAnchorB);
  7626. var worldDistance = vec2.distance(worldAnchorA, worldAnchorB);
  7627. /**
  7628. * Rest length of the spring.
  7629. * @property restLength
  7630. * @type {number}
  7631. */
  7632. this.restLength = typeof(options.restLength) === "number" ? options.restLength : worldDistance;
  7633. }
  7634. LinearSpring.prototype = new Spring();
  7635. LinearSpring.prototype.constructor = LinearSpring;
  7636. /**
  7637. * Set the anchor point on body A, using world coordinates.
  7638. * @method setWorldAnchorA
  7639. * @param {Array} worldAnchorA
  7640. */
  7641. LinearSpring.prototype.setWorldAnchorA = function(worldAnchorA){
  7642. this.bodyA.toLocalFrame(this.localAnchorA, worldAnchorA);
  7643. };
  7644. /**
  7645. * Set the anchor point on body B, using world coordinates.
  7646. * @method setWorldAnchorB
  7647. * @param {Array} worldAnchorB
  7648. */
  7649. LinearSpring.prototype.setWorldAnchorB = function(worldAnchorB){
  7650. this.bodyB.toLocalFrame(this.localAnchorB, worldAnchorB);
  7651. };
  7652. /**
  7653. * Get the anchor point on body A, in world coordinates.
  7654. * @method getWorldAnchorA
  7655. * @param {Array} result The vector to store the result in.
  7656. */
  7657. LinearSpring.prototype.getWorldAnchorA = function(result){
  7658. this.bodyA.toWorldFrame(result, this.localAnchorA);
  7659. };
  7660. /**
  7661. * Get the anchor point on body B, in world coordinates.
  7662. * @method getWorldAnchorB
  7663. * @param {Array} result The vector to store the result in.
  7664. */
  7665. LinearSpring.prototype.getWorldAnchorB = function(result){
  7666. this.bodyB.toWorldFrame(result, this.localAnchorB);
  7667. };
  7668. var applyForce_r = vec2.create(),
  7669. applyForce_r_unit = vec2.create(),
  7670. applyForce_u = vec2.create(),
  7671. applyForce_f = vec2.create(),
  7672. applyForce_worldAnchorA = vec2.create(),
  7673. applyForce_worldAnchorB = vec2.create(),
  7674. applyForce_ri = vec2.create(),
  7675. applyForce_rj = vec2.create(),
  7676. applyForce_tmp = vec2.create();
  7677. /**
  7678. * Apply the spring force to the connected bodies.
  7679. * @method applyForce
  7680. */
  7681. LinearSpring.prototype.applyForce = function(){
  7682. var k = this.stiffness,
  7683. d = this.damping,
  7684. l = this.restLength,
  7685. bodyA = this.bodyA,
  7686. bodyB = this.bodyB,
  7687. r = applyForce_r,
  7688. r_unit = applyForce_r_unit,
  7689. u = applyForce_u,
  7690. f = applyForce_f,
  7691. tmp = applyForce_tmp;
  7692. var worldAnchorA = applyForce_worldAnchorA,
  7693. worldAnchorB = applyForce_worldAnchorB,
  7694. ri = applyForce_ri,
  7695. rj = applyForce_rj;
  7696. // Get world anchors
  7697. this.getWorldAnchorA(worldAnchorA);
  7698. this.getWorldAnchorB(worldAnchorB);
  7699. // Get offset points
  7700. vec2.sub(ri, worldAnchorA, bodyA.position);
  7701. vec2.sub(rj, worldAnchorB, bodyB.position);
  7702. // Compute distance vector between world anchor points
  7703. vec2.sub(r, worldAnchorB, worldAnchorA);
  7704. var rlen = vec2.len(r);
  7705. vec2.normalize(r_unit,r);
  7706. //console.log(rlen)
  7707. //console.log("A",vec2.str(worldAnchorA),"B",vec2.str(worldAnchorB))
  7708. // Compute relative velocity of the anchor points, u
  7709. vec2.sub(u, bodyB.velocity, bodyA.velocity);
  7710. vec2.crossZV(tmp, bodyB.angularVelocity, rj);
  7711. vec2.add(u, u, tmp);
  7712. vec2.crossZV(tmp, bodyA.angularVelocity, ri);
  7713. vec2.sub(u, u, tmp);
  7714. // F = - k * ( x - L ) - D * ( u )
  7715. vec2.scale(f, r_unit, -k*(rlen-l) - d*vec2.dot(u,r_unit));
  7716. // Add forces to bodies
  7717. vec2.sub( bodyA.force, bodyA.force, f);
  7718. vec2.add( bodyB.force, bodyB.force, f);
  7719. // Angular force
  7720. var ri_x_f = vec2.crossLength(ri, f);
  7721. var rj_x_f = vec2.crossLength(rj, f);
  7722. bodyA.angularForce -= ri_x_f;
  7723. bodyB.angularForce += rj_x_f;
  7724. };
  7725. },{"../math/vec2":30,"../utils/Utils":57,"./Spring":34}],33:[function(_dereq_,module,exports){
  7726. var vec2 = _dereq_('../math/vec2');
  7727. var Spring = _dereq_('./Spring');
  7728. module.exports = RotationalSpring;
  7729. /**
  7730. * A rotational spring, connecting two bodies rotation. This spring explicitly adds angularForce (torque) to the bodies.
  7731. *
  7732. * The spring can be combined with a {{#crossLink "RevoluteConstraint"}}{{/crossLink}} to make, for example, a mouse trap.
  7733. *
  7734. * @class RotationalSpring
  7735. * @extends Spring
  7736. * @constructor
  7737. * @param {Body} bodyA
  7738. * @param {Body} bodyB
  7739. * @param {Object} [options]
  7740. * @param {number} [options.restAngle] The relative angle of bodies at which the spring is at rest. If not given, it's set to the current relative angle between the bodies.
  7741. * @param {number} [options.stiffness=100] Spring constant (see Hookes Law). A number >= 0.
  7742. * @param {number} [options.damping=1] A number >= 0.
  7743. */
  7744. function RotationalSpring(bodyA, bodyB, options){
  7745. options = options || {};
  7746. Spring.call(this, bodyA, bodyB, options);
  7747. /**
  7748. * Rest angle of the spring.
  7749. * @property restAngle
  7750. * @type {number}
  7751. */
  7752. this.restAngle = typeof(options.restAngle) === "number" ? options.restAngle : bodyB.angle - bodyA.angle;
  7753. }
  7754. RotationalSpring.prototype = new Spring();
  7755. RotationalSpring.prototype.constructor = RotationalSpring;
  7756. /**
  7757. * Apply the spring force to the connected bodies.
  7758. * @method applyForce
  7759. */
  7760. RotationalSpring.prototype.applyForce = function(){
  7761. var k = this.stiffness,
  7762. d = this.damping,
  7763. l = this.restAngle,
  7764. bodyA = this.bodyA,
  7765. bodyB = this.bodyB,
  7766. x = bodyB.angle - bodyA.angle,
  7767. u = bodyB.angularVelocity - bodyA.angularVelocity;
  7768. var torque = - k * (x - l) - d * u * 0;
  7769. bodyA.angularForce -= torque;
  7770. bodyB.angularForce += torque;
  7771. };
  7772. },{"../math/vec2":30,"./Spring":34}],34:[function(_dereq_,module,exports){
  7773. var vec2 = _dereq_('../math/vec2');
  7774. var Utils = _dereq_('../utils/Utils');
  7775. module.exports = Spring;
  7776. /**
  7777. * A spring, connecting two bodies. The Spring explicitly adds force and angularForce to the bodies and does therefore not put load on the constraint solver.
  7778. *
  7779. * @class Spring
  7780. * @constructor
  7781. * @param {Body} bodyA
  7782. * @param {Body} bodyB
  7783. * @param {Object} [options]
  7784. * @param {number} [options.stiffness=100] Spring constant (see Hookes Law). A number >= 0.
  7785. * @param {number} [options.damping=1] A number >= 0. Default: 1
  7786. * @param {Array} [options.localAnchorA] Where to hook the spring to body A, in local body coordinates. Defaults to the body center.
  7787. * @param {Array} [options.localAnchorB]
  7788. * @param {Array} [options.worldAnchorA] Where to hook the spring to body A, in world coordinates. Overrides the option "localAnchorA" if given.
  7789. * @param {Array} [options.worldAnchorB]
  7790. */
  7791. function Spring(bodyA, bodyB, options){
  7792. options = Utils.defaults(options,{
  7793. stiffness: 100,
  7794. damping: 1,
  7795. });
  7796. /**
  7797. * Stiffness of the spring.
  7798. * @property stiffness
  7799. * @type {number}
  7800. */
  7801. this.stiffness = options.stiffness;
  7802. /**
  7803. * Damping of the spring.
  7804. * @property damping
  7805. * @type {number}
  7806. */
  7807. this.damping = options.damping;
  7808. /**
  7809. * First connected body.
  7810. * @property bodyA
  7811. * @type {Body}
  7812. */
  7813. this.bodyA = bodyA;
  7814. /**
  7815. * Second connected body.
  7816. * @property bodyB
  7817. * @type {Body}
  7818. */
  7819. this.bodyB = bodyB;
  7820. }
  7821. /**
  7822. * Apply the spring force to the connected bodies.
  7823. * @method applyForce
  7824. */
  7825. Spring.prototype.applyForce = function(){
  7826. // To be implemented by subclasses
  7827. };
  7828. },{"../math/vec2":30,"../utils/Utils":57}],35:[function(_dereq_,module,exports){
  7829. var vec2 = _dereq_('../math/vec2');
  7830. var Utils = _dereq_('../utils/Utils');
  7831. var Constraint = _dereq_('../constraints/Constraint');
  7832. var FrictionEquation = _dereq_('../equations/FrictionEquation');
  7833. var Body = _dereq_('../objects/Body');
  7834. module.exports = TopDownVehicle;
  7835. /**
  7836. * @class TopDownVehicle
  7837. * @constructor
  7838. * @param {Body} chassisBody A dynamic body, already added to the world.
  7839. * @param {Object} [options]
  7840. *
  7841. * @example
  7842. *
  7843. * // Create a dynamic body for the chassis
  7844. * var chassisBody = new Body({
  7845. * mass: 1
  7846. * });
  7847. * var boxShape = new Box({ width: 0.5, height: 1 });
  7848. * chassisBody.addShape(boxShape);
  7849. * world.addBody(chassisBody);
  7850. *
  7851. * // Create the vehicle
  7852. * var vehicle = new TopDownVehicle(chassisBody);
  7853. *
  7854. * // Add one front wheel and one back wheel - we don't actually need four :)
  7855. * var frontWheel = vehicle.addWheel({
  7856. * localPosition: [0, 0.5] // front
  7857. * });
  7858. * frontWheel.setSideFriction(4);
  7859. *
  7860. * // Back wheel
  7861. * var backWheel = vehicle.addWheel({
  7862. * localPosition: [0, -0.5] // back
  7863. * });
  7864. * backWheel.setSideFriction(3); // Less side friction on back wheel makes it easier to drift
  7865. * vehicle.addToWorld(world);
  7866. *
  7867. * // Steer value zero means straight forward. Positive is left and negative right.
  7868. * frontWheel.steerValue = Math.PI / 16;
  7869. *
  7870. * // Engine force forward
  7871. * backWheel.engineForce = 10;
  7872. * backWheel.setBrakeForce(0);
  7873. */
  7874. function TopDownVehicle(chassisBody, options){
  7875. options = options || {};
  7876. /**
  7877. * @property {Body} chassisBody
  7878. */
  7879. this.chassisBody = chassisBody;
  7880. /**
  7881. * @property {Array} wheels
  7882. */
  7883. this.wheels = [];
  7884. // A dummy body to constrain the chassis to
  7885. this.groundBody = new Body({ mass: 0 });
  7886. this.world = null;
  7887. var that = this;
  7888. this.preStepCallback = function(){
  7889. that.update();
  7890. };
  7891. }
  7892. /**
  7893. * @method addToWorld
  7894. * @param {World} world
  7895. */
  7896. TopDownVehicle.prototype.addToWorld = function(world){
  7897. this.world = world;
  7898. world.addBody(this.groundBody);
  7899. world.on('preStep', this.preStepCallback);
  7900. for (var i = 0; i < this.wheels.length; i++) {
  7901. var wheel = this.wheels[i];
  7902. world.addConstraint(wheel);
  7903. }
  7904. };
  7905. /**
  7906. * @method removeFromWorld
  7907. * @param {World} world
  7908. */
  7909. TopDownVehicle.prototype.removeFromWorld = function(){
  7910. var world = this.world;
  7911. world.removeBody(this.groundBody);
  7912. world.off('preStep', this.preStepCallback);
  7913. for (var i = 0; i < this.wheels.length; i++) {
  7914. var wheel = this.wheels[i];
  7915. world.removeConstraint(wheel);
  7916. }
  7917. this.world = null;
  7918. };
  7919. /**
  7920. * @method addWheel
  7921. * @param {object} [wheelOptions]
  7922. * @return {WheelConstraint}
  7923. */
  7924. TopDownVehicle.prototype.addWheel = function(wheelOptions){
  7925. var wheel = new WheelConstraint(this,wheelOptions);
  7926. this.wheels.push(wheel);
  7927. return wheel;
  7928. };
  7929. /**
  7930. * @method update
  7931. */
  7932. TopDownVehicle.prototype.update = function(){
  7933. for (var i = 0; i < this.wheels.length; i++) {
  7934. this.wheels[i].update();
  7935. }
  7936. };
  7937. /**
  7938. * @class WheelConstraint
  7939. * @constructor
  7940. * @extends {Constraint}
  7941. * @param {Vehicle} vehicle
  7942. * @param {object} [options]
  7943. * @param {Array} [options.localForwardVector]The local wheel forward vector in local body space. Default is zero.
  7944. * @param {Array} [options.localPosition] The local position of the wheen in the chassis body. Default is zero - the center of the body.
  7945. * @param {Array} [options.sideFriction=5] The max friction force in the sideways direction.
  7946. */
  7947. function WheelConstraint(vehicle, options){
  7948. options = options || {};
  7949. this.vehicle = vehicle;
  7950. this.forwardEquation = new FrictionEquation(vehicle.chassisBody, vehicle.groundBody);
  7951. this.sideEquation = new FrictionEquation(vehicle.chassisBody, vehicle.groundBody);
  7952. /**
  7953. * @property {number} steerValue
  7954. */
  7955. this.steerValue = 0;
  7956. /**
  7957. * @property {number} engineForce
  7958. */
  7959. this.engineForce = 0;
  7960. this.setSideFriction(options.sideFriction !== undefined ? options.sideFriction : 5);
  7961. /**
  7962. * @property {Array} localForwardVector
  7963. */
  7964. this.localForwardVector = vec2.fromValues(0, 1);
  7965. if(options.localForwardVector){
  7966. vec2.copy(this.localForwardVector, options.localForwardVector);
  7967. }
  7968. /**
  7969. * @property {Array} localPosition
  7970. */
  7971. this.localPosition = vec2.fromValues(0, 0);
  7972. if(options.localPosition){
  7973. vec2.copy(this.localPosition, options.localPosition);
  7974. }
  7975. Constraint.apply(this, vehicle.chassisBody, vehicle.groundBody);
  7976. this.equations.push(
  7977. this.forwardEquation,
  7978. this.sideEquation
  7979. );
  7980. this.setBrakeForce(0);
  7981. }
  7982. WheelConstraint.prototype = new Constraint();
  7983. /**
  7984. * @method setForwardFriction
  7985. */
  7986. WheelConstraint.prototype.setBrakeForce = function(force){
  7987. this.forwardEquation.setSlipForce(force);
  7988. };
  7989. /**
  7990. * @method setSideFriction
  7991. */
  7992. WheelConstraint.prototype.setSideFriction = function(force){
  7993. this.sideEquation.setSlipForce(force);
  7994. };
  7995. var worldVelocity = vec2.create();
  7996. var relativePoint = vec2.create();
  7997. /**
  7998. * @method getSpeed
  7999. */
  8000. WheelConstraint.prototype.getSpeed = function(){
  8001. this.vehicle.chassisBody.vectorToWorldFrame(relativePoint, this.localForwardVector);
  8002. this.vehicle.chassisBody.getVelocityAtPoint(worldVelocity, relativePoint);
  8003. return vec2.dot(worldVelocity, relativePoint);
  8004. };
  8005. var tmpVec = vec2.create();
  8006. /**
  8007. * @method update
  8008. */
  8009. WheelConstraint.prototype.update = function(){
  8010. // Directional
  8011. this.vehicle.chassisBody.vectorToWorldFrame(this.forwardEquation.t, this.localForwardVector);
  8012. vec2.rotate(this.sideEquation.t, this.localForwardVector, Math.PI / 2);
  8013. this.vehicle.chassisBody.vectorToWorldFrame(this.sideEquation.t, this.sideEquation.t);
  8014. vec2.rotate(this.forwardEquation.t, this.forwardEquation.t, this.steerValue);
  8015. vec2.rotate(this.sideEquation.t, this.sideEquation.t, this.steerValue);
  8016. // Attachment point
  8017. this.vehicle.chassisBody.toWorldFrame(this.forwardEquation.contactPointB, this.localPosition);
  8018. vec2.copy(this.sideEquation.contactPointB, this.forwardEquation.contactPointB);
  8019. this.vehicle.chassisBody.vectorToWorldFrame(this.forwardEquation.contactPointA, this.localPosition);
  8020. vec2.copy(this.sideEquation.contactPointA, this.forwardEquation.contactPointA);
  8021. // Add engine force
  8022. vec2.normalize(tmpVec, this.forwardEquation.t);
  8023. vec2.scale(tmpVec, tmpVec, this.engineForce);
  8024. this.vehicle.chassisBody.applyForce(tmpVec, this.forwardEquation.contactPointA);
  8025. };
  8026. },{"../constraints/Constraint":14,"../equations/FrictionEquation":23,"../math/vec2":30,"../objects/Body":31,"../utils/Utils":57}],36:[function(_dereq_,module,exports){
  8027. // Export p2 classes
  8028. var p2 = module.exports = {
  8029. AABB : _dereq_('./collision/AABB'),
  8030. AngleLockEquation : _dereq_('./equations/AngleLockEquation'),
  8031. Body : _dereq_('./objects/Body'),
  8032. Broadphase : _dereq_('./collision/Broadphase'),
  8033. Capsule : _dereq_('./shapes/Capsule'),
  8034. Circle : _dereq_('./shapes/Circle'),
  8035. Constraint : _dereq_('./constraints/Constraint'),
  8036. ContactEquation : _dereq_('./equations/ContactEquation'),
  8037. ContactEquationPool : _dereq_('./utils/ContactEquationPool'),
  8038. ContactMaterial : _dereq_('./material/ContactMaterial'),
  8039. Convex : _dereq_('./shapes/Convex'),
  8040. DistanceConstraint : _dereq_('./constraints/DistanceConstraint'),
  8041. Equation : _dereq_('./equations/Equation'),
  8042. EventEmitter : _dereq_('./events/EventEmitter'),
  8043. FrictionEquation : _dereq_('./equations/FrictionEquation'),
  8044. FrictionEquationPool : _dereq_('./utils/FrictionEquationPool'),
  8045. GearConstraint : _dereq_('./constraints/GearConstraint'),
  8046. GSSolver : _dereq_('./solver/GSSolver'),
  8047. Heightfield : _dereq_('./shapes/Heightfield'),
  8048. Line : _dereq_('./shapes/Line'),
  8049. LockConstraint : _dereq_('./constraints/LockConstraint'),
  8050. Material : _dereq_('./material/Material'),
  8051. Narrowphase : _dereq_('./collision/Narrowphase'),
  8052. NaiveBroadphase : _dereq_('./collision/NaiveBroadphase'),
  8053. Particle : _dereq_('./shapes/Particle'),
  8054. Plane : _dereq_('./shapes/Plane'),
  8055. Pool : _dereq_('./utils/Pool'),
  8056. RevoluteConstraint : _dereq_('./constraints/RevoluteConstraint'),
  8057. PrismaticConstraint : _dereq_('./constraints/PrismaticConstraint'),
  8058. Ray : _dereq_('./collision/Ray'),
  8059. RaycastResult : _dereq_('./collision/RaycastResult'),
  8060. Box : _dereq_('./shapes/Box'),
  8061. RotationalVelocityEquation : _dereq_('./equations/RotationalVelocityEquation'),
  8062. SAPBroadphase : _dereq_('./collision/SAPBroadphase'),
  8063. Shape : _dereq_('./shapes/Shape'),
  8064. Solver : _dereq_('./solver/Solver'),
  8065. Spring : _dereq_('./objects/Spring'),
  8066. TopDownVehicle : _dereq_('./objects/TopDownVehicle'),
  8067. LinearSpring : _dereq_('./objects/LinearSpring'),
  8068. RotationalSpring : _dereq_('./objects/RotationalSpring'),
  8069. Utils : _dereq_('./utils/Utils'),
  8070. World : _dereq_('./world/World'),
  8071. vec2 : _dereq_('./math/vec2'),
  8072. version : _dereq_('../package.json').version,
  8073. };
  8074. Object.defineProperty(p2, 'Rectangle', {
  8075. get: function() {
  8076. console.warn('The Rectangle class has been renamed to Box.');
  8077. return this.Box;
  8078. }
  8079. });
  8080. },{"../package.json":6,"./collision/AABB":7,"./collision/Broadphase":8,"./collision/NaiveBroadphase":9,"./collision/Narrowphase":10,"./collision/Ray":11,"./collision/RaycastResult":12,"./collision/SAPBroadphase":13,"./constraints/Constraint":14,"./constraints/DistanceConstraint":15,"./constraints/GearConstraint":16,"./constraints/LockConstraint":17,"./constraints/PrismaticConstraint":18,"./constraints/RevoluteConstraint":19,"./equations/AngleLockEquation":20,"./equations/ContactEquation":21,"./equations/Equation":22,"./equations/FrictionEquation":23,"./equations/RotationalVelocityEquation":25,"./events/EventEmitter":26,"./material/ContactMaterial":27,"./material/Material":28,"./math/vec2":30,"./objects/Body":31,"./objects/LinearSpring":32,"./objects/RotationalSpring":33,"./objects/Spring":34,"./objects/TopDownVehicle":35,"./shapes/Box":37,"./shapes/Capsule":38,"./shapes/Circle":39,"./shapes/Convex":40,"./shapes/Heightfield":41,"./shapes/Line":42,"./shapes/Particle":43,"./shapes/Plane":44,"./shapes/Shape":45,"./solver/GSSolver":46,"./solver/Solver":47,"./utils/ContactEquationPool":48,"./utils/FrictionEquationPool":49,"./utils/Pool":55,"./utils/Utils":57,"./world/World":61}],37:[function(_dereq_,module,exports){
  8081. var vec2 = _dereq_('../math/vec2')
  8082. , Shape = _dereq_('./Shape')
  8083. , Convex = _dereq_('./Convex');
  8084. module.exports = Box;
  8085. /**
  8086. * Box shape class.
  8087. * @class Box
  8088. * @constructor
  8089. * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.)
  8090. * @param {Number} [options.width=1] Total width of the box
  8091. * @param {Number} [options.height=1] Total height of the box
  8092. * @extends Convex
  8093. */
  8094. function Box(options){
  8095. if(typeof(arguments[0]) === 'number' && typeof(arguments[1]) === 'number'){
  8096. options = {
  8097. width: arguments[0],
  8098. height: arguments[1]
  8099. };
  8100. console.warn('The Rectangle has been renamed to Box and its constructor signature has changed. Please use the following format: new Box({ width: 1, height: 1, ... })');
  8101. }
  8102. options = options || {};
  8103. /**
  8104. * Total width of the box
  8105. * @property width
  8106. * @type {Number}
  8107. */
  8108. var width = this.width = options.width || 1;
  8109. /**
  8110. * Total height of the box
  8111. * @property height
  8112. * @type {Number}
  8113. */
  8114. var height = this.height = options.height || 1;
  8115. var verts = [
  8116. vec2.fromValues(-width/2, -height/2),
  8117. vec2.fromValues( width/2, -height/2),
  8118. vec2.fromValues( width/2, height/2),
  8119. vec2.fromValues(-width/2, height/2)
  8120. ];
  8121. var axes = [
  8122. vec2.fromValues(1, 0),
  8123. vec2.fromValues(0, 1)
  8124. ];
  8125. options.vertices = verts;
  8126. options.axes = axes;
  8127. options.type = Shape.BOX;
  8128. Convex.call(this, options);
  8129. }
  8130. Box.prototype = new Convex();
  8131. Box.prototype.constructor = Box;
  8132. /**
  8133. * Compute moment of inertia
  8134. * @method computeMomentOfInertia
  8135. * @param {Number} mass
  8136. * @return {Number}
  8137. */
  8138. Box.prototype.computeMomentOfInertia = function(mass){
  8139. var w = this.width,
  8140. h = this.height;
  8141. return mass * (h*h + w*w) / 12;
  8142. };
  8143. /**
  8144. * Update the bounding radius
  8145. * @method updateBoundingRadius
  8146. */
  8147. Box.prototype.updateBoundingRadius = function(){
  8148. var w = this.width,
  8149. h = this.height;
  8150. this.boundingRadius = Math.sqrt(w*w + h*h) / 2;
  8151. };
  8152. var corner1 = vec2.create(),
  8153. corner2 = vec2.create(),
  8154. corner3 = vec2.create(),
  8155. corner4 = vec2.create();
  8156. /**
  8157. * @method computeAABB
  8158. * @param {AABB} out The resulting AABB.
  8159. * @param {Array} position
  8160. * @param {Number} angle
  8161. */
  8162. Box.prototype.computeAABB = function(out, position, angle){
  8163. out.setFromPoints(this.vertices,position,angle,0);
  8164. };
  8165. Box.prototype.updateArea = function(){
  8166. this.area = this.width * this.height;
  8167. };
  8168. },{"../math/vec2":30,"./Convex":40,"./Shape":45}],38:[function(_dereq_,module,exports){
  8169. var Shape = _dereq_('./Shape')
  8170. , vec2 = _dereq_('../math/vec2');
  8171. module.exports = Capsule;
  8172. /**
  8173. * Capsule shape class.
  8174. * @class Capsule
  8175. * @constructor
  8176. * @extends Shape
  8177. * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.)
  8178. * @param {Number} [options.length=1] The distance between the end points
  8179. * @param {Number} [options.radius=1] Radius of the capsule
  8180. * @example
  8181. * var capsuleShape = new Capsule({
  8182. * length: 1,
  8183. * radius: 2
  8184. * });
  8185. * body.addShape(capsuleShape);
  8186. */
  8187. function Capsule(options){
  8188. if(typeof(arguments[0]) === 'number' && typeof(arguments[1]) === 'number'){
  8189. options = {
  8190. length: arguments[0],
  8191. radius: arguments[1]
  8192. };
  8193. console.warn('The Capsule constructor signature has changed. Please use the following format: new Capsule({ radius: 1, length: 1 })');
  8194. }
  8195. options = options || {};
  8196. /**
  8197. * The distance between the end points.
  8198. * @property {Number} length
  8199. */
  8200. this.length = options.length || 1;
  8201. /**
  8202. * The radius of the capsule.
  8203. * @property {Number} radius
  8204. */
  8205. this.radius = options.radius || 1;
  8206. options.type = Shape.CAPSULE;
  8207. Shape.call(this, options);
  8208. }
  8209. Capsule.prototype = new Shape();
  8210. Capsule.prototype.constructor = Capsule;
  8211. /**
  8212. * Compute the mass moment of inertia of the Capsule.
  8213. * @method conputeMomentOfInertia
  8214. * @param {Number} mass
  8215. * @return {Number}
  8216. * @todo
  8217. */
  8218. Capsule.prototype.computeMomentOfInertia = function(mass){
  8219. // Approximate with rectangle
  8220. var r = this.radius,
  8221. w = this.length + r, // 2*r is too much, 0 is too little
  8222. h = r*2;
  8223. return mass * (h*h + w*w) / 12;
  8224. };
  8225. /**
  8226. * @method updateBoundingRadius
  8227. */
  8228. Capsule.prototype.updateBoundingRadius = function(){
  8229. this.boundingRadius = this.radius + this.length/2;
  8230. };
  8231. /**
  8232. * @method updateArea
  8233. */
  8234. Capsule.prototype.updateArea = function(){
  8235. this.area = Math.PI * this.radius * this.radius + this.radius * 2 * this.length;
  8236. };
  8237. var r = vec2.create();
  8238. /**
  8239. * @method computeAABB
  8240. * @param {AABB} out The resulting AABB.
  8241. * @param {Array} position
  8242. * @param {Number} angle
  8243. */
  8244. Capsule.prototype.computeAABB = function(out, position, angle){
  8245. var radius = this.radius;
  8246. // Compute center position of one of the the circles, world oriented, but with local offset
  8247. vec2.set(r,this.length / 2,0);
  8248. if(angle !== 0){
  8249. vec2.rotate(r,r,angle);
  8250. }
  8251. // Get bounds
  8252. vec2.set(out.upperBound, Math.max(r[0]+radius, -r[0]+radius),
  8253. Math.max(r[1]+radius, -r[1]+radius));
  8254. vec2.set(out.lowerBound, Math.min(r[0]-radius, -r[0]-radius),
  8255. Math.min(r[1]-radius, -r[1]-radius));
  8256. // Add offset
  8257. vec2.add(out.lowerBound, out.lowerBound, position);
  8258. vec2.add(out.upperBound, out.upperBound, position);
  8259. };
  8260. var intersectCapsule_hitPointWorld = vec2.create();
  8261. var intersectCapsule_normal = vec2.create();
  8262. var intersectCapsule_l0 = vec2.create();
  8263. var intersectCapsule_l1 = vec2.create();
  8264. var intersectCapsule_unit_y = vec2.fromValues(0,1);
  8265. /**
  8266. * @method raycast
  8267. * @param {RaycastResult} result
  8268. * @param {Ray} ray
  8269. * @param {array} position
  8270. * @param {number} angle
  8271. */
  8272. Capsule.prototype.raycast = function(result, ray, position, angle){
  8273. var from = ray.from;
  8274. var to = ray.to;
  8275. var direction = ray.direction;
  8276. var hitPointWorld = intersectCapsule_hitPointWorld;
  8277. var normal = intersectCapsule_normal;
  8278. var l0 = intersectCapsule_l0;
  8279. var l1 = intersectCapsule_l1;
  8280. // The sides
  8281. var halfLen = this.length / 2;
  8282. for(var i=0; i<2; i++){
  8283. // get start and end of the line
  8284. var y = this.radius * (i*2-1);
  8285. vec2.set(l0, -halfLen, y);
  8286. vec2.set(l1, halfLen, y);
  8287. vec2.toGlobalFrame(l0, l0, position, angle);
  8288. vec2.toGlobalFrame(l1, l1, position, angle);
  8289. var delta = vec2.getLineSegmentsIntersectionFraction(from, to, l0, l1);
  8290. if(delta >= 0){
  8291. vec2.rotate(normal, intersectCapsule_unit_y, angle);
  8292. vec2.scale(normal, normal, (i*2-1));
  8293. ray.reportIntersection(result, delta, normal, -1);
  8294. if(result.shouldStop(ray)){
  8295. return;
  8296. }
  8297. }
  8298. }
  8299. // Circles
  8300. var diagonalLengthSquared = Math.pow(this.radius, 2) + Math.pow(halfLen, 2);
  8301. for(var i=0; i<2; i++){
  8302. vec2.set(l0, halfLen * (i*2-1), 0);
  8303. vec2.toGlobalFrame(l0, l0, position, angle);
  8304. var a = Math.pow(to[0] - from[0], 2) + Math.pow(to[1] - from[1], 2);
  8305. var b = 2 * ((to[0] - from[0]) * (from[0] - l0[0]) + (to[1] - from[1]) * (from[1] - l0[1]));
  8306. var c = Math.pow(from[0] - l0[0], 2) + Math.pow(from[1] - l0[1], 2) - Math.pow(this.radius, 2);
  8307. var delta = Math.pow(b, 2) - 4 * a * c;
  8308. if(delta < 0){
  8309. // No intersection
  8310. continue;
  8311. } else if(delta === 0){
  8312. // single intersection point
  8313. vec2.lerp(hitPointWorld, from, to, delta);
  8314. if(vec2.squaredDistance(hitPointWorld, position) > diagonalLengthSquared){
  8315. vec2.sub(normal, hitPointWorld, l0);
  8316. vec2.normalize(normal,normal);
  8317. ray.reportIntersection(result, delta, normal, -1);
  8318. if(result.shouldStop(ray)){
  8319. return;
  8320. }
  8321. }
  8322. } else {
  8323. var sqrtDelta = Math.sqrt(delta);
  8324. var inv2a = 1 / (2 * a);
  8325. var d1 = (- b - sqrtDelta) * inv2a;
  8326. var d2 = (- b + sqrtDelta) * inv2a;
  8327. if(d1 >= 0 && d1 <= 1){
  8328. vec2.lerp(hitPointWorld, from, to, d1);
  8329. if(vec2.squaredDistance(hitPointWorld, position) > diagonalLengthSquared){
  8330. vec2.sub(normal, hitPointWorld, l0);
  8331. vec2.normalize(normal,normal);
  8332. ray.reportIntersection(result, d1, normal, -1);
  8333. if(result.shouldStop(ray)){
  8334. return;
  8335. }
  8336. }
  8337. }
  8338. if(d2 >= 0 && d2 <= 1){
  8339. vec2.lerp(hitPointWorld, from, to, d2);
  8340. if(vec2.squaredDistance(hitPointWorld, position) > diagonalLengthSquared){
  8341. vec2.sub(normal, hitPointWorld, l0);
  8342. vec2.normalize(normal,normal);
  8343. ray.reportIntersection(result, d2, normal, -1);
  8344. if(result.shouldStop(ray)){
  8345. return;
  8346. }
  8347. }
  8348. }
  8349. }
  8350. }
  8351. };
  8352. },{"../math/vec2":30,"./Shape":45}],39:[function(_dereq_,module,exports){
  8353. var Shape = _dereq_('./Shape')
  8354. , vec2 = _dereq_('../math/vec2');
  8355. module.exports = Circle;
  8356. /**
  8357. * Circle shape class.
  8358. * @class Circle
  8359. * @extends Shape
  8360. * @constructor
  8361. * @param {options} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.)
  8362. * @param {number} [options.radius=1] The radius of this circle
  8363. *
  8364. * @example
  8365. * var circleShape = new Circle({ radius: 1 });
  8366. * body.addShape(circleShape);
  8367. */
  8368. function Circle(options){
  8369. if(typeof(arguments[0]) === 'number'){
  8370. options = {
  8371. radius: arguments[0]
  8372. };
  8373. console.warn('The Circle constructor signature has changed. Please use the following format: new Circle({ radius: 1 })');
  8374. }
  8375. options = options || {};
  8376. /**
  8377. * The radius of the circle.
  8378. * @property radius
  8379. * @type {number}
  8380. */
  8381. this.radius = options.radius || 1;
  8382. options.type = Shape.CIRCLE;
  8383. Shape.call(this, options);
  8384. }
  8385. Circle.prototype = new Shape();
  8386. Circle.prototype.constructor = Circle;
  8387. /**
  8388. * @method computeMomentOfInertia
  8389. * @param {Number} mass
  8390. * @return {Number}
  8391. */
  8392. Circle.prototype.computeMomentOfInertia = function(mass){
  8393. var r = this.radius;
  8394. return mass * r * r / 2;
  8395. };
  8396. /**
  8397. * @method updateBoundingRadius
  8398. * @return {Number}
  8399. */
  8400. Circle.prototype.updateBoundingRadius = function(){
  8401. this.boundingRadius = this.radius;
  8402. };
  8403. /**
  8404. * @method updateArea
  8405. * @return {Number}
  8406. */
  8407. Circle.prototype.updateArea = function(){
  8408. this.area = Math.PI * this.radius * this.radius;
  8409. };
  8410. /**
  8411. * @method computeAABB
  8412. * @param {AABB} out The resulting AABB.
  8413. * @param {Array} position
  8414. * @param {Number} angle
  8415. */
  8416. Circle.prototype.computeAABB = function(out, position, angle){
  8417. var r = this.radius;
  8418. vec2.set(out.upperBound, r, r);
  8419. vec2.set(out.lowerBound, -r, -r);
  8420. if(position){
  8421. vec2.add(out.lowerBound, out.lowerBound, position);
  8422. vec2.add(out.upperBound, out.upperBound, position);
  8423. }
  8424. };
  8425. var Ray_intersectSphere_intersectionPoint = vec2.create();
  8426. var Ray_intersectSphere_normal = vec2.create();
  8427. /**
  8428. * @method raycast
  8429. * @param {RaycastResult} result
  8430. * @param {Ray} ray
  8431. * @param {array} position
  8432. * @param {number} angle
  8433. */
  8434. Circle.prototype.raycast = function(result, ray, position, angle){
  8435. var from = ray.from,
  8436. to = ray.to,
  8437. r = this.radius;
  8438. var a = Math.pow(to[0] - from[0], 2) + Math.pow(to[1] - from[1], 2);
  8439. var b = 2 * ((to[0] - from[0]) * (from[0] - position[0]) + (to[1] - from[1]) * (from[1] - position[1]));
  8440. var c = Math.pow(from[0] - position[0], 2) + Math.pow(from[1] - position[1], 2) - Math.pow(r, 2);
  8441. var delta = Math.pow(b, 2) - 4 * a * c;
  8442. var intersectionPoint = Ray_intersectSphere_intersectionPoint;
  8443. var normal = Ray_intersectSphere_normal;
  8444. if(delta < 0){
  8445. // No intersection
  8446. return;
  8447. } else if(delta === 0){
  8448. // single intersection point
  8449. vec2.lerp(intersectionPoint, from, to, delta);
  8450. vec2.sub(normal, intersectionPoint, position);
  8451. vec2.normalize(normal,normal);
  8452. ray.reportIntersection(result, delta, normal, -1);
  8453. } else {
  8454. var sqrtDelta = Math.sqrt(delta);
  8455. var inv2a = 1 / (2 * a);
  8456. var d1 = (- b - sqrtDelta) * inv2a;
  8457. var d2 = (- b + sqrtDelta) * inv2a;
  8458. if(d1 >= 0 && d1 <= 1){
  8459. vec2.lerp(intersectionPoint, from, to, d1);
  8460. vec2.sub(normal, intersectionPoint, position);
  8461. vec2.normalize(normal,normal);
  8462. ray.reportIntersection(result, d1, normal, -1);
  8463. if(result.shouldStop(ray)){
  8464. return;
  8465. }
  8466. }
  8467. if(d2 >= 0 && d2 <= 1){
  8468. vec2.lerp(intersectionPoint, from, to, d2);
  8469. vec2.sub(normal, intersectionPoint, position);
  8470. vec2.normalize(normal,normal);
  8471. ray.reportIntersection(result, d2, normal, -1);
  8472. }
  8473. }
  8474. };
  8475. },{"../math/vec2":30,"./Shape":45}],40:[function(_dereq_,module,exports){
  8476. var Shape = _dereq_('./Shape')
  8477. , vec2 = _dereq_('../math/vec2')
  8478. , polyk = _dereq_('../math/polyk')
  8479. , decomp = _dereq_('poly-decomp');
  8480. module.exports = Convex;
  8481. /**
  8482. * Convex shape class.
  8483. * @class Convex
  8484. * @constructor
  8485. * @extends Shape
  8486. * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.)
  8487. * @param {Array} [options.vertices] An array of vertices that span this shape. Vertices are given in counter-clockwise (CCW) direction.
  8488. * @param {Array} [options.axes] An array of unit length vectors, representing the symmetry axes in the convex.
  8489. * @example
  8490. * // Create a box
  8491. * var vertices = [[-1,-1], [1,-1], [1,1], [-1,1]];
  8492. * var convexShape = new Convex({ vertices: vertices });
  8493. * body.addShape(convexShape);
  8494. */
  8495. function Convex(options){
  8496. if(Array.isArray(arguments[0])){
  8497. options = {
  8498. vertices: arguments[0],
  8499. axes: arguments[1]
  8500. };
  8501. console.warn('The Convex constructor signature has changed. Please use the following format: new Convex({ vertices: [...], ... })');
  8502. }
  8503. options = options || {};
  8504. /**
  8505. * Vertices defined in the local frame.
  8506. * @property vertices
  8507. * @type {Array}
  8508. */
  8509. this.vertices = [];
  8510. // Copy the verts
  8511. var vertices = options.vertices !== undefined ? options.vertices : [];
  8512. for(var i=0; i < vertices.length; i++){
  8513. var v = vec2.create();
  8514. vec2.copy(v, vertices[i]);
  8515. this.vertices.push(v);
  8516. }
  8517. /**
  8518. * Axes defined in the local frame.
  8519. * @property axes
  8520. * @type {Array}
  8521. */
  8522. this.axes = [];
  8523. if(options.axes){
  8524. // Copy the axes
  8525. for(var i=0; i < options.axes.length; i++){
  8526. var axis = vec2.create();
  8527. vec2.copy(axis, options.axes[i]);
  8528. this.axes.push(axis);
  8529. }
  8530. } else {
  8531. // Construct axes from the vertex data
  8532. for(var i = 0; i < this.vertices.length; i++){
  8533. // Get the world edge
  8534. var worldPoint0 = this.vertices[i];
  8535. var worldPoint1 = this.vertices[(i+1) % this.vertices.length];
  8536. var normal = vec2.create();
  8537. vec2.sub(normal, worldPoint1, worldPoint0);
  8538. // Get normal - just rotate 90 degrees since vertices are given in CCW
  8539. vec2.rotate90cw(normal, normal);
  8540. vec2.normalize(normal, normal);
  8541. this.axes.push(normal);
  8542. }
  8543. }
  8544. /**
  8545. * The center of mass of the Convex
  8546. * @property centerOfMass
  8547. * @type {Array}
  8548. */
  8549. this.centerOfMass = vec2.fromValues(0,0);
  8550. /**
  8551. * Triangulated version of this convex. The structure is Array of 3-Arrays, and each subarray contains 3 integers, referencing the vertices.
  8552. * @property triangles
  8553. * @type {Array}
  8554. */
  8555. this.triangles = [];
  8556. if(this.vertices.length){
  8557. this.updateTriangles();
  8558. this.updateCenterOfMass();
  8559. }
  8560. /**
  8561. * The bounding radius of the convex
  8562. * @property boundingRadius
  8563. * @type {Number}
  8564. */
  8565. this.boundingRadius = 0;
  8566. options.type = Shape.CONVEX;
  8567. Shape.call(this, options);
  8568. this.updateBoundingRadius();
  8569. this.updateArea();
  8570. if(this.area < 0){
  8571. throw new Error("Convex vertices must be given in conter-clockwise winding.");
  8572. }
  8573. }
  8574. Convex.prototype = new Shape();
  8575. Convex.prototype.constructor = Convex;
  8576. var tmpVec1 = vec2.create();
  8577. var tmpVec2 = vec2.create();
  8578. /**
  8579. * Project a Convex onto a world-oriented axis
  8580. * @method projectOntoAxis
  8581. * @static
  8582. * @param {Array} offset
  8583. * @param {Array} localAxis
  8584. * @param {Array} result
  8585. */
  8586. Convex.prototype.projectOntoLocalAxis = function(localAxis, result){
  8587. var max=null,
  8588. min=null,
  8589. v,
  8590. value,
  8591. localAxis = tmpVec1;
  8592. // Get projected position of all vertices
  8593. for(var i=0; i<this.vertices.length; i++){
  8594. v = this.vertices[i];
  8595. value = vec2.dot(v, localAxis);
  8596. if(max === null || value > max){
  8597. max = value;
  8598. }
  8599. if(min === null || value < min){
  8600. min = value;
  8601. }
  8602. }
  8603. if(min > max){
  8604. var t = min;
  8605. min = max;
  8606. max = t;
  8607. }
  8608. vec2.set(result, min, max);
  8609. };
  8610. Convex.prototype.projectOntoWorldAxis = function(localAxis, shapeOffset, shapeAngle, result){
  8611. var worldAxis = tmpVec2;
  8612. this.projectOntoLocalAxis(localAxis, result);
  8613. // Project the position of the body onto the axis - need to add this to the result
  8614. if(shapeAngle !== 0){
  8615. vec2.rotate(worldAxis, localAxis, shapeAngle);
  8616. } else {
  8617. worldAxis = localAxis;
  8618. }
  8619. var offset = vec2.dot(shapeOffset, worldAxis);
  8620. vec2.set(result, result[0] + offset, result[1] + offset);
  8621. };
  8622. /**
  8623. * Update the .triangles property
  8624. * @method updateTriangles
  8625. */
  8626. Convex.prototype.updateTriangles = function(){
  8627. this.triangles.length = 0;
  8628. // Rewrite on polyk notation, array of numbers
  8629. var polykVerts = [];
  8630. for(var i=0; i<this.vertices.length; i++){
  8631. var v = this.vertices[i];
  8632. polykVerts.push(v[0],v[1]);
  8633. }
  8634. // Triangulate
  8635. var triangles = polyk.Triangulate(polykVerts);
  8636. // Loop over all triangles, add their inertia contributions to I
  8637. for(var i=0; i<triangles.length; i+=3){
  8638. var id1 = triangles[i],
  8639. id2 = triangles[i+1],
  8640. id3 = triangles[i+2];
  8641. // Add to triangles
  8642. this.triangles.push([id1,id2,id3]);
  8643. }
  8644. };
  8645. var updateCenterOfMass_centroid = vec2.create(),
  8646. updateCenterOfMass_centroid_times_mass = vec2.create(),
  8647. updateCenterOfMass_a = vec2.create(),
  8648. updateCenterOfMass_b = vec2.create(),
  8649. updateCenterOfMass_c = vec2.create(),
  8650. updateCenterOfMass_ac = vec2.create(),
  8651. updateCenterOfMass_ca = vec2.create(),
  8652. updateCenterOfMass_cb = vec2.create(),
  8653. updateCenterOfMass_n = vec2.create();
  8654. /**
  8655. * Update the .centerOfMass property.
  8656. * @method updateCenterOfMass
  8657. */
  8658. Convex.prototype.updateCenterOfMass = function(){
  8659. var triangles = this.triangles,
  8660. verts = this.vertices,
  8661. cm = this.centerOfMass,
  8662. centroid = updateCenterOfMass_centroid,
  8663. n = updateCenterOfMass_n,
  8664. a = updateCenterOfMass_a,
  8665. b = updateCenterOfMass_b,
  8666. c = updateCenterOfMass_c,
  8667. ac = updateCenterOfMass_ac,
  8668. ca = updateCenterOfMass_ca,
  8669. cb = updateCenterOfMass_cb,
  8670. centroid_times_mass = updateCenterOfMass_centroid_times_mass;
  8671. vec2.set(cm,0,0);
  8672. var totalArea = 0;
  8673. for(var i=0; i!==triangles.length; i++){
  8674. var t = triangles[i],
  8675. a = verts[t[0]],
  8676. b = verts[t[1]],
  8677. c = verts[t[2]];
  8678. vec2.centroid(centroid,a,b,c);
  8679. // Get mass for the triangle (density=1 in this case)
  8680. // http://math.stackexchange.com/questions/80198/area-of-triangle-via-vectors
  8681. var m = Convex.triangleArea(a,b,c);
  8682. totalArea += m;
  8683. // Add to center of mass
  8684. vec2.scale(centroid_times_mass, centroid, m);
  8685. vec2.add(cm, cm, centroid_times_mass);
  8686. }
  8687. vec2.scale(cm,cm,1/totalArea);
  8688. };
  8689. /**
  8690. * Compute the mass moment of inertia of the Convex.
  8691. * @method computeMomentOfInertia
  8692. * @param {Number} mass
  8693. * @return {Number}
  8694. * @see http://www.gamedev.net/topic/342822-moment-of-inertia-of-a-polygon-2d/
  8695. */
  8696. Convex.prototype.computeMomentOfInertia = function(mass){
  8697. var denom = 0.0,
  8698. numer = 0.0,
  8699. N = this.vertices.length;
  8700. for(var j = N-1, i = 0; i < N; j = i, i ++){
  8701. var p0 = this.vertices[j];
  8702. var p1 = this.vertices[i];
  8703. var a = Math.abs(vec2.crossLength(p0,p1));
  8704. var b = vec2.dot(p1,p1) + vec2.dot(p1,p0) + vec2.dot(p0,p0);
  8705. denom += a * b;
  8706. numer += a;
  8707. }
  8708. return (mass / 6.0) * (denom / numer);
  8709. };
  8710. /**
  8711. * Updates the .boundingRadius property
  8712. * @method updateBoundingRadius
  8713. */
  8714. Convex.prototype.updateBoundingRadius = function(){
  8715. var verts = this.vertices,
  8716. r2 = 0;
  8717. for(var i=0; i!==verts.length; i++){
  8718. var l2 = vec2.squaredLength(verts[i]);
  8719. if(l2 > r2){
  8720. r2 = l2;
  8721. }
  8722. }
  8723. this.boundingRadius = Math.sqrt(r2);
  8724. };
  8725. /**
  8726. * Get the area of the triangle spanned by the three points a, b, c. The area is positive if the points are given in counter-clockwise order, otherwise negative.
  8727. * @static
  8728. * @method triangleArea
  8729. * @param {Array} a
  8730. * @param {Array} b
  8731. * @param {Array} c
  8732. * @return {Number}
  8733. */
  8734. Convex.triangleArea = function(a,b,c){
  8735. return (((b[0] - a[0])*(c[1] - a[1]))-((c[0] - a[0])*(b[1] - a[1]))) * 0.5;
  8736. };
  8737. /**
  8738. * Update the .area
  8739. * @method updateArea
  8740. */
  8741. Convex.prototype.updateArea = function(){
  8742. this.updateTriangles();
  8743. this.area = 0;
  8744. var triangles = this.triangles,
  8745. verts = this.vertices;
  8746. for(var i=0; i!==triangles.length; i++){
  8747. var t = triangles[i],
  8748. a = verts[t[0]],
  8749. b = verts[t[1]],
  8750. c = verts[t[2]];
  8751. // Get mass for the triangle (density=1 in this case)
  8752. var m = Convex.triangleArea(a,b,c);
  8753. this.area += m;
  8754. }
  8755. };
  8756. /**
  8757. * @method computeAABB
  8758. * @param {AABB} out
  8759. * @param {Array} position
  8760. * @param {Number} angle
  8761. */
  8762. Convex.prototype.computeAABB = function(out, position, angle){
  8763. out.setFromPoints(this.vertices, position, angle, 0);
  8764. };
  8765. var intersectConvex_rayStart = vec2.create();
  8766. var intersectConvex_rayEnd = vec2.create();
  8767. var intersectConvex_normal = vec2.create();
  8768. /**
  8769. * @method raycast
  8770. * @param {RaycastResult} result
  8771. * @param {Ray} ray
  8772. * @param {array} position
  8773. * @param {number} angle
  8774. */
  8775. Convex.prototype.raycast = function(result, ray, position, angle){
  8776. var rayStart = intersectConvex_rayStart;
  8777. var rayEnd = intersectConvex_rayEnd;
  8778. var normal = intersectConvex_normal;
  8779. var vertices = this.vertices;
  8780. // Transform to local shape space
  8781. vec2.toLocalFrame(rayStart, ray.from, position, angle);
  8782. vec2.toLocalFrame(rayEnd, ray.to, position, angle);
  8783. var n = vertices.length;
  8784. for (var i = 0; i < n && !result.shouldStop(ray); i++) {
  8785. var q1 = vertices[i];
  8786. var q2 = vertices[(i+1) % n];
  8787. var delta = vec2.getLineSegmentsIntersectionFraction(rayStart, rayEnd, q1, q2);
  8788. if(delta >= 0){
  8789. vec2.sub(normal, q2, q1);
  8790. vec2.rotate(normal, normal, -Math.PI / 2 + angle);
  8791. vec2.normalize(normal, normal);
  8792. ray.reportIntersection(result, delta, normal, i);
  8793. }
  8794. }
  8795. };
  8796. },{"../math/polyk":29,"../math/vec2":30,"./Shape":45,"poly-decomp":5}],41:[function(_dereq_,module,exports){
  8797. var Shape = _dereq_('./Shape')
  8798. , vec2 = _dereq_('../math/vec2')
  8799. , Utils = _dereq_('../utils/Utils');
  8800. module.exports = Heightfield;
  8801. /**
  8802. * Heightfield shape class. Height data is given as an array. These data points are spread out evenly with a distance "elementWidth".
  8803. * @class Heightfield
  8804. * @extends Shape
  8805. * @constructor
  8806. * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.)
  8807. * @param {array} [options.heights] An array of Y values that will be used to construct the terrain.
  8808. * @param {Number} [options.minValue] Minimum value of the data points in the data array. Will be computed automatically if not given.
  8809. * @param {Number} [options.maxValue] Maximum value.
  8810. * @param {Number} [options.elementWidth=0.1] World spacing between the data points in X direction.
  8811. *
  8812. * @example
  8813. * // Generate some height data (y-values).
  8814. * var heights = [];
  8815. * for(var i = 0; i < 1000; i++){
  8816. * var y = 0.5 * Math.cos(0.2 * i);
  8817. * heights.push(y);
  8818. * }
  8819. *
  8820. * // Create the heightfield shape
  8821. * var heightfieldShape = new Heightfield({
  8822. * heights: heights,
  8823. * elementWidth: 1 // Distance between the data points in X direction
  8824. * });
  8825. * var heightfieldBody = new Body();
  8826. * heightfieldBody.addShape(heightfieldShape);
  8827. * world.addBody(heightfieldBody);
  8828. *
  8829. * @todo Should use a scale property with X and Y direction instead of just elementWidth
  8830. */
  8831. function Heightfield(options){
  8832. if(Array.isArray(arguments[0])){
  8833. options = {
  8834. heights: arguments[0]
  8835. };
  8836. if(typeof(arguments[1]) === 'object'){
  8837. for(var key in arguments[1]){
  8838. options[key] = arguments[1][key];
  8839. }
  8840. }
  8841. console.warn('The Heightfield constructor signature has changed. Please use the following format: new Heightfield({ heights: [...], ... })');
  8842. }
  8843. options = options || {};
  8844. /**
  8845. * An array of numbers, or height values, that are spread out along the x axis.
  8846. * @property {array} heights
  8847. */
  8848. this.heights = options.heights ? options.heights.slice(0) : [];
  8849. /**
  8850. * Max value of the heights
  8851. * @property {number} maxValue
  8852. */
  8853. this.maxValue = options.maxValue || null;
  8854. /**
  8855. * Max value of the heights
  8856. * @property {number} minValue
  8857. */
  8858. this.minValue = options.minValue || null;
  8859. /**
  8860. * The width of each element
  8861. * @property {number} elementWidth
  8862. */
  8863. this.elementWidth = options.elementWidth || 0.1;
  8864. if(options.maxValue === undefined || options.minValue === undefined){
  8865. this.updateMaxMinValues();
  8866. }
  8867. options.type = Shape.HEIGHTFIELD;
  8868. Shape.call(this, options);
  8869. }
  8870. Heightfield.prototype = new Shape();
  8871. Heightfield.prototype.constructor = Heightfield;
  8872. /**
  8873. * Update the .minValue and the .maxValue
  8874. * @method updateMaxMinValues
  8875. */
  8876. Heightfield.prototype.updateMaxMinValues = function(){
  8877. var data = this.heights;
  8878. var maxValue = data[0];
  8879. var minValue = data[0];
  8880. for(var i=0; i !== data.length; i++){
  8881. var v = data[i];
  8882. if(v > maxValue){
  8883. maxValue = v;
  8884. }
  8885. if(v < minValue){
  8886. minValue = v;
  8887. }
  8888. }
  8889. this.maxValue = maxValue;
  8890. this.minValue = minValue;
  8891. };
  8892. /**
  8893. * @method computeMomentOfInertia
  8894. * @param {Number} mass
  8895. * @return {Number}
  8896. */
  8897. Heightfield.prototype.computeMomentOfInertia = function(mass){
  8898. return Number.MAX_VALUE;
  8899. };
  8900. Heightfield.prototype.updateBoundingRadius = function(){
  8901. this.boundingRadius = Number.MAX_VALUE;
  8902. };
  8903. Heightfield.prototype.updateArea = function(){
  8904. var data = this.heights,
  8905. area = 0;
  8906. for(var i=0; i<data.length-1; i++){
  8907. area += (data[i]+data[i+1]) / 2 * this.elementWidth;
  8908. }
  8909. this.area = area;
  8910. };
  8911. var points = [
  8912. vec2.create(),
  8913. vec2.create(),
  8914. vec2.create(),
  8915. vec2.create()
  8916. ];
  8917. /**
  8918. * @method computeAABB
  8919. * @param {AABB} out The resulting AABB.
  8920. * @param {Array} position
  8921. * @param {Number} angle
  8922. */
  8923. Heightfield.prototype.computeAABB = function(out, position, angle){
  8924. vec2.set(points[0], 0, this.maxValue);
  8925. vec2.set(points[1], this.elementWidth * this.heights.length, this.maxValue);
  8926. vec2.set(points[2], this.elementWidth * this.heights.length, this.minValue);
  8927. vec2.set(points[3], 0, this.minValue);
  8928. out.setFromPoints(points, position, angle);
  8929. };
  8930. /**
  8931. * Get a line segment in the heightfield
  8932. * @method getLineSegment
  8933. * @param {array} start Where to store the resulting start point
  8934. * @param {array} end Where to store the resulting end point
  8935. * @param {number} i
  8936. */
  8937. Heightfield.prototype.getLineSegment = function(start, end, i){
  8938. var data = this.heights;
  8939. var width = this.elementWidth;
  8940. vec2.set(start, i * width, data[i]);
  8941. vec2.set(end, (i + 1) * width, data[i + 1]);
  8942. };
  8943. Heightfield.prototype.getSegmentIndex = function(position){
  8944. return Math.floor(position[0] / this.elementWidth);
  8945. };
  8946. Heightfield.prototype.getClampedSegmentIndex = function(position){
  8947. var i = this.getSegmentIndex(position);
  8948. i = Math.min(this.heights.length, Math.max(i, 0)); // clamp
  8949. return i;
  8950. };
  8951. var intersectHeightfield_hitPointWorld = vec2.create();
  8952. var intersectHeightfield_worldNormal = vec2.create();
  8953. var intersectHeightfield_l0 = vec2.create();
  8954. var intersectHeightfield_l1 = vec2.create();
  8955. var intersectHeightfield_localFrom = vec2.create();
  8956. var intersectHeightfield_localTo = vec2.create();
  8957. var intersectHeightfield_unit_y = vec2.fromValues(0,1);
  8958. // Returns 1 if the lines intersect, otherwise 0.
  8959. function getLineSegmentsIntersection (out, p0, p1, p2, p3) {
  8960. var s1_x, s1_y, s2_x, s2_y;
  8961. s1_x = p1[0] - p0[0];
  8962. s1_y = p1[1] - p0[1];
  8963. s2_x = p3[0] - p2[0];
  8964. s2_y = p3[1] - p2[1];
  8965. var s, t;
  8966. s = (-s1_y * (p0[0] - p2[0]) + s1_x * (p0[1] - p2[1])) / (-s2_x * s1_y + s1_x * s2_y);
  8967. t = ( s2_x * (p0[1] - p2[1]) - s2_y * (p0[0] - p2[0])) / (-s2_x * s1_y + s1_x * s2_y);
  8968. if (s >= 0 && s <= 1 && t >= 0 && t <= 1) { // Collision detected
  8969. var intX = p0[0] + (t * s1_x);
  8970. var intY = p0[1] + (t * s1_y);
  8971. out[0] = intX;
  8972. out[1] = intY;
  8973. return t;
  8974. }
  8975. return -1; // No collision
  8976. }
  8977. /**
  8978. * @method raycast
  8979. * @param {RayResult} result
  8980. * @param {Ray} ray
  8981. * @param {array} position
  8982. * @param {number} angle
  8983. */
  8984. Heightfield.prototype.raycast = function(result, ray, position, angle){
  8985. var from = ray.from;
  8986. var to = ray.to;
  8987. var direction = ray.direction;
  8988. var hitPointWorld = intersectHeightfield_hitPointWorld;
  8989. var worldNormal = intersectHeightfield_worldNormal;
  8990. var l0 = intersectHeightfield_l0;
  8991. var l1 = intersectHeightfield_l1;
  8992. var localFrom = intersectHeightfield_localFrom;
  8993. var localTo = intersectHeightfield_localTo;
  8994. // get local ray start and end
  8995. vec2.toLocalFrame(localFrom, from, position, angle);
  8996. vec2.toLocalFrame(localTo, to, position, angle);
  8997. // Get the segment range
  8998. var i0 = this.getClampedSegmentIndex(localFrom);
  8999. var i1 = this.getClampedSegmentIndex(localTo);
  9000. if(i0 > i1){
  9001. var tmp = i0;
  9002. i0 = i1;
  9003. i1 = tmp;
  9004. }
  9005. // The segments
  9006. for(var i=0; i<this.heights.length - 1; i++){
  9007. this.getLineSegment(l0, l1, i);
  9008. var t = vec2.getLineSegmentsIntersectionFraction(localFrom, localTo, l0, l1);
  9009. if(t >= 0){
  9010. vec2.sub(worldNormal, l1, l0);
  9011. vec2.rotate(worldNormal, worldNormal, angle + Math.PI / 2);
  9012. vec2.normalize(worldNormal, worldNormal);
  9013. ray.reportIntersection(result, t, worldNormal, -1);
  9014. if(result.shouldStop(ray)){
  9015. return;
  9016. }
  9017. }
  9018. }
  9019. };
  9020. },{"../math/vec2":30,"../utils/Utils":57,"./Shape":45}],42:[function(_dereq_,module,exports){
  9021. var Shape = _dereq_('./Shape')
  9022. , vec2 = _dereq_('../math/vec2');
  9023. module.exports = Line;
  9024. /**
  9025. * Line shape class. The line shape is along the x direction, and stretches from [-length/2, 0] to [length/2,0].
  9026. * @class Line
  9027. * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.)
  9028. * @param {Number} [options.length=1] The total length of the line
  9029. * @extends Shape
  9030. * @constructor
  9031. */
  9032. function Line(options){
  9033. if(typeof(arguments[0]) === 'number'){
  9034. options = {
  9035. length: arguments[0]
  9036. };
  9037. console.warn('The Line constructor signature has changed. Please use the following format: new Line({ length: 1, ... })');
  9038. }
  9039. options = options || {};
  9040. /**
  9041. * Length of this line
  9042. * @property {Number} length
  9043. * @default 1
  9044. */
  9045. this.length = options.length || 1;
  9046. options.type = Shape.LINE;
  9047. Shape.call(this, options);
  9048. }
  9049. Line.prototype = new Shape();
  9050. Line.prototype.constructor = Line;
  9051. Line.prototype.computeMomentOfInertia = function(mass){
  9052. return mass * Math.pow(this.length,2) / 12;
  9053. };
  9054. Line.prototype.updateBoundingRadius = function(){
  9055. this.boundingRadius = this.length/2;
  9056. };
  9057. var points = [vec2.create(),vec2.create()];
  9058. /**
  9059. * @method computeAABB
  9060. * @param {AABB} out The resulting AABB.
  9061. * @param {Array} position
  9062. * @param {Number} angle
  9063. */
  9064. Line.prototype.computeAABB = function(out, position, angle){
  9065. var l2 = this.length / 2;
  9066. vec2.set(points[0], -l2, 0);
  9067. vec2.set(points[1], l2, 0);
  9068. out.setFromPoints(points,position,angle,0);
  9069. };
  9070. var raycast_hitPoint = vec2.create();
  9071. var raycast_normal = vec2.create();
  9072. var raycast_l0 = vec2.create();
  9073. var raycast_l1 = vec2.create();
  9074. var raycast_unit_y = vec2.fromValues(0,1);
  9075. /**
  9076. * @method raycast
  9077. * @param {RaycastResult} result
  9078. * @param {Ray} ray
  9079. * @param {number} angle
  9080. * @param {array} position
  9081. */
  9082. Line.prototype.raycast = function(result, ray, position, angle){
  9083. var from = ray.from;
  9084. var to = ray.to;
  9085. var l0 = raycast_l0;
  9086. var l1 = raycast_l1;
  9087. // get start and end of the line
  9088. var halfLen = this.length / 2;
  9089. vec2.set(l0, -halfLen, 0);
  9090. vec2.set(l1, halfLen, 0);
  9091. vec2.toGlobalFrame(l0, l0, position, angle);
  9092. vec2.toGlobalFrame(l1, l1, position, angle);
  9093. var fraction = vec2.getLineSegmentsIntersectionFraction(l0, l1, from, to);
  9094. if(fraction >= 0){
  9095. var normal = raycast_normal;
  9096. vec2.rotate(normal, raycast_unit_y, angle); // todo: this should depend on which side the ray comes from
  9097. ray.reportIntersection(result, fraction, normal, -1);
  9098. }
  9099. };
  9100. },{"../math/vec2":30,"./Shape":45}],43:[function(_dereq_,module,exports){
  9101. var Shape = _dereq_('./Shape')
  9102. , vec2 = _dereq_('../math/vec2');
  9103. module.exports = Particle;
  9104. /**
  9105. * Particle shape class.
  9106. * @class Particle
  9107. * @constructor
  9108. * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.)
  9109. * @extends Shape
  9110. */
  9111. function Particle(options){
  9112. options = options || {};
  9113. options.type = Shape.PARTICLE;
  9114. Shape.call(this, options);
  9115. }
  9116. Particle.prototype = new Shape();
  9117. Particle.prototype.constructor = Particle;
  9118. Particle.prototype.computeMomentOfInertia = function(mass){
  9119. return 0; // Can't rotate a particle
  9120. };
  9121. Particle.prototype.updateBoundingRadius = function(){
  9122. this.boundingRadius = 0;
  9123. };
  9124. /**
  9125. * @method computeAABB
  9126. * @param {AABB} out
  9127. * @param {Array} position
  9128. * @param {Number} angle
  9129. */
  9130. Particle.prototype.computeAABB = function(out, position, angle){
  9131. vec2.copy(out.lowerBound, position);
  9132. vec2.copy(out.upperBound, position);
  9133. };
  9134. },{"../math/vec2":30,"./Shape":45}],44:[function(_dereq_,module,exports){
  9135. var Shape = _dereq_('./Shape')
  9136. , vec2 = _dereq_('../math/vec2')
  9137. , Utils = _dereq_('../utils/Utils');
  9138. module.exports = Plane;
  9139. /**
  9140. * Plane shape class. The plane is facing in the Y direction.
  9141. * @class Plane
  9142. * @extends Shape
  9143. * @constructor
  9144. * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.)
  9145. */
  9146. function Plane(options){
  9147. options = options || {};
  9148. options.type = Shape.PLANE;
  9149. Shape.call(this, options);
  9150. }
  9151. Plane.prototype = new Shape();
  9152. Plane.prototype.constructor = Plane;
  9153. /**
  9154. * Compute moment of inertia
  9155. * @method computeMomentOfInertia
  9156. */
  9157. Plane.prototype.computeMomentOfInertia = function(mass){
  9158. return 0; // Plane is infinite. The inertia should therefore be infinty but by convention we set 0 here
  9159. };
  9160. /**
  9161. * Update the bounding radius
  9162. * @method updateBoundingRadius
  9163. */
  9164. Plane.prototype.updateBoundingRadius = function(){
  9165. this.boundingRadius = Number.MAX_VALUE;
  9166. };
  9167. /**
  9168. * @method computeAABB
  9169. * @param {AABB} out
  9170. * @param {Array} position
  9171. * @param {Number} angle
  9172. */
  9173. Plane.prototype.computeAABB = function(out, position, angle){
  9174. var a = angle % (2 * Math.PI);
  9175. var set = vec2.set;
  9176. var max = Number.MAX_VALUE;
  9177. var lowerBound = out.lowerBound;
  9178. var upperBound = out.upperBound;
  9179. if(a === 0){
  9180. // y goes from -inf to 0
  9181. set(lowerBound, -max, -max);
  9182. set(upperBound, max, 0);
  9183. } else if(a === Math.PI / 2){
  9184. // x goes from 0 to inf
  9185. set(lowerBound, 0, -max);
  9186. set(upperBound, max, max);
  9187. } else if(a === Math.PI){
  9188. // y goes from 0 to inf
  9189. set(lowerBound, -max, 0);
  9190. set(upperBound, max, max);
  9191. } else if(a === 3*Math.PI/2){
  9192. // x goes from -inf to 0
  9193. set(lowerBound, -max, -max);
  9194. set(upperBound, 0, max);
  9195. } else {
  9196. // Set max bounds
  9197. set(lowerBound, -max, -max);
  9198. set(upperBound, max, max);
  9199. }
  9200. vec2.add(lowerBound, lowerBound, position);
  9201. vec2.add(upperBound, upperBound, position);
  9202. };
  9203. Plane.prototype.updateArea = function(){
  9204. this.area = Number.MAX_VALUE;
  9205. };
  9206. var intersectPlane_planePointToFrom = vec2.create();
  9207. var intersectPlane_dir_scaled_with_t = vec2.create();
  9208. var intersectPlane_hitPoint = vec2.create();
  9209. var intersectPlane_normal = vec2.create();
  9210. var intersectPlane_len = vec2.create();
  9211. /**
  9212. * @method raycast
  9213. * @param {RayResult} result
  9214. * @param {Ray} ray
  9215. * @param {array} position
  9216. * @param {number} angle
  9217. */
  9218. Plane.prototype.raycast = function(result, ray, position, angle){
  9219. var from = ray.from;
  9220. var to = ray.to;
  9221. var direction = ray.direction;
  9222. var planePointToFrom = intersectPlane_planePointToFrom;
  9223. var dir_scaled_with_t = intersectPlane_dir_scaled_with_t;
  9224. var hitPoint = intersectPlane_hitPoint;
  9225. var normal = intersectPlane_normal;
  9226. var len = intersectPlane_len;
  9227. // Get plane normal
  9228. vec2.set(normal, 0, 1);
  9229. vec2.rotate(normal, normal, angle);
  9230. vec2.sub(len, from, position);
  9231. var planeToFrom = vec2.dot(len, normal);
  9232. vec2.sub(len, to, position);
  9233. var planeToTo = vec2.dot(len, normal);
  9234. if(planeToFrom * planeToTo > 0){
  9235. // "from" and "to" are on the same side of the plane... bail out
  9236. return;
  9237. }
  9238. if(vec2.squaredDistance(from, to) < planeToFrom * planeToFrom){
  9239. return;
  9240. }
  9241. var n_dot_dir = vec2.dot(normal, direction);
  9242. vec2.sub(planePointToFrom, from, position);
  9243. var t = -vec2.dot(normal, planePointToFrom) / n_dot_dir / ray.length;
  9244. ray.reportIntersection(result, t, normal, -1);
  9245. };
  9246. },{"../math/vec2":30,"../utils/Utils":57,"./Shape":45}],45:[function(_dereq_,module,exports){
  9247. module.exports = Shape;
  9248. var vec2 = _dereq_('../math/vec2');
  9249. /**
  9250. * Base class for shapes.
  9251. * @class Shape
  9252. * @constructor
  9253. * @param {object} [options]
  9254. * @param {array} [options.position]
  9255. * @param {number} [options.angle=0]
  9256. * @param {number} [options.collisionGroup=1]
  9257. * @param {number} [options.collisionMask=1]
  9258. * @param {boolean} [options.sensor=false]
  9259. * @param {boolean} [options.collisionResponse=true]
  9260. * @param {object} [options.type=0]
  9261. */
  9262. function Shape(options){
  9263. options = options || {};
  9264. /**
  9265. * The body this shape is attached to. A shape can only be attached to a single body.
  9266. * @property {Body} body
  9267. */
  9268. this.body = null;
  9269. /**
  9270. * Body-local position of the shape.
  9271. * @property {Array} position
  9272. */
  9273. this.position = vec2.fromValues(0,0);
  9274. if(options.position){
  9275. vec2.copy(this.position, options.position);
  9276. }
  9277. /**
  9278. * Body-local angle of the shape.
  9279. * @property {number} angle
  9280. */
  9281. this.angle = options.angle || 0;
  9282. /**
  9283. * The type of the shape. One of:
  9284. *
  9285. * * {{#crossLink "Shape/CIRCLE:property"}}Shape.CIRCLE{{/crossLink}}
  9286. * * {{#crossLink "Shape/PARTICLE:property"}}Shape.PARTICLE{{/crossLink}}
  9287. * * {{#crossLink "Shape/PLANE:property"}}Shape.PLANE{{/crossLink}}
  9288. * * {{#crossLink "Shape/CONVEX:property"}}Shape.CONVEX{{/crossLink}}
  9289. * * {{#crossLink "Shape/LINE:property"}}Shape.LINE{{/crossLink}}
  9290. * * {{#crossLink "Shape/BOX:property"}}Shape.BOX{{/crossLink}}
  9291. * * {{#crossLink "Shape/CAPSULE:property"}}Shape.CAPSULE{{/crossLink}}
  9292. * * {{#crossLink "Shape/HEIGHTFIELD:property"}}Shape.HEIGHTFIELD{{/crossLink}}
  9293. *
  9294. * @property {number} type
  9295. */
  9296. this.type = options.type || 0;
  9297. /**
  9298. * Shape object identifier.
  9299. * @type {Number}
  9300. * @property id
  9301. */
  9302. this.id = Shape.idCounter++;
  9303. /**
  9304. * Bounding circle radius of this shape
  9305. * @property boundingRadius
  9306. * @type {Number}
  9307. */
  9308. this.boundingRadius = 0;
  9309. /**
  9310. * Collision group that this shape belongs to (bit mask). See <a href="http://www.aurelienribon.com/blog/2011/07/box2d-tutorial-collision-filtering/">this tutorial</a>.
  9311. * @property collisionGroup
  9312. * @type {Number}
  9313. * @example
  9314. * // Setup bits for each available group
  9315. * var PLAYER = Math.pow(2,0),
  9316. * ENEMY = Math.pow(2,1),
  9317. * GROUND = Math.pow(2,2)
  9318. *
  9319. * // Put shapes into their groups
  9320. * player1Shape.collisionGroup = PLAYER;
  9321. * player2Shape.collisionGroup = PLAYER;
  9322. * enemyShape .collisionGroup = ENEMY;
  9323. * groundShape .collisionGroup = GROUND;
  9324. *
  9325. * // Assign groups that each shape collide with.
  9326. * // Note that the players can collide with ground and enemies, but not with other players.
  9327. * player1Shape.collisionMask = ENEMY | GROUND;
  9328. * player2Shape.collisionMask = ENEMY | GROUND;
  9329. * enemyShape .collisionMask = PLAYER | GROUND;
  9330. * groundShape .collisionMask = PLAYER | ENEMY;
  9331. *
  9332. * @example
  9333. * // How collision check is done
  9334. * if(shapeA.collisionGroup & shapeB.collisionMask)!=0 && (shapeB.collisionGroup & shapeA.collisionMask)!=0){
  9335. * // The shapes will collide
  9336. * }
  9337. */
  9338. this.collisionGroup = options.collisionGroup !== undefined ? options.collisionGroup : 1;
  9339. /**
  9340. * Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled. That means that this shape will move through other body shapes, but it will still trigger contact events, etc.
  9341. * @property {Boolean} collisionResponse
  9342. */
  9343. this.collisionResponse = options.collisionResponse !== undefined ? options.collisionResponse : true;
  9344. /**
  9345. * Collision mask of this shape. See .collisionGroup.
  9346. * @property collisionMask
  9347. * @type {Number}
  9348. */
  9349. this.collisionMask = options.collisionMask !== undefined ? options.collisionMask : 1;
  9350. /**
  9351. * Material to use in collisions for this Shape. If this is set to null, the world will use default material properties instead.
  9352. * @property material
  9353. * @type {Material}
  9354. */
  9355. this.material = options.material || null;
  9356. /**
  9357. * Area of this shape.
  9358. * @property area
  9359. * @type {Number}
  9360. */
  9361. this.area = 0;
  9362. /**
  9363. * Set to true if you want this shape to be a sensor. A sensor does not generate contacts, but it still reports contact events. This is good if you want to know if a shape is overlapping another shape, without them generating contacts.
  9364. * @property {Boolean} sensor
  9365. */
  9366. this.sensor = options.sensor !== undefined ? options.sensor : false;
  9367. if(this.type){
  9368. this.updateBoundingRadius();
  9369. }
  9370. this.updateArea();
  9371. }
  9372. Shape.idCounter = 0;
  9373. /**
  9374. * @static
  9375. * @property {Number} CIRCLE
  9376. */
  9377. Shape.CIRCLE = 1;
  9378. /**
  9379. * @static
  9380. * @property {Number} PARTICLE
  9381. */
  9382. Shape.PARTICLE = 2;
  9383. /**
  9384. * @static
  9385. * @property {Number} PLANE
  9386. */
  9387. Shape.PLANE = 4;
  9388. /**
  9389. * @static
  9390. * @property {Number} CONVEX
  9391. */
  9392. Shape.CONVEX = 8;
  9393. /**
  9394. * @static
  9395. * @property {Number} LINE
  9396. */
  9397. Shape.LINE = 16;
  9398. /**
  9399. * @static
  9400. * @property {Number} BOX
  9401. */
  9402. Shape.BOX = 32;
  9403. Object.defineProperty(Shape, 'RECTANGLE', {
  9404. get: function() {
  9405. console.warn('Shape.RECTANGLE is deprecated, use Shape.BOX instead.');
  9406. return Shape.BOX;
  9407. }
  9408. });
  9409. /**
  9410. * @static
  9411. * @property {Number} CAPSULE
  9412. */
  9413. Shape.CAPSULE = 64;
  9414. /**
  9415. * @static
  9416. * @property {Number} HEIGHTFIELD
  9417. */
  9418. Shape.HEIGHTFIELD = 128;
  9419. /**
  9420. * Should return the moment of inertia around the Z axis of the body given the total mass. See <a href="http://en.wikipedia.org/wiki/List_of_moments_of_inertia">Wikipedia's list of moments of inertia</a>.
  9421. * @method computeMomentOfInertia
  9422. * @param {Number} mass
  9423. * @return {Number} If the inertia is infinity or if the object simply isn't possible to rotate, return 0.
  9424. */
  9425. Shape.prototype.computeMomentOfInertia = function(mass){};
  9426. /**
  9427. * Returns the bounding circle radius of this shape.
  9428. * @method updateBoundingRadius
  9429. * @return {Number}
  9430. */
  9431. Shape.prototype.updateBoundingRadius = function(){};
  9432. /**
  9433. * Update the .area property of the shape.
  9434. * @method updateArea
  9435. */
  9436. Shape.prototype.updateArea = function(){
  9437. // To be implemented in all subclasses
  9438. };
  9439. /**
  9440. * Compute the world axis-aligned bounding box (AABB) of this shape.
  9441. * @method computeAABB
  9442. * @param {AABB} out The resulting AABB.
  9443. * @param {Array} position World position of the shape.
  9444. * @param {Number} angle World angle of the shape.
  9445. */
  9446. Shape.prototype.computeAABB = function(out, position, angle){
  9447. // To be implemented in each subclass
  9448. };
  9449. /**
  9450. * Perform raycasting on this shape.
  9451. * @method raycast
  9452. * @param {RayResult} result Where to store the resulting data.
  9453. * @param {Ray} ray The Ray that you want to use for raycasting.
  9454. * @param {array} position World position of the shape (the .position property will be ignored).
  9455. * @param {number} angle World angle of the shape (the .angle property will be ignored).
  9456. */
  9457. Shape.prototype.raycast = function(result, ray, position, angle){
  9458. // To be implemented in each subclass
  9459. };
  9460. },{"../math/vec2":30}],46:[function(_dereq_,module,exports){
  9461. var vec2 = _dereq_('../math/vec2')
  9462. , Solver = _dereq_('./Solver')
  9463. , Utils = _dereq_('../utils/Utils')
  9464. , FrictionEquation = _dereq_('../equations/FrictionEquation');
  9465. module.exports = GSSolver;
  9466. /**
  9467. * Iterative Gauss-Seidel constraint equation solver.
  9468. *
  9469. * @class GSSolver
  9470. * @constructor
  9471. * @extends Solver
  9472. * @param {Object} [options]
  9473. * @param {Number} [options.iterations=10]
  9474. * @param {Number} [options.tolerance=0]
  9475. */
  9476. function GSSolver(options){
  9477. Solver.call(this,options,Solver.GS);
  9478. options = options || {};
  9479. /**
  9480. * The max number of iterations to do when solving. More gives better results, but is more expensive.
  9481. * @property iterations
  9482. * @type {Number}
  9483. */
  9484. this.iterations = options.iterations || 10;
  9485. /**
  9486. * The error tolerance, per constraint. If the total error is below this limit, the solver will stop iterating. Set to zero for as good solution as possible, but to something larger than zero to make computations faster.
  9487. * @property tolerance
  9488. * @type {Number}
  9489. * @default 1e-7
  9490. */
  9491. this.tolerance = options.tolerance || 1e-7;
  9492. this.arrayStep = 30;
  9493. this.lambda = new Utils.ARRAY_TYPE(this.arrayStep);
  9494. this.Bs = new Utils.ARRAY_TYPE(this.arrayStep);
  9495. this.invCs = new Utils.ARRAY_TYPE(this.arrayStep);
  9496. /**
  9497. * Set to true to set all right hand side terms to zero when solving. Can be handy for a few applications.
  9498. * @property useZeroRHS
  9499. * @type {Boolean}
  9500. */
  9501. this.useZeroRHS = false;
  9502. /**
  9503. * Number of solver iterations that are done to approximate normal forces. When these iterations are done, friction force will be computed from the contact normal forces. These friction forces will override any other friction forces set from the World for example.
  9504. * The solver will use less iterations if the solution is below the .tolerance.
  9505. * @property frictionIterations
  9506. * @type {Number}
  9507. */
  9508. this.frictionIterations = 0;
  9509. /**
  9510. * The number of iterations that were made during the last solve. If .tolerance is zero, this value will always be equal to .iterations, but if .tolerance is larger than zero, and the solver can quit early, then this number will be somewhere between 1 and .iterations.
  9511. * @property {Number} usedIterations
  9512. */
  9513. this.usedIterations = 0;
  9514. }
  9515. GSSolver.prototype = new Solver();
  9516. GSSolver.prototype.constructor = GSSolver;
  9517. function setArrayZero(array){
  9518. var l = array.length;
  9519. while(l--){
  9520. array[l] = +0.0;
  9521. }
  9522. }
  9523. /**
  9524. * Solve the system of equations
  9525. * @method solve
  9526. * @param {Number} h Time step
  9527. * @param {World} world World to solve
  9528. */
  9529. GSSolver.prototype.solve = function(h, world){
  9530. this.sortEquations();
  9531. var iter = 0,
  9532. maxIter = this.iterations,
  9533. maxFrictionIter = this.frictionIterations,
  9534. equations = this.equations,
  9535. Neq = equations.length,
  9536. tolSquared = Math.pow(this.tolerance*Neq, 2),
  9537. bodies = world.bodies,
  9538. Nbodies = world.bodies.length,
  9539. add = vec2.add,
  9540. set = vec2.set,
  9541. useZeroRHS = this.useZeroRHS,
  9542. lambda = this.lambda;
  9543. this.usedIterations = 0;
  9544. if(Neq){
  9545. for(var i=0; i!==Nbodies; i++){
  9546. var b = bodies[i];
  9547. // Update solve mass
  9548. b.updateSolveMassProperties();
  9549. }
  9550. }
  9551. // Things that does not change during iteration can be computed once
  9552. if(lambda.length < Neq){
  9553. lambda = this.lambda = new Utils.ARRAY_TYPE(Neq + this.arrayStep);
  9554. this.Bs = new Utils.ARRAY_TYPE(Neq + this.arrayStep);
  9555. this.invCs = new Utils.ARRAY_TYPE(Neq + this.arrayStep);
  9556. }
  9557. setArrayZero(lambda);
  9558. var invCs = this.invCs,
  9559. Bs = this.Bs,
  9560. lambda = this.lambda;
  9561. for(var i=0; i!==equations.length; i++){
  9562. var c = equations[i];
  9563. if(c.timeStep !== h || c.needsUpdate){
  9564. c.timeStep = h;
  9565. c.update();
  9566. }
  9567. Bs[i] = c.computeB(c.a,c.b,h);
  9568. invCs[i] = c.computeInvC(c.epsilon);
  9569. }
  9570. var q, B, c, deltalambdaTot,i,j;
  9571. if(Neq !== 0){
  9572. for(i=0; i!==Nbodies; i++){
  9573. var b = bodies[i];
  9574. // Reset vlambda
  9575. b.resetConstraintVelocity();
  9576. }
  9577. if(maxFrictionIter){
  9578. // Iterate over contact equations to get normal forces
  9579. for(iter=0; iter!==maxFrictionIter; iter++){
  9580. // Accumulate the total error for each iteration.
  9581. deltalambdaTot = 0.0;
  9582. for(j=0; j!==Neq; j++){
  9583. c = equations[j];
  9584. var deltalambda = GSSolver.iterateEquation(j,c,c.epsilon,Bs,invCs,lambda,useZeroRHS,h,iter);
  9585. deltalambdaTot += Math.abs(deltalambda);
  9586. }
  9587. this.usedIterations++;
  9588. // If the total error is small enough - stop iterate
  9589. if(deltalambdaTot*deltalambdaTot <= tolSquared){
  9590. break;
  9591. }
  9592. }
  9593. GSSolver.updateMultipliers(equations, lambda, 1/h);
  9594. // Set computed friction force
  9595. for(j=0; j!==Neq; j++){
  9596. var eq = equations[j];
  9597. if(eq instanceof FrictionEquation){
  9598. var f = 0.0;
  9599. for(var k=0; k!==eq.contactEquations.length; k++){
  9600. f += eq.contactEquations[k].multiplier;
  9601. }
  9602. f *= eq.frictionCoefficient / eq.contactEquations.length;
  9603. eq.maxForce = f;
  9604. eq.minForce = -f;
  9605. }
  9606. }
  9607. }
  9608. // Iterate over all equations
  9609. for(iter=0; iter!==maxIter; iter++){
  9610. // Accumulate the total error for each iteration.
  9611. deltalambdaTot = 0.0;
  9612. for(j=0; j!==Neq; j++){
  9613. c = equations[j];
  9614. var deltalambda = GSSolver.iterateEquation(j,c,c.epsilon,Bs,invCs,lambda,useZeroRHS,h,iter);
  9615. deltalambdaTot += Math.abs(deltalambda);
  9616. }
  9617. this.usedIterations++;
  9618. // If the total error is small enough - stop iterate
  9619. if(deltalambdaTot*deltalambdaTot <= tolSquared){
  9620. break;
  9621. }
  9622. }
  9623. // Add result to velocity
  9624. for(i=0; i!==Nbodies; i++){
  9625. bodies[i].addConstraintVelocity();
  9626. }
  9627. GSSolver.updateMultipliers(equations, lambda, 1/h);
  9628. }
  9629. };
  9630. // Sets the .multiplier property of each equation
  9631. GSSolver.updateMultipliers = function(equations, lambda, invDt){
  9632. // Set the .multiplier property of each equation
  9633. var l = equations.length;
  9634. while(l--){
  9635. equations[l].multiplier = lambda[l] * invDt;
  9636. }
  9637. };
  9638. GSSolver.iterateEquation = function(j,eq,eps,Bs,invCs,lambda,useZeroRHS,dt,iter){
  9639. // Compute iteration
  9640. var B = Bs[j],
  9641. invC = invCs[j],
  9642. lambdaj = lambda[j],
  9643. GWlambda = eq.computeGWlambda();
  9644. var maxForce = eq.maxForce,
  9645. minForce = eq.minForce;
  9646. if(useZeroRHS){
  9647. B = 0;
  9648. }
  9649. var deltalambda = invC * ( B - GWlambda - eps * lambdaj );
  9650. // Clamp if we are not within the min/max interval
  9651. var lambdaj_plus_deltalambda = lambdaj + deltalambda;
  9652. if(lambdaj_plus_deltalambda < minForce*dt){
  9653. deltalambda = minForce*dt - lambdaj;
  9654. } else if(lambdaj_plus_deltalambda > maxForce*dt){
  9655. deltalambda = maxForce*dt - lambdaj;
  9656. }
  9657. lambda[j] += deltalambda;
  9658. eq.addToWlambda(deltalambda);
  9659. return deltalambda;
  9660. };
  9661. },{"../equations/FrictionEquation":23,"../math/vec2":30,"../utils/Utils":57,"./Solver":47}],47:[function(_dereq_,module,exports){
  9662. var Utils = _dereq_('../utils/Utils')
  9663. , EventEmitter = _dereq_('../events/EventEmitter');
  9664. module.exports = Solver;
  9665. /**
  9666. * Base class for constraint solvers.
  9667. * @class Solver
  9668. * @constructor
  9669. * @extends EventEmitter
  9670. */
  9671. function Solver(options,type){
  9672. options = options || {};
  9673. EventEmitter.call(this);
  9674. this.type = type;
  9675. /**
  9676. * Current equations in the solver.
  9677. *
  9678. * @property equations
  9679. * @type {Array}
  9680. */
  9681. this.equations = [];
  9682. /**
  9683. * Function that is used to sort all equations before each solve.
  9684. * @property equationSortFunction
  9685. * @type {function|boolean}
  9686. */
  9687. this.equationSortFunction = options.equationSortFunction || false;
  9688. }
  9689. Solver.prototype = new EventEmitter();
  9690. Solver.prototype.constructor = Solver;
  9691. /**
  9692. * Method to be implemented in each subclass
  9693. * @method solve
  9694. * @param {Number} dt
  9695. * @param {World} world
  9696. */
  9697. Solver.prototype.solve = function(dt,world){
  9698. throw new Error("Solver.solve should be implemented by subclasses!");
  9699. };
  9700. var mockWorld = {bodies:[]};
  9701. /**
  9702. * Solves all constraints in an island.
  9703. * @method solveIsland
  9704. * @param {Number} dt
  9705. * @param {Island} island
  9706. */
  9707. Solver.prototype.solveIsland = function(dt,island){
  9708. this.removeAllEquations();
  9709. if(island.equations.length){
  9710. // Add equations to solver
  9711. this.addEquations(island.equations);
  9712. mockWorld.bodies.length = 0;
  9713. island.getBodies(mockWorld.bodies);
  9714. // Solve
  9715. if(mockWorld.bodies.length){
  9716. this.solve(dt,mockWorld);
  9717. }
  9718. }
  9719. };
  9720. /**
  9721. * Sort all equations using the .equationSortFunction. Should be called by subclasses before solving.
  9722. * @method sortEquations
  9723. */
  9724. Solver.prototype.sortEquations = function(){
  9725. if(this.equationSortFunction){
  9726. this.equations.sort(this.equationSortFunction);
  9727. }
  9728. };
  9729. /**
  9730. * Add an equation to be solved.
  9731. *
  9732. * @method addEquation
  9733. * @param {Equation} eq
  9734. */
  9735. Solver.prototype.addEquation = function(eq){
  9736. if(eq.enabled){
  9737. this.equations.push(eq);
  9738. }
  9739. };
  9740. /**
  9741. * Add equations. Same as .addEquation, but this time the argument is an array of Equations
  9742. *
  9743. * @method addEquations
  9744. * @param {Array} eqs
  9745. */
  9746. Solver.prototype.addEquations = function(eqs){
  9747. //Utils.appendArray(this.equations,eqs);
  9748. for(var i=0, N=eqs.length; i!==N; i++){
  9749. var eq = eqs[i];
  9750. if(eq.enabled){
  9751. this.equations.push(eq);
  9752. }
  9753. }
  9754. };
  9755. /**
  9756. * Remove an equation.
  9757. *
  9758. * @method removeEquation
  9759. * @param {Equation} eq
  9760. */
  9761. Solver.prototype.removeEquation = function(eq){
  9762. var i = this.equations.indexOf(eq);
  9763. if(i !== -1){
  9764. this.equations.splice(i,1);
  9765. }
  9766. };
  9767. /**
  9768. * Remove all currently added equations.
  9769. *
  9770. * @method removeAllEquations
  9771. */
  9772. Solver.prototype.removeAllEquations = function(){
  9773. this.equations.length=0;
  9774. };
  9775. Solver.GS = 1;
  9776. Solver.ISLAND = 2;
  9777. },{"../events/EventEmitter":26,"../utils/Utils":57}],48:[function(_dereq_,module,exports){
  9778. var ContactEquation = _dereq_('../equations/ContactEquation');
  9779. var Pool = _dereq_('./Pool');
  9780. module.exports = ContactEquationPool;
  9781. /**
  9782. * @class
  9783. */
  9784. function ContactEquationPool() {
  9785. Pool.apply(this, arguments);
  9786. }
  9787. ContactEquationPool.prototype = new Pool();
  9788. ContactEquationPool.prototype.constructor = ContactEquationPool;
  9789. /**
  9790. * @method create
  9791. * @return {ContactEquation}
  9792. */
  9793. ContactEquationPool.prototype.create = function () {
  9794. return new ContactEquation();
  9795. };
  9796. /**
  9797. * @method destroy
  9798. * @param {ContactEquation} equation
  9799. * @return {ContactEquationPool}
  9800. */
  9801. ContactEquationPool.prototype.destroy = function (equation) {
  9802. equation.bodyA = equation.bodyB = null;
  9803. return this;
  9804. };
  9805. },{"../equations/ContactEquation":21,"./Pool":55}],49:[function(_dereq_,module,exports){
  9806. var FrictionEquation = _dereq_('../equations/FrictionEquation');
  9807. var Pool = _dereq_('./Pool');
  9808. module.exports = FrictionEquationPool;
  9809. /**
  9810. * @class
  9811. */
  9812. function FrictionEquationPool() {
  9813. Pool.apply(this, arguments);
  9814. }
  9815. FrictionEquationPool.prototype = new Pool();
  9816. FrictionEquationPool.prototype.constructor = FrictionEquationPool;
  9817. /**
  9818. * @method create
  9819. * @return {FrictionEquation}
  9820. */
  9821. FrictionEquationPool.prototype.create = function () {
  9822. return new FrictionEquation();
  9823. };
  9824. /**
  9825. * @method destroy
  9826. * @param {FrictionEquation} equation
  9827. * @return {FrictionEquationPool}
  9828. */
  9829. FrictionEquationPool.prototype.destroy = function (equation) {
  9830. equation.bodyA = equation.bodyB = null;
  9831. return this;
  9832. };
  9833. },{"../equations/FrictionEquation":23,"./Pool":55}],50:[function(_dereq_,module,exports){
  9834. var IslandNode = _dereq_('../world/IslandNode');
  9835. var Pool = _dereq_('./Pool');
  9836. module.exports = IslandNodePool;
  9837. /**
  9838. * @class
  9839. */
  9840. function IslandNodePool() {
  9841. Pool.apply(this, arguments);
  9842. }
  9843. IslandNodePool.prototype = new Pool();
  9844. IslandNodePool.prototype.constructor = IslandNodePool;
  9845. /**
  9846. * @method create
  9847. * @return {IslandNode}
  9848. */
  9849. IslandNodePool.prototype.create = function () {
  9850. return new IslandNode();
  9851. };
  9852. /**
  9853. * @method destroy
  9854. * @param {IslandNode} node
  9855. * @return {IslandNodePool}
  9856. */
  9857. IslandNodePool.prototype.destroy = function (node) {
  9858. node.reset();
  9859. return this;
  9860. };
  9861. },{"../world/IslandNode":60,"./Pool":55}],51:[function(_dereq_,module,exports){
  9862. var Island = _dereq_('../world/Island');
  9863. var Pool = _dereq_('./Pool');
  9864. module.exports = IslandPool;
  9865. /**
  9866. * @class
  9867. */
  9868. function IslandPool() {
  9869. Pool.apply(this, arguments);
  9870. }
  9871. IslandPool.prototype = new Pool();
  9872. IslandPool.prototype.constructor = IslandPool;
  9873. /**
  9874. * @method create
  9875. * @return {Island}
  9876. */
  9877. IslandPool.prototype.create = function () {
  9878. return new Island();
  9879. };
  9880. /**
  9881. * @method destroy
  9882. * @param {Island} island
  9883. * @return {IslandPool}
  9884. */
  9885. IslandPool.prototype.destroy = function (island) {
  9886. island.reset();
  9887. return this;
  9888. };
  9889. },{"../world/Island":58,"./Pool":55}],52:[function(_dereq_,module,exports){
  9890. var TupleDictionary = _dereq_('./TupleDictionary');
  9891. var OverlapKeeperRecord = _dereq_('./OverlapKeeperRecord');
  9892. var OverlapKeeperRecordPool = _dereq_('./OverlapKeeperRecordPool');
  9893. var Utils = _dereq_('./Utils');
  9894. module.exports = OverlapKeeper;
  9895. /**
  9896. * Keeps track of overlaps in the current state and the last step state.
  9897. * @class OverlapKeeper
  9898. * @constructor
  9899. */
  9900. function OverlapKeeper() {
  9901. this.overlappingShapesLastState = new TupleDictionary();
  9902. this.overlappingShapesCurrentState = new TupleDictionary();
  9903. this.recordPool = new OverlapKeeperRecordPool({ size: 16 });
  9904. this.tmpDict = new TupleDictionary();
  9905. this.tmpArray1 = [];
  9906. }
  9907. /**
  9908. * Ticks one step forward in time. This will move the current overlap state to the "old" overlap state, and create a new one as current.
  9909. * @method tick
  9910. */
  9911. OverlapKeeper.prototype.tick = function() {
  9912. var last = this.overlappingShapesLastState;
  9913. var current = this.overlappingShapesCurrentState;
  9914. // Save old objects into pool
  9915. var l = last.keys.length;
  9916. while(l--){
  9917. var key = last.keys[l];
  9918. var lastObject = last.getByKey(key);
  9919. var currentObject = current.getByKey(key);
  9920. if(lastObject){
  9921. // The record is only used in the "last" dict, and will be removed. We might as well pool it.
  9922. this.recordPool.release(lastObject);
  9923. }
  9924. }
  9925. // Clear last object
  9926. last.reset();
  9927. // Transfer from new object to old
  9928. last.copy(current);
  9929. // Clear current object
  9930. current.reset();
  9931. };
  9932. /**
  9933. * @method setOverlapping
  9934. * @param {Body} bodyA
  9935. * @param {Body} shapeA
  9936. * @param {Body} bodyB
  9937. * @param {Body} shapeB
  9938. */
  9939. OverlapKeeper.prototype.setOverlapping = function(bodyA, shapeA, bodyB, shapeB) {
  9940. var last = this.overlappingShapesLastState;
  9941. var current = this.overlappingShapesCurrentState;
  9942. // Store current contact state
  9943. if(!current.get(shapeA.id, shapeB.id)){
  9944. var data = this.recordPool.get();
  9945. data.set(bodyA, shapeA, bodyB, shapeB);
  9946. current.set(shapeA.id, shapeB.id, data);
  9947. }
  9948. };
  9949. OverlapKeeper.prototype.getNewOverlaps = function(result){
  9950. return this.getDiff(this.overlappingShapesLastState, this.overlappingShapesCurrentState, result);
  9951. };
  9952. OverlapKeeper.prototype.getEndOverlaps = function(result){
  9953. return this.getDiff(this.overlappingShapesCurrentState, this.overlappingShapesLastState, result);
  9954. };
  9955. /**
  9956. * Checks if two bodies are currently overlapping.
  9957. * @method bodiesAreOverlapping
  9958. * @param {Body} bodyA
  9959. * @param {Body} bodyB
  9960. * @return {boolean}
  9961. */
  9962. OverlapKeeper.prototype.bodiesAreOverlapping = function(bodyA, bodyB){
  9963. var current = this.overlappingShapesCurrentState;
  9964. var l = current.keys.length;
  9965. while(l--){
  9966. var key = current.keys[l];
  9967. var data = current.data[key];
  9968. if((data.bodyA === bodyA && data.bodyB === bodyB) || data.bodyA === bodyB && data.bodyB === bodyA){
  9969. return true;
  9970. }
  9971. }
  9972. return false;
  9973. };
  9974. OverlapKeeper.prototype.getDiff = function(dictA, dictB, result){
  9975. var result = result || [];
  9976. var last = dictA;
  9977. var current = dictB;
  9978. result.length = 0;
  9979. var l = current.keys.length;
  9980. while(l--){
  9981. var key = current.keys[l];
  9982. var data = current.data[key];
  9983. if(!data){
  9984. throw new Error('Key '+key+' had no data!');
  9985. }
  9986. var lastData = last.data[key];
  9987. if(!lastData){
  9988. // Not overlapping in last state, but in current.
  9989. result.push(data);
  9990. }
  9991. }
  9992. return result;
  9993. };
  9994. OverlapKeeper.prototype.isNewOverlap = function(shapeA, shapeB){
  9995. var idA = shapeA.id|0,
  9996. idB = shapeB.id|0;
  9997. var last = this.overlappingShapesLastState;
  9998. var current = this.overlappingShapesCurrentState;
  9999. // Not in last but in new
  10000. return !!!last.get(idA, idB) && !!current.get(idA, idB);
  10001. };
  10002. OverlapKeeper.prototype.getNewBodyOverlaps = function(result){
  10003. this.tmpArray1.length = 0;
  10004. var overlaps = this.getNewOverlaps(this.tmpArray1);
  10005. return this.getBodyDiff(overlaps, result);
  10006. };
  10007. OverlapKeeper.prototype.getEndBodyOverlaps = function(result){
  10008. this.tmpArray1.length = 0;
  10009. var overlaps = this.getEndOverlaps(this.tmpArray1);
  10010. return this.getBodyDiff(overlaps, result);
  10011. };
  10012. OverlapKeeper.prototype.getBodyDiff = function(overlaps, result){
  10013. result = result || [];
  10014. var accumulator = this.tmpDict;
  10015. var l = overlaps.length;
  10016. while(l--){
  10017. var data = overlaps[l];
  10018. // Since we use body id's for the accumulator, these will be a subset of the original one
  10019. accumulator.set(data.bodyA.id|0, data.bodyB.id|0, data);
  10020. }
  10021. l = accumulator.keys.length;
  10022. while(l--){
  10023. var data = accumulator.getByKey(accumulator.keys[l]);
  10024. if(data){
  10025. result.push(data.bodyA, data.bodyB);
  10026. }
  10027. }
  10028. accumulator.reset();
  10029. return result;
  10030. };
  10031. },{"./OverlapKeeperRecord":53,"./OverlapKeeperRecordPool":54,"./TupleDictionary":56,"./Utils":57}],53:[function(_dereq_,module,exports){
  10032. module.exports = OverlapKeeperRecord;
  10033. /**
  10034. * Overlap data container for the OverlapKeeper
  10035. * @class OverlapKeeperRecord
  10036. * @constructor
  10037. * @param {Body} bodyA
  10038. * @param {Shape} shapeA
  10039. * @param {Body} bodyB
  10040. * @param {Shape} shapeB
  10041. */
  10042. function OverlapKeeperRecord(bodyA, shapeA, bodyB, shapeB){
  10043. /**
  10044. * @property {Shape} shapeA
  10045. */
  10046. this.shapeA = shapeA;
  10047. /**
  10048. * @property {Shape} shapeB
  10049. */
  10050. this.shapeB = shapeB;
  10051. /**
  10052. * @property {Body} bodyA
  10053. */
  10054. this.bodyA = bodyA;
  10055. /**
  10056. * @property {Body} bodyB
  10057. */
  10058. this.bodyB = bodyB;
  10059. }
  10060. /**
  10061. * Set the data for the record
  10062. * @method set
  10063. * @param {Body} bodyA
  10064. * @param {Shape} shapeA
  10065. * @param {Body} bodyB
  10066. * @param {Shape} shapeB
  10067. */
  10068. OverlapKeeperRecord.prototype.set = function(bodyA, shapeA, bodyB, shapeB){
  10069. OverlapKeeperRecord.call(this, bodyA, shapeA, bodyB, shapeB);
  10070. };
  10071. },{}],54:[function(_dereq_,module,exports){
  10072. var OverlapKeeperRecord = _dereq_('./OverlapKeeperRecord');
  10073. var Pool = _dereq_('./Pool');
  10074. module.exports = OverlapKeeperRecordPool;
  10075. /**
  10076. * @class
  10077. */
  10078. function OverlapKeeperRecordPool() {
  10079. Pool.apply(this, arguments);
  10080. }
  10081. OverlapKeeperRecordPool.prototype = new Pool();
  10082. OverlapKeeperRecordPool.prototype.constructor = OverlapKeeperRecordPool;
  10083. /**
  10084. * @method create
  10085. * @return {OverlapKeeperRecord}
  10086. */
  10087. OverlapKeeperRecordPool.prototype.create = function () {
  10088. return new OverlapKeeperRecord();
  10089. };
  10090. /**
  10091. * @method destroy
  10092. * @param {OverlapKeeperRecord} record
  10093. * @return {OverlapKeeperRecordPool}
  10094. */
  10095. OverlapKeeperRecordPool.prototype.destroy = function (record) {
  10096. record.bodyA = record.bodyB = record.shapeA = record.shapeB = null;
  10097. return this;
  10098. };
  10099. },{"./OverlapKeeperRecord":53,"./Pool":55}],55:[function(_dereq_,module,exports){
  10100. module.exports = Pool;
  10101. /**
  10102. * @class Object pooling utility.
  10103. */
  10104. function Pool(options) {
  10105. options = options || {};
  10106. /**
  10107. * @property {Array} objects
  10108. * @type {Array}
  10109. */
  10110. this.objects = [];
  10111. if(options.size !== undefined){
  10112. this.resize(options.size);
  10113. }
  10114. }
  10115. /**
  10116. * @method resize
  10117. * @param {number} size
  10118. * @return {Pool} Self, for chaining
  10119. */
  10120. Pool.prototype.resize = function (size) {
  10121. var objects = this.objects;
  10122. while (objects.length > size) {
  10123. objects.pop();
  10124. }
  10125. while (objects.length < size) {
  10126. objects.push(this.create());
  10127. }
  10128. return this;
  10129. };
  10130. /**
  10131. * Get an object from the pool or create a new instance.
  10132. * @method get
  10133. * @return {Object}
  10134. */
  10135. Pool.prototype.get = function () {
  10136. var objects = this.objects;
  10137. return objects.length ? objects.pop() : this.create();
  10138. };
  10139. /**
  10140. * Clean up and put the object back into the pool for later use.
  10141. * @method release
  10142. * @param {Object} object
  10143. * @return {Pool} Self for chaining
  10144. */
  10145. Pool.prototype.release = function (object) {
  10146. this.destroy(object);
  10147. this.objects.push(object);
  10148. return this;
  10149. };
  10150. },{}],56:[function(_dereq_,module,exports){
  10151. var Utils = _dereq_('./Utils');
  10152. module.exports = TupleDictionary;
  10153. /**
  10154. * @class TupleDictionary
  10155. * @constructor
  10156. */
  10157. function TupleDictionary() {
  10158. /**
  10159. * The data storage
  10160. * @property data
  10161. * @type {Object}
  10162. */
  10163. this.data = {};
  10164. /**
  10165. * Keys that are currently used.
  10166. * @property {Array} keys
  10167. */
  10168. this.keys = [];
  10169. }
  10170. /**
  10171. * Generate a key given two integers
  10172. * @method getKey
  10173. * @param {number} i
  10174. * @param {number} j
  10175. * @return {string}
  10176. */
  10177. TupleDictionary.prototype.getKey = function(id1, id2) {
  10178. id1 = id1|0;
  10179. id2 = id2|0;
  10180. if ( (id1|0) === (id2|0) ){
  10181. return -1;
  10182. }
  10183. // valid for values < 2^16
  10184. return ((id1|0) > (id2|0) ?
  10185. (id1 << 16) | (id2 & 0xFFFF) :
  10186. (id2 << 16) | (id1 & 0xFFFF))|0
  10187. ;
  10188. };
  10189. /**
  10190. * @method getByKey
  10191. * @param {Number} key
  10192. * @return {Object}
  10193. */
  10194. TupleDictionary.prototype.getByKey = function(key) {
  10195. key = key|0;
  10196. return this.data[key];
  10197. };
  10198. /**
  10199. * @method get
  10200. * @param {Number} i
  10201. * @param {Number} j
  10202. * @return {Number}
  10203. */
  10204. TupleDictionary.prototype.get = function(i, j) {
  10205. return this.data[this.getKey(i, j)];
  10206. };
  10207. /**
  10208. * Set a value.
  10209. * @method set
  10210. * @param {Number} i
  10211. * @param {Number} j
  10212. * @param {Number} value
  10213. */
  10214. TupleDictionary.prototype.set = function(i, j, value) {
  10215. if(!value){
  10216. throw new Error("No data!");
  10217. }
  10218. var key = this.getKey(i, j);
  10219. // Check if key already exists
  10220. if(!this.data[key]){
  10221. this.keys.push(key);
  10222. }
  10223. this.data[key] = value;
  10224. return key;
  10225. };
  10226. /**
  10227. * Remove all data.
  10228. * @method reset
  10229. */
  10230. TupleDictionary.prototype.reset = function() {
  10231. var data = this.data,
  10232. keys = this.keys;
  10233. var l = keys.length;
  10234. while(l--) {
  10235. delete data[keys[l]];
  10236. }
  10237. keys.length = 0;
  10238. };
  10239. /**
  10240. * Copy another TupleDictionary. Note that all data in this dictionary will be removed.
  10241. * @method copy
  10242. * @param {TupleDictionary} dict The TupleDictionary to copy into this one.
  10243. */
  10244. TupleDictionary.prototype.copy = function(dict) {
  10245. this.reset();
  10246. Utils.appendArray(this.keys, dict.keys);
  10247. var l = dict.keys.length;
  10248. while(l--){
  10249. var key = dict.keys[l];
  10250. this.data[key] = dict.data[key];
  10251. }
  10252. };
  10253. },{"./Utils":57}],57:[function(_dereq_,module,exports){
  10254. /* global P2_ARRAY_TYPE */
  10255. module.exports = Utils;
  10256. /**
  10257. * Misc utility functions
  10258. * @class Utils
  10259. * @constructor
  10260. */
  10261. function Utils(){}
  10262. /**
  10263. * Append the values in array b to the array a. See <a href="http://stackoverflow.com/questions/1374126/how-to-append-an-array-to-an-existing-javascript-array/1374131#1374131">this</a> for an explanation.
  10264. * @method appendArray
  10265. * @static
  10266. * @param {Array} a
  10267. * @param {Array} b
  10268. */
  10269. Utils.appendArray = function(a,b){
  10270. if (b.length < 150000) {
  10271. a.push.apply(a, b);
  10272. } else {
  10273. for (var i = 0, len = b.length; i !== len; ++i) {
  10274. a.push(b[i]);
  10275. }
  10276. }
  10277. };
  10278. /**
  10279. * Garbage free Array.splice(). Does not allocate a new array.
  10280. * @method splice
  10281. * @static
  10282. * @param {Array} array
  10283. * @param {Number} index
  10284. * @param {Number} howmany
  10285. */
  10286. Utils.splice = function(array,index,howmany){
  10287. howmany = howmany || 1;
  10288. for (var i=index, len=array.length-howmany; i < len; i++){
  10289. array[i] = array[i + howmany];
  10290. }
  10291. array.length = len;
  10292. };
  10293. /**
  10294. * The array type to use for internal numeric computations throughout the library. Float32Array is used if it is available, but falls back on Array. If you want to set array type manually, inject it via the global variable P2_ARRAY_TYPE. See example below.
  10295. * @static
  10296. * @property {function} ARRAY_TYPE
  10297. * @example
  10298. * <script>
  10299. * <!-- Inject your preferred array type before loading p2.js -->
  10300. * P2_ARRAY_TYPE = Array;
  10301. * </script>
  10302. * <script src="p2.js"></script>
  10303. */
  10304. if(typeof P2_ARRAY_TYPE !== 'undefined') {
  10305. Utils.ARRAY_TYPE = P2_ARRAY_TYPE;
  10306. } else if (typeof Float32Array !== 'undefined'){
  10307. Utils.ARRAY_TYPE = Float32Array;
  10308. } else {
  10309. Utils.ARRAY_TYPE = Array;
  10310. }
  10311. /**
  10312. * Extend an object with the properties of another
  10313. * @static
  10314. * @method extend
  10315. * @param {object} a
  10316. * @param {object} b
  10317. */
  10318. Utils.extend = function(a,b){
  10319. for(var key in b){
  10320. a[key] = b[key];
  10321. }
  10322. };
  10323. /**
  10324. * Extend an options object with default values.
  10325. * @static
  10326. * @method defaults
  10327. * @param {object} options The options object. May be falsy: in this case, a new object is created and returned.
  10328. * @param {object} defaults An object containing default values.
  10329. * @return {object} The modified options object.
  10330. */
  10331. Utils.defaults = function(options, defaults){
  10332. options = options || {};
  10333. for(var key in defaults){
  10334. if(!(key in options)){
  10335. options[key] = defaults[key];
  10336. }
  10337. }
  10338. return options;
  10339. };
  10340. },{}],58:[function(_dereq_,module,exports){
  10341. var Body = _dereq_('../objects/Body');
  10342. module.exports = Island;
  10343. /**
  10344. * An island of bodies connected with equations.
  10345. * @class Island
  10346. * @constructor
  10347. */
  10348. function Island(){
  10349. /**
  10350. * Current equations in this island.
  10351. * @property equations
  10352. * @type {Array}
  10353. */
  10354. this.equations = [];
  10355. /**
  10356. * Current bodies in this island.
  10357. * @property bodies
  10358. * @type {Array}
  10359. */
  10360. this.bodies = [];
  10361. }
  10362. /**
  10363. * Clean this island from bodies and equations.
  10364. * @method reset
  10365. */
  10366. Island.prototype.reset = function(){
  10367. this.equations.length = this.bodies.length = 0;
  10368. };
  10369. var bodyIds = [];
  10370. /**
  10371. * Get all unique bodies in this island.
  10372. * @method getBodies
  10373. * @return {Array} An array of Body
  10374. */
  10375. Island.prototype.getBodies = function(result){
  10376. var bodies = result || [],
  10377. eqs = this.equations;
  10378. bodyIds.length = 0;
  10379. for(var i=0; i!==eqs.length; i++){
  10380. var eq = eqs[i];
  10381. if(bodyIds.indexOf(eq.bodyA.id)===-1){
  10382. bodies.push(eq.bodyA);
  10383. bodyIds.push(eq.bodyA.id);
  10384. }
  10385. if(bodyIds.indexOf(eq.bodyB.id)===-1){
  10386. bodies.push(eq.bodyB);
  10387. bodyIds.push(eq.bodyB.id);
  10388. }
  10389. }
  10390. return bodies;
  10391. };
  10392. /**
  10393. * Check if the entire island wants to sleep.
  10394. * @method wantsToSleep
  10395. * @return {Boolean}
  10396. */
  10397. Island.prototype.wantsToSleep = function(){
  10398. for(var i=0; i<this.bodies.length; i++){
  10399. var b = this.bodies[i];
  10400. if(b.type === Body.DYNAMIC && !b.wantsToSleep){
  10401. return false;
  10402. }
  10403. }
  10404. return true;
  10405. };
  10406. /**
  10407. * Make all bodies in the island sleep.
  10408. * @method sleep
  10409. */
  10410. Island.prototype.sleep = function(){
  10411. for(var i=0; i<this.bodies.length; i++){
  10412. var b = this.bodies[i];
  10413. b.sleep();
  10414. }
  10415. return true;
  10416. };
  10417. },{"../objects/Body":31}],59:[function(_dereq_,module,exports){
  10418. var vec2 = _dereq_('../math/vec2')
  10419. , Island = _dereq_('./Island')
  10420. , IslandNode = _dereq_('./IslandNode')
  10421. , IslandNodePool = _dereq_('./../utils/IslandNodePool')
  10422. , IslandPool = _dereq_('./../utils/IslandPool')
  10423. , Body = _dereq_('../objects/Body');
  10424. module.exports = IslandManager;
  10425. /**
  10426. * Splits the system of bodies and equations into independent islands
  10427. *
  10428. * @class IslandManager
  10429. * @constructor
  10430. * @param {Object} [options]
  10431. * @extends Solver
  10432. */
  10433. function IslandManager(options){
  10434. /**
  10435. * @property nodePool
  10436. * @type {IslandNodePool}
  10437. */
  10438. this.nodePool = new IslandNodePool({ size: 16 });
  10439. /**
  10440. * @property islandPool
  10441. * @type {IslandPool}
  10442. */
  10443. this.islandPool = new IslandPool({ size: 8 });
  10444. /**
  10445. * The equations to split. Manually fill this array before running .split().
  10446. * @property {Array} equations
  10447. */
  10448. this.equations = [];
  10449. /**
  10450. * The resulting {{#crossLink "Island"}}{{/crossLink}}s.
  10451. * @property {Array} islands
  10452. */
  10453. this.islands = [];
  10454. /**
  10455. * The resulting graph nodes.
  10456. * @property {Array} nodes
  10457. */
  10458. this.nodes = [];
  10459. /**
  10460. * The node queue, used when traversing the graph of nodes.
  10461. * @private
  10462. * @property {Array} queue
  10463. */
  10464. this.queue = [];
  10465. }
  10466. /**
  10467. * Get an unvisited node from a list of nodes.
  10468. * @static
  10469. * @method getUnvisitedNode
  10470. * @param {Array} nodes
  10471. * @return {IslandNode|boolean} The node if found, else false.
  10472. */
  10473. IslandManager.getUnvisitedNode = function(nodes){
  10474. var Nnodes = nodes.length;
  10475. for(var i=0; i!==Nnodes; i++){
  10476. var node = nodes[i];
  10477. if(!node.visited && node.body.type === Body.DYNAMIC){
  10478. return node;
  10479. }
  10480. }
  10481. return false;
  10482. };
  10483. /**
  10484. * Visit a node.
  10485. * @method visit
  10486. * @param {IslandNode} node
  10487. * @param {Array} bds
  10488. * @param {Array} eqs
  10489. */
  10490. IslandManager.prototype.visit = function (node,bds,eqs){
  10491. bds.push(node.body);
  10492. var Neqs = node.equations.length;
  10493. for(var i=0; i!==Neqs; i++){
  10494. var eq = node.equations[i];
  10495. if(eqs.indexOf(eq) === -1){ // Already added?
  10496. eqs.push(eq);
  10497. }
  10498. }
  10499. };
  10500. /**
  10501. * Runs the search algorithm, starting at a root node. The resulting bodies and equations will be stored in the provided arrays.
  10502. * @method bfs
  10503. * @param {IslandNode} root The node to start from
  10504. * @param {Array} bds An array to append resulting Bodies to.
  10505. * @param {Array} eqs An array to append resulting Equations to.
  10506. */
  10507. IslandManager.prototype.bfs = function(root,bds,eqs){
  10508. // Reset the visit queue
  10509. var queue = this.queue;
  10510. queue.length = 0;
  10511. // Add root node to queue
  10512. queue.push(root);
  10513. root.visited = true;
  10514. this.visit(root,bds,eqs);
  10515. // Process all queued nodes
  10516. while(queue.length) {
  10517. // Get next node in the queue
  10518. var node = queue.pop();
  10519. // Visit unvisited neighboring nodes
  10520. var child;
  10521. while((child = IslandManager.getUnvisitedNode(node.neighbors))) {
  10522. child.visited = true;
  10523. this.visit(child,bds,eqs);
  10524. // Only visit the children of this node if it's dynamic
  10525. if(child.body.type === Body.DYNAMIC){
  10526. queue.push(child);
  10527. }
  10528. }
  10529. }
  10530. };
  10531. /**
  10532. * Split the world into independent islands. The result is stored in .islands.
  10533. * @method split
  10534. * @param {World} world
  10535. * @return {Array} The generated islands
  10536. */
  10537. IslandManager.prototype.split = function(world){
  10538. var bodies = world.bodies,
  10539. nodes = this.nodes,
  10540. equations = this.equations;
  10541. // Move old nodes to the node pool
  10542. while(nodes.length){
  10543. this.nodePool.release(nodes.pop());
  10544. }
  10545. // Create needed nodes, reuse if possible
  10546. for(var i=0; i!==bodies.length; i++){
  10547. var node = this.nodePool.get();
  10548. node.body = bodies[i];
  10549. nodes.push(node);
  10550. // if(this.nodePool.length){
  10551. // var node = this.nodePool.pop();
  10552. // node.reset();
  10553. // node.body = bodies[i];
  10554. // nodes.push(node);
  10555. // } else {
  10556. // nodes.push(new IslandNode(bodies[i]));
  10557. // }
  10558. }
  10559. // Add connectivity data. Each equation connects 2 bodies.
  10560. for(var k=0; k!==equations.length; k++){
  10561. var eq=equations[k],
  10562. i=bodies.indexOf(eq.bodyA),
  10563. j=bodies.indexOf(eq.bodyB),
  10564. ni=nodes[i],
  10565. nj=nodes[j];
  10566. ni.neighbors.push(nj);
  10567. nj.neighbors.push(ni);
  10568. ni.equations.push(eq);
  10569. nj.equations.push(eq);
  10570. }
  10571. // Move old islands to the island pool
  10572. var islands = this.islands;
  10573. for(var i=0; i<islands.length; i++){
  10574. this.islandPool.release(islands[i]);
  10575. }
  10576. islands.length = 0;
  10577. // Get islands
  10578. var child;
  10579. while((child = IslandManager.getUnvisitedNode(nodes))){
  10580. // Create new island
  10581. var island = this.islandPool.get();
  10582. // Get all equations and bodies in this island
  10583. this.bfs(child, island.bodies, island.equations);
  10584. islands.push(island);
  10585. }
  10586. return islands;
  10587. };
  10588. },{"../math/vec2":30,"../objects/Body":31,"./../utils/IslandNodePool":50,"./../utils/IslandPool":51,"./Island":58,"./IslandNode":60}],60:[function(_dereq_,module,exports){
  10589. module.exports = IslandNode;
  10590. /**
  10591. * Holds a body and keeps track of some additional properties needed for graph traversal.
  10592. * @class IslandNode
  10593. * @constructor
  10594. * @param {Body} body
  10595. */
  10596. function IslandNode(body){
  10597. /**
  10598. * The body that is contained in this node.
  10599. * @property {Body} body
  10600. */
  10601. this.body = body;
  10602. /**
  10603. * Neighboring IslandNodes
  10604. * @property {Array} neighbors
  10605. */
  10606. this.neighbors = [];
  10607. /**
  10608. * Equations connected to this node.
  10609. * @property {Array} equations
  10610. */
  10611. this.equations = [];
  10612. /**
  10613. * If this node was visiting during the graph traversal.
  10614. * @property visited
  10615. * @type {Boolean}
  10616. */
  10617. this.visited = false;
  10618. }
  10619. /**
  10620. * Clean this node from bodies and equations.
  10621. * @method reset
  10622. */
  10623. IslandNode.prototype.reset = function(){
  10624. this.equations.length = 0;
  10625. this.neighbors.length = 0;
  10626. this.visited = false;
  10627. this.body = null;
  10628. };
  10629. },{}],61:[function(_dereq_,module,exports){
  10630. var GSSolver = _dereq_('../solver/GSSolver')
  10631. , Solver = _dereq_('../solver/Solver')
  10632. , Ray = _dereq_('../collision/Ray')
  10633. , vec2 = _dereq_('../math/vec2')
  10634. , Circle = _dereq_('../shapes/Circle')
  10635. , Convex = _dereq_('../shapes/Convex')
  10636. , Line = _dereq_('../shapes/Line')
  10637. , Plane = _dereq_('../shapes/Plane')
  10638. , Capsule = _dereq_('../shapes/Capsule')
  10639. , Particle = _dereq_('../shapes/Particle')
  10640. , EventEmitter = _dereq_('../events/EventEmitter')
  10641. , Body = _dereq_('../objects/Body')
  10642. , Shape = _dereq_('../shapes/Shape')
  10643. , LinearSpring = _dereq_('../objects/LinearSpring')
  10644. , Material = _dereq_('../material/Material')
  10645. , ContactMaterial = _dereq_('../material/ContactMaterial')
  10646. , DistanceConstraint = _dereq_('../constraints/DistanceConstraint')
  10647. , Constraint = _dereq_('../constraints/Constraint')
  10648. , LockConstraint = _dereq_('../constraints/LockConstraint')
  10649. , RevoluteConstraint = _dereq_('../constraints/RevoluteConstraint')
  10650. , PrismaticConstraint = _dereq_('../constraints/PrismaticConstraint')
  10651. , GearConstraint = _dereq_('../constraints/GearConstraint')
  10652. , pkg = _dereq_('../../package.json')
  10653. , Broadphase = _dereq_('../collision/Broadphase')
  10654. , AABB = _dereq_('../collision/AABB')
  10655. , SAPBroadphase = _dereq_('../collision/SAPBroadphase')
  10656. , Narrowphase = _dereq_('../collision/Narrowphase')
  10657. , Utils = _dereq_('../utils/Utils')
  10658. , OverlapKeeper = _dereq_('../utils/OverlapKeeper')
  10659. , IslandManager = _dereq_('./IslandManager')
  10660. , RotationalSpring = _dereq_('../objects/RotationalSpring');
  10661. module.exports = World;
  10662. /**
  10663. * The dynamics world, where all bodies and constraints live.
  10664. *
  10665. * @class World
  10666. * @constructor
  10667. * @param {Object} [options]
  10668. * @param {Solver} [options.solver] Defaults to GSSolver.
  10669. * @param {Array} [options.gravity] Defaults to y=-9.78.
  10670. * @param {Broadphase} [options.broadphase] Defaults to SAPBroadphase
  10671. * @param {Boolean} [options.islandSplit=true]
  10672. * @extends EventEmitter
  10673. *
  10674. * @example
  10675. * var world = new World({
  10676. * gravity: [0, -10],
  10677. * broadphase: new SAPBroadphase()
  10678. * });
  10679. * world.addBody(new Body());
  10680. */
  10681. function World(options){
  10682. EventEmitter.apply(this);
  10683. options = options || {};
  10684. /**
  10685. * All springs in the world. To add a spring to the world, use {{#crossLink "World/addSpring:method"}}{{/crossLink}}.
  10686. *
  10687. * @property springs
  10688. * @type {Array}
  10689. */
  10690. this.springs = [];
  10691. /**
  10692. * All bodies in the world. To add a body to the world, use {{#crossLink "World/addBody:method"}}{{/crossLink}}.
  10693. * @property {Array} bodies
  10694. */
  10695. this.bodies = [];
  10696. /**
  10697. * Disabled body collision pairs. See {{#crossLink "World/disableBodyCollision:method"}}.
  10698. * @private
  10699. * @property {Array} disabledBodyCollisionPairs
  10700. */
  10701. this.disabledBodyCollisionPairs = [];
  10702. /**
  10703. * The solver used to satisfy constraints and contacts. Default is {{#crossLink "GSSolver"}}{{/crossLink}}.
  10704. * @property {Solver} solver
  10705. */
  10706. this.solver = options.solver || new GSSolver();
  10707. /**
  10708. * The narrowphase to use to generate contacts.
  10709. *
  10710. * @property narrowphase
  10711. * @type {Narrowphase}
  10712. */
  10713. this.narrowphase = new Narrowphase(this);
  10714. /**
  10715. * The island manager of this world.
  10716. * @property {IslandManager} islandManager
  10717. */
  10718. this.islandManager = new IslandManager();
  10719. /**
  10720. * Gravity in the world. This is applied on all bodies in the beginning of each step().
  10721. *
  10722. * @property gravity
  10723. * @type {Array}
  10724. */
  10725. this.gravity = vec2.fromValues(0, -9.78);
  10726. if(options.gravity){
  10727. vec2.copy(this.gravity, options.gravity);
  10728. }
  10729. /**
  10730. * Gravity to use when approximating the friction max force (mu*mass*gravity).
  10731. * @property {Number} frictionGravity
  10732. */
  10733. this.frictionGravity = vec2.length(this.gravity) || 10;
  10734. /**
  10735. * Set to true if you want .frictionGravity to be automatically set to the length of .gravity.
  10736. * @property {Boolean} useWorldGravityAsFrictionGravity
  10737. * @default true
  10738. */
  10739. this.useWorldGravityAsFrictionGravity = true;
  10740. /**
  10741. * If the length of .gravity is zero, and .useWorldGravityAsFrictionGravity=true, then switch to using .frictionGravity for friction instead. This fallback is useful for gravityless games.
  10742. * @property {Boolean} useFrictionGravityOnZeroGravity
  10743. * @default true
  10744. */
  10745. this.useFrictionGravityOnZeroGravity = true;
  10746. /**
  10747. * The broadphase algorithm to use.
  10748. *
  10749. * @property broadphase
  10750. * @type {Broadphase}
  10751. */
  10752. this.broadphase = options.broadphase || new SAPBroadphase();
  10753. this.broadphase.setWorld(this);
  10754. /**
  10755. * User-added constraints.
  10756. *
  10757. * @property constraints
  10758. * @type {Array}
  10759. */
  10760. this.constraints = [];
  10761. /**
  10762. * Dummy default material in the world, used in .defaultContactMaterial
  10763. * @property {Material} defaultMaterial
  10764. */
  10765. this.defaultMaterial = new Material();
  10766. /**
  10767. * The default contact material to use, if no contact material was set for the colliding materials.
  10768. * @property {ContactMaterial} defaultContactMaterial
  10769. */
  10770. this.defaultContactMaterial = new ContactMaterial(this.defaultMaterial,this.defaultMaterial);
  10771. /**
  10772. * For keeping track of what time step size we used last step
  10773. * @property lastTimeStep
  10774. * @type {Number}
  10775. */
  10776. this.lastTimeStep = 1/60;
  10777. /**
  10778. * Enable to automatically apply spring forces each step.
  10779. * @property applySpringForces
  10780. * @type {Boolean}
  10781. * @default true
  10782. */
  10783. this.applySpringForces = true;
  10784. /**
  10785. * Enable to automatically apply body damping each step.
  10786. * @property applyDamping
  10787. * @type {Boolean}
  10788. * @default true
  10789. */
  10790. this.applyDamping = true;
  10791. /**
  10792. * Enable to automatically apply gravity each step.
  10793. * @property applyGravity
  10794. * @type {Boolean}
  10795. * @default true
  10796. */
  10797. this.applyGravity = true;
  10798. /**
  10799. * Enable/disable constraint solving in each step.
  10800. * @property solveConstraints
  10801. * @type {Boolean}
  10802. * @default true
  10803. */
  10804. this.solveConstraints = true;
  10805. /**
  10806. * The ContactMaterials added to the World.
  10807. * @property contactMaterials
  10808. * @type {Array}
  10809. */
  10810. this.contactMaterials = [];
  10811. /**
  10812. * World time.
  10813. * @property time
  10814. * @type {Number}
  10815. */
  10816. this.time = 0.0;
  10817. this.accumulator = 0;
  10818. /**
  10819. * Is true during step().
  10820. * @property {Boolean} stepping
  10821. */
  10822. this.stepping = false;
  10823. /**
  10824. * Bodies that are scheduled to be removed at the end of the step.
  10825. * @property {Array} bodiesToBeRemoved
  10826. * @private
  10827. */
  10828. this.bodiesToBeRemoved = [];
  10829. /**
  10830. * Whether to enable island splitting. Island splitting can be an advantage for both precision and performance. See {{#crossLink "IslandManager"}}{{/crossLink}}.
  10831. * @property {Boolean} islandSplit
  10832. * @default true
  10833. */
  10834. this.islandSplit = typeof(options.islandSplit)!=="undefined" ? !!options.islandSplit : true;
  10835. /**
  10836. * Set to true if you want to the world to emit the "impact" event. Turning this off could improve performance.
  10837. * @property emitImpactEvent
  10838. * @type {Boolean}
  10839. * @default true
  10840. */
  10841. this.emitImpactEvent = true;
  10842. // Id counters
  10843. this._constraintIdCounter = 0;
  10844. this._bodyIdCounter = 0;
  10845. /**
  10846. * Fired after the step().
  10847. * @event postStep
  10848. */
  10849. this.postStepEvent = {
  10850. type : "postStep"
  10851. };
  10852. /**
  10853. * Fired when a body is added to the world.
  10854. * @event addBody
  10855. * @param {Body} body
  10856. */
  10857. this.addBodyEvent = {
  10858. type : "addBody",
  10859. body : null
  10860. };
  10861. /**
  10862. * Fired when a body is removed from the world.
  10863. * @event removeBody
  10864. * @param {Body} body
  10865. */
  10866. this.removeBodyEvent = {
  10867. type : "removeBody",
  10868. body : null
  10869. };
  10870. /**
  10871. * Fired when a spring is added to the world.
  10872. * @event addSpring
  10873. * @param {Spring} spring
  10874. */
  10875. this.addSpringEvent = {
  10876. type : "addSpring",
  10877. spring : null
  10878. };
  10879. /**
  10880. * Fired when a first contact is created between two bodies. This event is fired after the step has been done.
  10881. * @event impact
  10882. * @param {Body} bodyA
  10883. * @param {Body} bodyB
  10884. */
  10885. this.impactEvent = {
  10886. type: "impact",
  10887. bodyA : null,
  10888. bodyB : null,
  10889. shapeA : null,
  10890. shapeB : null,
  10891. contactEquation : null
  10892. };
  10893. /**
  10894. * Fired after the Broadphase has collected collision pairs in the world.
  10895. * Inside the event handler, you can modify the pairs array as you like, to
  10896. * prevent collisions between objects that you don't want.
  10897. * @event postBroadphase
  10898. * @param {Array} pairs An array of collision pairs. If this array is [body1,body2,body3,body4], then the body pairs 1,2 and 3,4 would advance to narrowphase.
  10899. */
  10900. this.postBroadphaseEvent = {
  10901. type: "postBroadphase",
  10902. pairs: null
  10903. };
  10904. /**
  10905. * How to deactivate bodies during simulation. Possible modes are: {{#crossLink "World/NO_SLEEPING:property"}}World.NO_SLEEPING{{/crossLink}}, {{#crossLink "World/BODY_SLEEPING:property"}}World.BODY_SLEEPING{{/crossLink}} and {{#crossLink "World/ISLAND_SLEEPING:property"}}World.ISLAND_SLEEPING{{/crossLink}}.
  10906. * If sleeping is enabled, you might need to {{#crossLink "Body/wakeUp:method"}}wake up{{/crossLink}} the bodies if they fall asleep when they shouldn't. If you want to enable sleeping in the world, but want to disable it for a particular body, see {{#crossLink "Body/allowSleep:property"}}Body.allowSleep{{/crossLink}}.
  10907. * @property sleepMode
  10908. * @type {number}
  10909. * @default World.NO_SLEEPING
  10910. */
  10911. this.sleepMode = World.NO_SLEEPING;
  10912. /**
  10913. * Fired when two shapes starts start to overlap. Fired in the narrowphase, during step.
  10914. * @event beginContact
  10915. * @param {Shape} shapeA
  10916. * @param {Shape} shapeB
  10917. * @param {Body} bodyA
  10918. * @param {Body} bodyB
  10919. * @param {Array} contactEquations
  10920. */
  10921. this.beginContactEvent = {
  10922. type: "beginContact",
  10923. shapeA: null,
  10924. shapeB: null,
  10925. bodyA: null,
  10926. bodyB: null,
  10927. contactEquations: []
  10928. };
  10929. /**
  10930. * Fired when two shapes stop overlapping, after the narrowphase (during step).
  10931. * @event endContact
  10932. * @param {Shape} shapeA
  10933. * @param {Shape} shapeB
  10934. * @param {Body} bodyA
  10935. * @param {Body} bodyB
  10936. */
  10937. this.endContactEvent = {
  10938. type: "endContact",
  10939. shapeA: null,
  10940. shapeB: null,
  10941. bodyA: null,
  10942. bodyB: null
  10943. };
  10944. /**
  10945. * Fired just before equations are added to the solver to be solved. Can be used to control what equations goes into the solver.
  10946. * @event preSolve
  10947. * @param {Array} contactEquations An array of contacts to be solved.
  10948. * @param {Array} frictionEquations An array of friction equations to be solved.
  10949. */
  10950. this.preSolveEvent = {
  10951. type: "preSolve",
  10952. contactEquations: null,
  10953. frictionEquations: null
  10954. };
  10955. // For keeping track of overlapping shapes
  10956. this.overlappingShapesLastState = { keys:[] };
  10957. this.overlappingShapesCurrentState = { keys:[] };
  10958. /**
  10959. * @property {OverlapKeeper} overlapKeeper
  10960. */
  10961. this.overlapKeeper = new OverlapKeeper();
  10962. }
  10963. World.prototype = new Object(EventEmitter.prototype);
  10964. World.prototype.constructor = World;
  10965. /**
  10966. * Never deactivate bodies.
  10967. * @static
  10968. * @property {number} NO_SLEEPING
  10969. */
  10970. World.NO_SLEEPING = 1;
  10971. /**
  10972. * Deactivate individual bodies if they are sleepy.
  10973. * @static
  10974. * @property {number} BODY_SLEEPING
  10975. */
  10976. World.BODY_SLEEPING = 2;
  10977. /**
  10978. * Deactivates bodies that are in contact, if all of them are sleepy. Note that you must enable {{#crossLink "World/islandSplit:property"}}.islandSplit{{/crossLink}} for this to work.
  10979. * @static
  10980. * @property {number} ISLAND_SLEEPING
  10981. */
  10982. World.ISLAND_SLEEPING = 4;
  10983. /**
  10984. * Add a constraint to the simulation.
  10985. *
  10986. * @method addConstraint
  10987. * @param {Constraint} constraint
  10988. * @example
  10989. * var constraint = new LockConstraint(bodyA, bodyB);
  10990. * world.addConstraint(constraint);
  10991. */
  10992. World.prototype.addConstraint = function(constraint){
  10993. this.constraints.push(constraint);
  10994. };
  10995. /**
  10996. * Add a ContactMaterial to the simulation.
  10997. * @method addContactMaterial
  10998. * @param {ContactMaterial} contactMaterial
  10999. */
  11000. World.prototype.addContactMaterial = function(contactMaterial){
  11001. this.contactMaterials.push(contactMaterial);
  11002. };
  11003. /**
  11004. * Removes a contact material
  11005. *
  11006. * @method removeContactMaterial
  11007. * @param {ContactMaterial} cm
  11008. */
  11009. World.prototype.removeContactMaterial = function(cm){
  11010. var idx = this.contactMaterials.indexOf(cm);
  11011. if(idx!==-1){
  11012. Utils.splice(this.contactMaterials,idx,1);
  11013. }
  11014. };
  11015. /**
  11016. * Get a contact material given two materials
  11017. * @method getContactMaterial
  11018. * @param {Material} materialA
  11019. * @param {Material} materialB
  11020. * @return {ContactMaterial} The matching ContactMaterial, or false on fail.
  11021. * @todo Use faster hash map to lookup from material id's
  11022. */
  11023. World.prototype.getContactMaterial = function(materialA,materialB){
  11024. var cmats = this.contactMaterials;
  11025. for(var i=0, N=cmats.length; i!==N; i++){
  11026. var cm = cmats[i];
  11027. if( (cm.materialA.id === materialA.id) && (cm.materialB.id === materialB.id) ||
  11028. (cm.materialA.id === materialB.id) && (cm.materialB.id === materialA.id) ){
  11029. return cm;
  11030. }
  11031. }
  11032. return false;
  11033. };
  11034. /**
  11035. * Removes a constraint
  11036. *
  11037. * @method removeConstraint
  11038. * @param {Constraint} constraint
  11039. */
  11040. World.prototype.removeConstraint = function(constraint){
  11041. var idx = this.constraints.indexOf(constraint);
  11042. if(idx!==-1){
  11043. Utils.splice(this.constraints,idx,1);
  11044. }
  11045. };
  11046. var step_r = vec2.create(),
  11047. step_runit = vec2.create(),
  11048. step_u = vec2.create(),
  11049. step_f = vec2.create(),
  11050. step_fhMinv = vec2.create(),
  11051. step_velodt = vec2.create(),
  11052. step_mg = vec2.create(),
  11053. xiw = vec2.fromValues(0,0),
  11054. xjw = vec2.fromValues(0,0),
  11055. zero = vec2.fromValues(0,0),
  11056. interpvelo = vec2.fromValues(0,0);
  11057. /**
  11058. * Step the physics world forward in time.
  11059. *
  11060. * There are two modes. The simple mode is fixed timestepping without interpolation. In this case you only use the first argument. The second case uses interpolation. In that you also provide the time since the function was last used, as well as the maximum fixed timesteps to take.
  11061. *
  11062. * @method step
  11063. * @param {Number} dt The fixed time step size to use.
  11064. * @param {Number} [timeSinceLastCalled=0] The time elapsed since the function was last called.
  11065. * @param {Number} [maxSubSteps=10] Maximum number of fixed steps to take per function call.
  11066. *
  11067. * @example
  11068. * // Simple fixed timestepping without interpolation
  11069. * var fixedTimeStep = 1 / 60;
  11070. * var world = new World();
  11071. * var body = new Body({ mass: 1 });
  11072. * world.addBody(body);
  11073. *
  11074. * function animate(){
  11075. * requestAnimationFrame(animate);
  11076. * world.step(fixedTimeStep);
  11077. * renderBody(body.position, body.angle);
  11078. * }
  11079. *
  11080. * // Start animation loop
  11081. * requestAnimationFrame(animate);
  11082. *
  11083. * @example
  11084. * // Fixed timestepping with interpolation
  11085. * var maxSubSteps = 10;
  11086. * var lastTimeSeconds;
  11087. *
  11088. * function animate(t){
  11089. * requestAnimationFrame(animate);
  11090. * timeSeconds = t / 1000;
  11091. * lastTimeSeconds = lastTimeSeconds || timeSeconds;
  11092. *
  11093. * deltaTime = timeSeconds - lastTimeSeconds;
  11094. * world.step(fixedTimeStep, deltaTime, maxSubSteps);
  11095. *
  11096. * renderBody(body.interpolatedPosition, body.interpolatedAngle);
  11097. * }
  11098. *
  11099. * // Start animation loop
  11100. * requestAnimationFrame(animate);
  11101. *
  11102. * @see http://bulletphysics.org/mediawiki-1.5.8/index.php/Stepping_The_World
  11103. */
  11104. World.prototype.step = function(dt,timeSinceLastCalled,maxSubSteps){
  11105. maxSubSteps = maxSubSteps || 10;
  11106. timeSinceLastCalled = timeSinceLastCalled || 0;
  11107. if(timeSinceLastCalled === 0){ // Fixed, simple stepping
  11108. this.internalStep(dt);
  11109. // Increment time
  11110. this.time += dt;
  11111. } else {
  11112. this.accumulator += timeSinceLastCalled;
  11113. var substeps = 0;
  11114. while (this.accumulator >= dt && substeps < maxSubSteps) {
  11115. // Do fixed steps to catch up
  11116. this.internalStep(dt);
  11117. this.time += dt;
  11118. this.accumulator -= dt;
  11119. substeps++;
  11120. }
  11121. var t = (this.accumulator % dt) / dt;
  11122. for(var j=0; j!==this.bodies.length; j++){
  11123. var b = this.bodies[j];
  11124. vec2.lerp(b.interpolatedPosition, b.previousPosition, b.position, t);
  11125. b.interpolatedAngle = b.previousAngle + t * (b.angle - b.previousAngle);
  11126. }
  11127. }
  11128. };
  11129. var endOverlaps = [];
  11130. /**
  11131. * Make a fixed step.
  11132. * @method internalStep
  11133. * @param {number} dt
  11134. * @private
  11135. */
  11136. World.prototype.internalStep = function(dt){
  11137. this.stepping = true;
  11138. var that = this,
  11139. Nsprings = this.springs.length,
  11140. springs = this.springs,
  11141. bodies = this.bodies,
  11142. g = this.gravity,
  11143. solver = this.solver,
  11144. Nbodies = this.bodies.length,
  11145. broadphase = this.broadphase,
  11146. np = this.narrowphase,
  11147. constraints = this.constraints,
  11148. t0, t1,
  11149. fhMinv = step_fhMinv,
  11150. velodt = step_velodt,
  11151. mg = step_mg,
  11152. scale = vec2.scale,
  11153. add = vec2.add,
  11154. rotate = vec2.rotate,
  11155. islandManager = this.islandManager;
  11156. this.overlapKeeper.tick();
  11157. this.lastTimeStep = dt;
  11158. // Update approximate friction gravity.
  11159. if(this.useWorldGravityAsFrictionGravity){
  11160. var gravityLen = vec2.length(this.gravity);
  11161. if(!(gravityLen === 0 && this.useFrictionGravityOnZeroGravity)){
  11162. // Nonzero gravity. Use it.
  11163. this.frictionGravity = gravityLen;
  11164. }
  11165. }
  11166. // Add gravity to bodies
  11167. if(this.applyGravity){
  11168. for(var i=0; i!==Nbodies; i++){
  11169. var b = bodies[i],
  11170. fi = b.force;
  11171. if(b.type !== Body.DYNAMIC || b.sleepState === Body.SLEEPING){
  11172. continue;
  11173. }
  11174. vec2.scale(mg,g,b.mass*b.gravityScale); // F=m*g
  11175. add(fi,fi,mg);
  11176. }
  11177. }
  11178. // Add spring forces
  11179. if(this.applySpringForces){
  11180. for(var i=0; i!==Nsprings; i++){
  11181. var s = springs[i];
  11182. s.applyForce();
  11183. }
  11184. }
  11185. if(this.applyDamping){
  11186. for(var i=0; i!==Nbodies; i++){
  11187. var b = bodies[i];
  11188. if(b.type === Body.DYNAMIC){
  11189. b.applyDamping(dt);
  11190. }
  11191. }
  11192. }
  11193. // Broadphase
  11194. var result = broadphase.getCollisionPairs(this);
  11195. // Remove ignored collision pairs
  11196. var ignoredPairs = this.disabledBodyCollisionPairs;
  11197. for(var i=ignoredPairs.length-2; i>=0; i-=2){
  11198. for(var j=result.length-2; j>=0; j-=2){
  11199. if( (ignoredPairs[i] === result[j] && ignoredPairs[i+1] === result[j+1]) ||
  11200. (ignoredPairs[i+1] === result[j] && ignoredPairs[i] === result[j+1])){
  11201. result.splice(j,2);
  11202. }
  11203. }
  11204. }
  11205. // Remove constrained pairs with collideConnected == false
  11206. var Nconstraints = constraints.length;
  11207. for(i=0; i!==Nconstraints; i++){
  11208. var c = constraints[i];
  11209. if(!c.collideConnected){
  11210. for(var j=result.length-2; j>=0; j-=2){
  11211. if( (c.bodyA === result[j] && c.bodyB === result[j+1]) ||
  11212. (c.bodyB === result[j] && c.bodyA === result[j+1])){
  11213. result.splice(j,2);
  11214. }
  11215. }
  11216. }
  11217. }
  11218. // postBroadphase event
  11219. this.postBroadphaseEvent.pairs = result;
  11220. this.emit(this.postBroadphaseEvent);
  11221. this.postBroadphaseEvent.pairs = null;
  11222. // Narrowphase
  11223. np.reset(this);
  11224. for(var i=0, Nresults=result.length; i!==Nresults; i+=2){
  11225. var bi = result[i],
  11226. bj = result[i+1];
  11227. // Loop over all shapes of body i
  11228. for(var k=0, Nshapesi=bi.shapes.length; k!==Nshapesi; k++){
  11229. var si = bi.shapes[k],
  11230. xi = si.position,
  11231. ai = si.angle;
  11232. // All shapes of body j
  11233. for(var l=0, Nshapesj=bj.shapes.length; l!==Nshapesj; l++){
  11234. var sj = bj.shapes[l],
  11235. xj = sj.position,
  11236. aj = sj.angle;
  11237. var cm = this.defaultContactMaterial;
  11238. if(si.material && sj.material){
  11239. var tmp = this.getContactMaterial(si.material,sj.material);
  11240. if(tmp){
  11241. cm = tmp;
  11242. }
  11243. }
  11244. this.runNarrowphase(np,bi,si,xi,ai,bj,sj,xj,aj,cm,this.frictionGravity);
  11245. }
  11246. }
  11247. }
  11248. // Wake up bodies
  11249. for(var i=0; i!==Nbodies; i++){
  11250. var body = bodies[i];
  11251. if(body._wakeUpAfterNarrowphase){
  11252. body.wakeUp();
  11253. body._wakeUpAfterNarrowphase = false;
  11254. }
  11255. }
  11256. // Emit end overlap events
  11257. if(this.has('endContact')){
  11258. this.overlapKeeper.getEndOverlaps(endOverlaps);
  11259. var e = this.endContactEvent;
  11260. var l = endOverlaps.length;
  11261. while(l--){
  11262. var data = endOverlaps[l];
  11263. e.shapeA = data.shapeA;
  11264. e.shapeB = data.shapeB;
  11265. e.bodyA = data.bodyA;
  11266. e.bodyB = data.bodyB;
  11267. this.emit(e);
  11268. }
  11269. endOverlaps.length = 0;
  11270. }
  11271. var preSolveEvent = this.preSolveEvent;
  11272. preSolveEvent.contactEquations = np.contactEquations;
  11273. preSolveEvent.frictionEquations = np.frictionEquations;
  11274. this.emit(preSolveEvent);
  11275. preSolveEvent.contactEquations = preSolveEvent.frictionEquations = null;
  11276. // update constraint equations
  11277. var Nconstraints = constraints.length;
  11278. for(i=0; i!==Nconstraints; i++){
  11279. constraints[i].update();
  11280. }
  11281. if(np.contactEquations.length || np.frictionEquations.length || Nconstraints){
  11282. if(this.islandSplit){
  11283. // Split into islands
  11284. islandManager.equations.length = 0;
  11285. Utils.appendArray(islandManager.equations, np.contactEquations);
  11286. Utils.appendArray(islandManager.equations, np.frictionEquations);
  11287. for(i=0; i!==Nconstraints; i++){
  11288. Utils.appendArray(islandManager.equations, constraints[i].equations);
  11289. }
  11290. islandManager.split(this);
  11291. for(var i=0; i!==islandManager.islands.length; i++){
  11292. var island = islandManager.islands[i];
  11293. if(island.equations.length){
  11294. solver.solveIsland(dt,island);
  11295. }
  11296. }
  11297. } else {
  11298. // Add contact equations to solver
  11299. solver.addEquations(np.contactEquations);
  11300. solver.addEquations(np.frictionEquations);
  11301. // Add user-defined constraint equations
  11302. for(i=0; i!==Nconstraints; i++){
  11303. solver.addEquations(constraints[i].equations);
  11304. }
  11305. if(this.solveConstraints){
  11306. solver.solve(dt,this);
  11307. }
  11308. solver.removeAllEquations();
  11309. }
  11310. }
  11311. // Step forward
  11312. for(var i=0; i!==Nbodies; i++){
  11313. var body = bodies[i];
  11314. // if(body.sleepState !== Body.SLEEPING && body.type !== Body.STATIC){
  11315. body.integrate(dt);
  11316. // }
  11317. }
  11318. // Reset force
  11319. for(var i=0; i!==Nbodies; i++){
  11320. bodies[i].setZeroForce();
  11321. }
  11322. // Emit impact event
  11323. if(this.emitImpactEvent && this.has('impact')){
  11324. var ev = this.impactEvent;
  11325. for(var i=0; i!==np.contactEquations.length; i++){
  11326. var eq = np.contactEquations[i];
  11327. if(eq.firstImpact){
  11328. ev.bodyA = eq.bodyA;
  11329. ev.bodyB = eq.bodyB;
  11330. ev.shapeA = eq.shapeA;
  11331. ev.shapeB = eq.shapeB;
  11332. ev.contactEquation = eq;
  11333. this.emit(ev);
  11334. }
  11335. }
  11336. }
  11337. // Sleeping update
  11338. if(this.sleepMode === World.BODY_SLEEPING){
  11339. for(i=0; i!==Nbodies; i++){
  11340. bodies[i].sleepTick(this.time, false, dt);
  11341. }
  11342. } else if(this.sleepMode === World.ISLAND_SLEEPING && this.islandSplit){
  11343. // Tell all bodies to sleep tick but dont sleep yet
  11344. for(i=0; i!==Nbodies; i++){
  11345. bodies[i].sleepTick(this.time, true, dt);
  11346. }
  11347. // Sleep islands
  11348. for(var i=0; i<this.islandManager.islands.length; i++){
  11349. var island = this.islandManager.islands[i];
  11350. if(island.wantsToSleep()){
  11351. island.sleep();
  11352. }
  11353. }
  11354. }
  11355. this.stepping = false;
  11356. // Remove bodies that are scheduled for removal
  11357. var bodiesToBeRemoved = this.bodiesToBeRemoved;
  11358. for(var i=0; i!==bodiesToBeRemoved.length; i++){
  11359. this.removeBody(bodiesToBeRemoved[i]);
  11360. }
  11361. bodiesToBeRemoved.length = 0;
  11362. this.emit(this.postStepEvent);
  11363. };
  11364. /**
  11365. * Runs narrowphase for the shape pair i and j.
  11366. * @method runNarrowphase
  11367. * @param {Narrowphase} np
  11368. * @param {Body} bi
  11369. * @param {Shape} si
  11370. * @param {Array} xi
  11371. * @param {Number} ai
  11372. * @param {Body} bj
  11373. * @param {Shape} sj
  11374. * @param {Array} xj
  11375. * @param {Number} aj
  11376. * @param {Number} mu
  11377. */
  11378. World.prototype.runNarrowphase = function(np,bi,si,xi,ai,bj,sj,xj,aj,cm,glen){
  11379. // Check collision groups and masks
  11380. if(!((si.collisionGroup & sj.collisionMask) !== 0 && (sj.collisionGroup & si.collisionMask) !== 0)){
  11381. return;
  11382. }
  11383. // Get world position and angle of each shape
  11384. vec2.rotate(xiw, xi, bi.angle);
  11385. vec2.rotate(xjw, xj, bj.angle);
  11386. vec2.add(xiw, xiw, bi.position);
  11387. vec2.add(xjw, xjw, bj.position);
  11388. var aiw = ai + bi.angle;
  11389. var ajw = aj + bj.angle;
  11390. np.enableFriction = cm.friction > 0;
  11391. np.frictionCoefficient = cm.friction;
  11392. var reducedMass;
  11393. if(bi.type === Body.STATIC || bi.type === Body.KINEMATIC){
  11394. reducedMass = bj.mass;
  11395. } else if(bj.type === Body.STATIC || bj.type === Body.KINEMATIC){
  11396. reducedMass = bi.mass;
  11397. } else {
  11398. reducedMass = (bi.mass*bj.mass)/(bi.mass+bj.mass);
  11399. }
  11400. np.slipForce = cm.friction*glen*reducedMass;
  11401. np.restitution = cm.restitution;
  11402. np.surfaceVelocity = cm.surfaceVelocity;
  11403. np.frictionStiffness = cm.frictionStiffness;
  11404. np.frictionRelaxation = cm.frictionRelaxation;
  11405. np.stiffness = cm.stiffness;
  11406. np.relaxation = cm.relaxation;
  11407. np.contactSkinSize = cm.contactSkinSize;
  11408. np.enabledEquations = bi.collisionResponse && bj.collisionResponse && si.collisionResponse && sj.collisionResponse;
  11409. var resolver = np[si.type | sj.type],
  11410. numContacts = 0;
  11411. if (resolver) {
  11412. var sensor = si.sensor || sj.sensor;
  11413. var numFrictionBefore = np.frictionEquations.length;
  11414. if (si.type < sj.type) {
  11415. numContacts = resolver.call(np, bi,si,xiw,aiw, bj,sj,xjw,ajw, sensor);
  11416. } else {
  11417. numContacts = resolver.call(np, bj,sj,xjw,ajw, bi,si,xiw,aiw, sensor);
  11418. }
  11419. var numFrictionEquations = np.frictionEquations.length - numFrictionBefore;
  11420. if(numContacts){
  11421. if( bi.allowSleep &&
  11422. bi.type === Body.DYNAMIC &&
  11423. bi.sleepState === Body.SLEEPING &&
  11424. bj.sleepState === Body.AWAKE &&
  11425. bj.type !== Body.STATIC
  11426. ){
  11427. var speedSquaredB = vec2.squaredLength(bj.velocity) + Math.pow(bj.angularVelocity,2);
  11428. var speedLimitSquaredB = Math.pow(bj.sleepSpeedLimit,2);
  11429. if(speedSquaredB >= speedLimitSquaredB*2){
  11430. bi._wakeUpAfterNarrowphase = true;
  11431. }
  11432. }
  11433. if( bj.allowSleep &&
  11434. bj.type === Body.DYNAMIC &&
  11435. bj.sleepState === Body.SLEEPING &&
  11436. bi.sleepState === Body.AWAKE &&
  11437. bi.type !== Body.STATIC
  11438. ){
  11439. var speedSquaredA = vec2.squaredLength(bi.velocity) + Math.pow(bi.angularVelocity,2);
  11440. var speedLimitSquaredA = Math.pow(bi.sleepSpeedLimit,2);
  11441. if(speedSquaredA >= speedLimitSquaredA*2){
  11442. bj._wakeUpAfterNarrowphase = true;
  11443. }
  11444. }
  11445. this.overlapKeeper.setOverlapping(bi, si, bj, sj);
  11446. if(this.has('beginContact') && this.overlapKeeper.isNewOverlap(si, sj)){
  11447. // Report new shape overlap
  11448. var e = this.beginContactEvent;
  11449. e.shapeA = si;
  11450. e.shapeB = sj;
  11451. e.bodyA = bi;
  11452. e.bodyB = bj;
  11453. // Reset contact equations
  11454. e.contactEquations.length = 0;
  11455. if(typeof(numContacts)==="number"){
  11456. for(var i=np.contactEquations.length-numContacts; i<np.contactEquations.length; i++){
  11457. e.contactEquations.push(np.contactEquations[i]);
  11458. }
  11459. }
  11460. this.emit(e);
  11461. }
  11462. // divide the max friction force by the number of contacts
  11463. if(typeof(numContacts)==="number" && numFrictionEquations > 1){ // Why divide by 1?
  11464. for(var i=np.frictionEquations.length-numFrictionEquations; i<np.frictionEquations.length; i++){
  11465. var f = np.frictionEquations[i];
  11466. f.setSlipForce(f.getSlipForce() / numFrictionEquations);
  11467. }
  11468. }
  11469. }
  11470. }
  11471. };
  11472. /**
  11473. * Add a spring to the simulation
  11474. *
  11475. * @method addSpring
  11476. * @param {Spring} spring
  11477. */
  11478. World.prototype.addSpring = function(spring){
  11479. this.springs.push(spring);
  11480. var evt = this.addSpringEvent;
  11481. evt.spring = spring;
  11482. this.emit(evt);
  11483. evt.spring = null;
  11484. };
  11485. /**
  11486. * Remove a spring
  11487. *
  11488. * @method removeSpring
  11489. * @param {Spring} spring
  11490. */
  11491. World.prototype.removeSpring = function(spring){
  11492. var idx = this.springs.indexOf(spring);
  11493. if(idx !== -1){
  11494. Utils.splice(this.springs,idx,1);
  11495. }
  11496. };
  11497. /**
  11498. * Add a body to the simulation
  11499. *
  11500. * @method addBody
  11501. * @param {Body} body
  11502. *
  11503. * @example
  11504. * var world = new World(),
  11505. * body = new Body();
  11506. * world.addBody(body);
  11507. * @todo What if this is done during step?
  11508. */
  11509. World.prototype.addBody = function(body){
  11510. if(this.bodies.indexOf(body) === -1){
  11511. this.bodies.push(body);
  11512. body.world = this;
  11513. var evt = this.addBodyEvent;
  11514. evt.body = body;
  11515. this.emit(evt);
  11516. evt.body = null;
  11517. }
  11518. };
  11519. /**
  11520. * Remove a body from the simulation. If this method is called during step(), the body removal is scheduled to after the step.
  11521. *
  11522. * @method removeBody
  11523. * @param {Body} body
  11524. */
  11525. World.prototype.removeBody = function(body){
  11526. if(this.stepping){
  11527. this.bodiesToBeRemoved.push(body);
  11528. } else {
  11529. body.world = null;
  11530. var idx = this.bodies.indexOf(body);
  11531. if(idx!==-1){
  11532. Utils.splice(this.bodies,idx,1);
  11533. this.removeBodyEvent.body = body;
  11534. body.resetConstraintVelocity();
  11535. this.emit(this.removeBodyEvent);
  11536. this.removeBodyEvent.body = null;
  11537. }
  11538. }
  11539. };
  11540. /**
  11541. * Get a body by its id.
  11542. * @method getBodyById
  11543. * @param {number} id
  11544. * @return {Body} The body, or false if it was not found.
  11545. */
  11546. World.prototype.getBodyById = function(id){
  11547. var bodies = this.bodies;
  11548. for(var i=0; i<bodies.length; i++){
  11549. var b = bodies[i];
  11550. if(b.id === id){
  11551. return b;
  11552. }
  11553. }
  11554. return false;
  11555. };
  11556. /**
  11557. * Disable collision between two bodies
  11558. * @method disableBodyCollision
  11559. * @param {Body} bodyA
  11560. * @param {Body} bodyB
  11561. */
  11562. World.prototype.disableBodyCollision = function(bodyA,bodyB){
  11563. this.disabledBodyCollisionPairs.push(bodyA,bodyB);
  11564. };
  11565. /**
  11566. * Enable collisions between the given two bodies
  11567. * @method enableBodyCollision
  11568. * @param {Body} bodyA
  11569. * @param {Body} bodyB
  11570. */
  11571. World.prototype.enableBodyCollision = function(bodyA,bodyB){
  11572. var pairs = this.disabledBodyCollisionPairs;
  11573. for(var i=0; i<pairs.length; i+=2){
  11574. if((pairs[i] === bodyA && pairs[i+1] === bodyB) || (pairs[i+1] === bodyA && pairs[i] === bodyB)){
  11575. pairs.splice(i,2);
  11576. return;
  11577. }
  11578. }
  11579. };
  11580. /**
  11581. * Resets the World, removes all bodies, constraints and springs.
  11582. *
  11583. * @method clear
  11584. */
  11585. World.prototype.clear = function(){
  11586. this.time = 0;
  11587. // Remove all solver equations
  11588. if(this.solver && this.solver.equations.length){
  11589. this.solver.removeAllEquations();
  11590. }
  11591. // Remove all constraints
  11592. var cs = this.constraints;
  11593. for(var i=cs.length-1; i>=0; i--){
  11594. this.removeConstraint(cs[i]);
  11595. }
  11596. // Remove all bodies
  11597. var bodies = this.bodies;
  11598. for(var i=bodies.length-1; i>=0; i--){
  11599. this.removeBody(bodies[i]);
  11600. }
  11601. // Remove all springs
  11602. var springs = this.springs;
  11603. for(var i=springs.length-1; i>=0; i--){
  11604. this.removeSpring(springs[i]);
  11605. }
  11606. // Remove all contact materials
  11607. var cms = this.contactMaterials;
  11608. for(var i=cms.length-1; i>=0; i--){
  11609. this.removeContactMaterial(cms[i]);
  11610. }
  11611. World.apply(this);
  11612. };
  11613. var hitTest_tmp1 = vec2.create(),
  11614. hitTest_zero = vec2.fromValues(0,0),
  11615. hitTest_tmp2 = vec2.fromValues(0,0);
  11616. /**
  11617. * Test if a world point overlaps bodies
  11618. * @method hitTest
  11619. * @param {Array} worldPoint Point to use for intersection tests
  11620. * @param {Array} bodies A list of objects to check for intersection
  11621. * @param {Number} precision Used for matching against particles and lines. Adds some margin to these infinitesimal objects.
  11622. * @return {Array} Array of bodies that overlap the point
  11623. * @todo Should use an api similar to the raycast function
  11624. * @todo Should probably implement a .containsPoint method for all shapes. Would be more efficient
  11625. */
  11626. World.prototype.hitTest = function(worldPoint,bodies,precision){
  11627. precision = precision || 0;
  11628. // Create a dummy particle body with a particle shape to test against the bodies
  11629. var pb = new Body({ position:worldPoint }),
  11630. ps = new Particle(),
  11631. px = worldPoint,
  11632. pa = 0,
  11633. x = hitTest_tmp1,
  11634. zero = hitTest_zero,
  11635. tmp = hitTest_tmp2;
  11636. pb.addShape(ps);
  11637. var n = this.narrowphase,
  11638. result = [];
  11639. // Check bodies
  11640. for(var i=0, N=bodies.length; i!==N; i++){
  11641. var b = bodies[i];
  11642. for(var j=0, NS=b.shapes.length; j!==NS; j++){
  11643. var s = b.shapes[j];
  11644. // Get shape world position + angle
  11645. vec2.rotate(x, s.position, b.angle);
  11646. vec2.add(x, x, b.position);
  11647. var a = s.angle + b.angle;
  11648. if( (s instanceof Circle && n.circleParticle (b,s,x,a, pb,ps,px,pa, true)) ||
  11649. (s instanceof Convex && n.particleConvex (pb,ps,px,pa, b,s,x,a, true)) ||
  11650. (s instanceof Plane && n.particlePlane (pb,ps,px,pa, b,s,x,a, true)) ||
  11651. (s instanceof Capsule && n.particleCapsule (pb,ps,px,pa, b,s,x,a, true)) ||
  11652. (s instanceof Particle && vec2.squaredLength(vec2.sub(tmp,x,worldPoint)) < precision*precision)
  11653. ){
  11654. result.push(b);
  11655. }
  11656. }
  11657. }
  11658. return result;
  11659. };
  11660. /**
  11661. * Set the stiffness for all equations and contact materials.
  11662. * @method setGlobalStiffness
  11663. * @param {Number} stiffness
  11664. */
  11665. World.prototype.setGlobalStiffness = function(stiffness){
  11666. // Set for all constraints
  11667. var constraints = this.constraints;
  11668. for(var i=0; i !== constraints.length; i++){
  11669. var c = constraints[i];
  11670. for(var j=0; j !== c.equations.length; j++){
  11671. var eq = c.equations[j];
  11672. eq.stiffness = stiffness;
  11673. eq.needsUpdate = true;
  11674. }
  11675. }
  11676. // Set for all contact materials
  11677. var contactMaterials = this.contactMaterials;
  11678. for(var i=0; i !== contactMaterials.length; i++){
  11679. var c = contactMaterials[i];
  11680. c.stiffness = c.frictionStiffness = stiffness;
  11681. }
  11682. // Set for default contact material
  11683. var c = this.defaultContactMaterial;
  11684. c.stiffness = c.frictionStiffness = stiffness;
  11685. };
  11686. /**
  11687. * Set the relaxation for all equations and contact materials.
  11688. * @method setGlobalRelaxation
  11689. * @param {Number} relaxation
  11690. */
  11691. World.prototype.setGlobalRelaxation = function(relaxation){
  11692. // Set for all constraints
  11693. for(var i=0; i !== this.constraints.length; i++){
  11694. var c = this.constraints[i];
  11695. for(var j=0; j !== c.equations.length; j++){
  11696. var eq = c.equations[j];
  11697. eq.relaxation = relaxation;
  11698. eq.needsUpdate = true;
  11699. }
  11700. }
  11701. // Set for all contact materials
  11702. for(var i=0; i !== this.contactMaterials.length; i++){
  11703. var c = this.contactMaterials[i];
  11704. c.relaxation = c.frictionRelaxation = relaxation;
  11705. }
  11706. // Set for default contact material
  11707. var c = this.defaultContactMaterial;
  11708. c.relaxation = c.frictionRelaxation = relaxation;
  11709. };
  11710. var tmpAABB = new AABB();
  11711. var tmpArray = [];
  11712. /**
  11713. * Ray cast against all bodies in the world.
  11714. * @method raycast
  11715. * @param {RaycastResult} result
  11716. * @param {Ray} ray
  11717. * @return {boolean} True if any body was hit.
  11718. *
  11719. * @example
  11720. * var ray = new Ray({
  11721. * mode: Ray.CLOSEST, // or ANY
  11722. * from: [0, 0],
  11723. * to: [10, 0],
  11724. * });
  11725. * var result = new RaycastResult();
  11726. * world.raycast(result, ray);
  11727. *
  11728. * // Get the hit point
  11729. * var hitPoint = vec2.create();
  11730. * result.getHitPoint(hitPoint, ray);
  11731. * console.log('Hit point: ', hitPoint[0], hitPoint[1], ' at distance ' + result.getHitDistance(ray));
  11732. *
  11733. * @example
  11734. * var ray = new Ray({
  11735. * mode: Ray.ALL,
  11736. * from: [0, 0],
  11737. * to: [10, 0],
  11738. * callback: function(result){
  11739. *
  11740. * // Print some info about the hit
  11741. * console.log('Hit body and shape: ', result.body, result.shape);
  11742. *
  11743. * // Get the hit point
  11744. * var hitPoint = vec2.create();
  11745. * result.getHitPoint(hitPoint, ray);
  11746. * console.log('Hit point: ', hitPoint[0], hitPoint[1], ' at distance ' + result.getHitDistance(ray));
  11747. *
  11748. * // If you are happy with the hits you got this far, you can stop the traversal here:
  11749. * result.stop();
  11750. * }
  11751. * });
  11752. * var result = new RaycastResult();
  11753. * world.raycast(result, ray);
  11754. */
  11755. World.prototype.raycast = function(result, ray){
  11756. // Get all bodies within the ray AABB
  11757. ray.getAABB(tmpAABB);
  11758. this.broadphase.aabbQuery(this, tmpAABB, tmpArray);
  11759. ray.intersectBodies(result, tmpArray);
  11760. tmpArray.length = 0;
  11761. return result.hasHit();
  11762. };
  11763. },{"../../package.json":6,"../collision/AABB":7,"../collision/Broadphase":8,"../collision/Narrowphase":10,"../collision/Ray":11,"../collision/SAPBroadphase":13,"../constraints/Constraint":14,"../constraints/DistanceConstraint":15,"../constraints/GearConstraint":16,"../constraints/LockConstraint":17,"../constraints/PrismaticConstraint":18,"../constraints/RevoluteConstraint":19,"../events/EventEmitter":26,"../material/ContactMaterial":27,"../material/Material":28,"../math/vec2":30,"../objects/Body":31,"../objects/LinearSpring":32,"../objects/RotationalSpring":33,"../shapes/Capsule":38,"../shapes/Circle":39,"../shapes/Convex":40,"../shapes/Line":42,"../shapes/Particle":43,"../shapes/Plane":44,"../shapes/Shape":45,"../solver/GSSolver":46,"../solver/Solver":47,"../utils/OverlapKeeper":52,"../utils/Utils":57,"./IslandManager":59}]},{},[36])
  11764. (36)
  11765. });
  11766. /**
  11767. * @author Mat Groves http://matgroves.com/ @Doormat23
  11768. */
  11769. (function(){
  11770. var root = this;
  11771. /**
  11772. * @author Mat Groves http://matgroves.com/ @Doormat23
  11773. */
  11774. /**
  11775. * The [pixi.js](http://www.pixijs.com/) module/namespace.
  11776. *
  11777. * @module PIXI
  11778. */
  11779. /**
  11780. * Namespace-class for [pixi.js](http://www.pixijs.com/).
  11781. *
  11782. * Contains assorted static properties and enumerations.
  11783. *
  11784. * @class PIXI
  11785. * @static
  11786. */
  11787. var PIXI = PIXI || {};
  11788. /**
  11789. * A reference to the Phaser Game instance that owns this Pixi renderer.
  11790. * @property {Phaser.Game} game
  11791. * @static
  11792. */
  11793. PIXI.game = null;
  11794. /**
  11795. * @property {Number} WEBGL_RENDERER
  11796. * @protected
  11797. * @static
  11798. */
  11799. PIXI.WEBGL_RENDERER = 0;
  11800. /**
  11801. * @property {Number} CANVAS_RENDERER
  11802. * @protected
  11803. * @static
  11804. */
  11805. PIXI.CANVAS_RENDERER = 1;
  11806. /**
  11807. * Version of pixi that is loaded.
  11808. * @property {String} VERSION
  11809. * @static
  11810. */
  11811. PIXI.VERSION = "v2.2.9";
  11812. // used to create uids for various pixi objects.
  11813. PIXI._UID = 0;
  11814. if (typeof(Float32Array) != 'undefined')
  11815. {
  11816. PIXI.Float32Array = Float32Array;
  11817. PIXI.Uint16Array = Uint16Array;
  11818. // Uint32Array and ArrayBuffer only used by WebGL renderer
  11819. // We can suppose that if WebGL is supported then typed arrays are supported too
  11820. // as they predate WebGL support for all browsers:
  11821. // see typed arrays support: http://caniuse.com/#search=TypedArrays
  11822. // see WebGL support: http://caniuse.com/#search=WebGL
  11823. PIXI.Uint32Array = Uint32Array;
  11824. PIXI.ArrayBuffer = ArrayBuffer;
  11825. }
  11826. else
  11827. {
  11828. PIXI.Float32Array = Array;
  11829. PIXI.Uint16Array = Array;
  11830. }
  11831. /**
  11832. * @property {Number} PI_2
  11833. * @static
  11834. */
  11835. PIXI.PI_2 = Math.PI * 2;
  11836. /**
  11837. * @property {Number} RAD_TO_DEG
  11838. * @static
  11839. */
  11840. PIXI.RAD_TO_DEG = 180 / Math.PI;
  11841. /**
  11842. * @property {Number} DEG_TO_RAD
  11843. * @static
  11844. */
  11845. PIXI.DEG_TO_RAD = Math.PI / 180;
  11846. /**
  11847. * @property {String} RETINA_PREFIX
  11848. * @protected
  11849. * @static
  11850. */
  11851. PIXI.RETINA_PREFIX = "@2x";
  11852. /**
  11853. * The default render options if none are supplied to
  11854. * {{#crossLink "WebGLRenderer"}}{{/crossLink}} or {{#crossLink "CanvasRenderer"}}{{/crossLink}}.
  11855. *
  11856. * @property {Object} defaultRenderOptions
  11857. * @property {Object} defaultRenderOptions.view=null
  11858. * @property {Boolean} defaultRenderOptions.transparent=false
  11859. * @property {Boolean} defaultRenderOptions.antialias=false
  11860. * @property {Boolean} defaultRenderOptions.preserveDrawingBuffer=false
  11861. * @property {Number} defaultRenderOptions.resolution=1
  11862. * @property {Boolean} defaultRenderOptions.clearBeforeRender=true
  11863. * @property {Boolean} defaultRenderOptions.autoResize=false
  11864. * @static
  11865. PIXI.defaultRenderOptions = {
  11866. view: null,
  11867. transparent: false,
  11868. antialias: false,
  11869. preserveDrawingBuffer: false,
  11870. resolution: 1,
  11871. clearBeforeRender: true,
  11872. autoResize: false
  11873. };
  11874. */
  11875. /**
  11876. * @author Mat Groves http://matgroves.com/ @Doormat23
  11877. */
  11878. /**
  11879. * The base class for all objects that are rendered on the screen.
  11880. * This is an abstract class and should not be used on its own rather it should be extended.
  11881. *
  11882. * @class DisplayObject
  11883. * @constructor
  11884. */
  11885. PIXI.DisplayObject = function()
  11886. {
  11887. /**
  11888. * The coordinate of the object relative to the local coordinates of the parent.
  11889. *
  11890. * @property position
  11891. * @type Point
  11892. */
  11893. this.position = new PIXI.Point(0, 0);
  11894. /**
  11895. * The scale factor of the object.
  11896. *
  11897. * @property scale
  11898. * @type Point
  11899. */
  11900. this.scale = new PIXI.Point(1, 1);
  11901. /**
  11902. * The pivot point of the displayObject that it rotates around
  11903. *
  11904. * @property pivot
  11905. * @type Point
  11906. */
  11907. this.pivot = new PIXI.Point(0, 0);
  11908. /**
  11909. * The rotation of the object in radians.
  11910. *
  11911. * @property rotation
  11912. * @type Number
  11913. */
  11914. this.rotation = 0;
  11915. /**
  11916. * The opacity of the object.
  11917. *
  11918. * @property alpha
  11919. * @type Number
  11920. */
  11921. this.alpha = 1;
  11922. /**
  11923. * The visibility of the object.
  11924. *
  11925. * @property visible
  11926. * @type Boolean
  11927. */
  11928. this.visible = true;
  11929. /**
  11930. * This is the defined area that will pick up mouse / touch events. It is null by default.
  11931. * 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)
  11932. *
  11933. * @property hitArea
  11934. * @type Rectangle|Circle|Ellipse|Polygon
  11935. */
  11936. this.hitArea = null;
  11937. /**
  11938. * Can this object be rendered
  11939. *
  11940. * @property renderable
  11941. * @type Boolean
  11942. */
  11943. this.renderable = false;
  11944. /**
  11945. * [read-only] The display object container that contains this display object.
  11946. *
  11947. * @property parent
  11948. * @type DisplayObjectContainer
  11949. * @readOnly
  11950. */
  11951. this.parent = null;
  11952. /**
  11953. * [read-only] The stage the display object is connected to, or undefined if it is not connected to the stage.
  11954. *
  11955. * @property stage
  11956. * @type Stage
  11957. * @readOnly
  11958. */
  11959. this.stage = null;
  11960. /**
  11961. * [read-only] The multiplied alpha of the displayObject
  11962. *
  11963. * @property worldAlpha
  11964. * @type Number
  11965. * @readOnly
  11966. */
  11967. this.worldAlpha = 1;
  11968. /**
  11969. * [read-only] Current transform of the object based on world (parent) factors
  11970. *
  11971. * @property worldTransform
  11972. * @type Matrix
  11973. * @readOnly
  11974. * @private
  11975. */
  11976. this.worldTransform = new PIXI.Matrix();
  11977. /**
  11978. * The position of the Display Object based on the world transform.
  11979. * This value is updated at the end of updateTransform and takes all parent transforms into account.
  11980. *
  11981. * @property worldPosition
  11982. * @type Point
  11983. * @readOnly
  11984. */
  11985. this.worldPosition = new PIXI.Point(0, 0);
  11986. /**
  11987. * The scale of the Display Object based on the world transform.
  11988. * This value is updated at the end of updateTransform and takes all parent transforms into account.
  11989. *
  11990. * @property worldScale
  11991. * @type Point
  11992. * @readOnly
  11993. */
  11994. this.worldScale = new PIXI.Point(1, 1);
  11995. /**
  11996. * The rotation of the Display Object, in radians, based on the world transform.
  11997. * This value is updated at the end of updateTransform and takes all parent transforms into account.
  11998. *
  11999. * @property worldRotation
  12000. * @type Number
  12001. * @readOnly
  12002. */
  12003. this.worldRotation = 0;
  12004. /**
  12005. * cached sin rotation and cos rotation
  12006. *
  12007. * @property _sr
  12008. * @type Number
  12009. * @private
  12010. */
  12011. this._sr = 0;
  12012. /**
  12013. * cached sin rotation and cos rotation
  12014. *
  12015. * @property _cr
  12016. * @type Number
  12017. * @private
  12018. */
  12019. this._cr = 1;
  12020. /**
  12021. * The area the filter is applied to like the hitArea this is used as more of an optimisation
  12022. * rather than figuring out the dimensions of the displayObject each frame you can set this rectangle
  12023. *
  12024. * @property filterArea
  12025. * @type Rectangle
  12026. */
  12027. this.filterArea = null;
  12028. /**
  12029. * The original, cached bounds of the object
  12030. *
  12031. * @property _bounds
  12032. * @type Rectangle
  12033. * @private
  12034. */
  12035. this._bounds = new PIXI.Rectangle(0, 0, 1, 1);
  12036. /**
  12037. * The most up-to-date bounds of the object
  12038. *
  12039. * @property _currentBounds
  12040. * @type Rectangle
  12041. * @private
  12042. */
  12043. this._currentBounds = null;
  12044. /**
  12045. * The original, cached mask of the object
  12046. *
  12047. * @property _mask
  12048. * @type Rectangle
  12049. * @private
  12050. */
  12051. this._mask = null;
  12052. /**
  12053. * Cached internal flag.
  12054. *
  12055. * @property _cacheAsBitmap
  12056. * @type Boolean
  12057. * @private
  12058. */
  12059. this._cacheAsBitmap = false;
  12060. /**
  12061. * Cached internal flag.
  12062. *
  12063. * @property _cacheIsDirty
  12064. * @type Boolean
  12065. * @private
  12066. */
  12067. this._cacheIsDirty = false;
  12068. };
  12069. // constructor
  12070. PIXI.DisplayObject.prototype.constructor = PIXI.DisplayObject;
  12071. /**
  12072. * Destroy this DisplayObject.
  12073. * Removes all references to transformCallbacks, its parent, the stage, filters, bounds, mask and cached Sprites.
  12074. *
  12075. * @method destroy
  12076. */
  12077. PIXI.DisplayObject.prototype.destroy = function()
  12078. {
  12079. if (this.children)
  12080. {
  12081. var i = this.children.length;
  12082. while (i--)
  12083. {
  12084. this.children[i].destroy();
  12085. }
  12086. this.children = [];
  12087. }
  12088. this.hitArea = null;
  12089. this.parent = null;
  12090. this.stage = null;
  12091. this.worldTransform = null;
  12092. this.filterArea = null;
  12093. this._bounds = null;
  12094. this._currentBounds = null;
  12095. this._mask = null;
  12096. // In case Pixi is still going to try and render it even though destroyed
  12097. this.renderable = false;
  12098. this._destroyCachedSprite();
  12099. };
  12100. /**
  12101. * [read-only] Indicates if the sprite is globally visible.
  12102. *
  12103. * @property worldVisible
  12104. * @type Boolean
  12105. */
  12106. Object.defineProperty(PIXI.DisplayObject.prototype, 'worldVisible', {
  12107. get: function() {
  12108. var item = this;
  12109. do
  12110. {
  12111. if (!item.visible) return false;
  12112. item = item.parent;
  12113. }
  12114. while(item);
  12115. return true;
  12116. }
  12117. });
  12118. /**
  12119. * 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.
  12120. * In PIXI a regular mask must be a PIXI.Graphics object. This allows for much faster masking in canvas as it utilises shape clipping.
  12121. * To remove a mask, set this property to null.
  12122. *
  12123. * @property mask
  12124. * @type Graphics
  12125. */
  12126. Object.defineProperty(PIXI.DisplayObject.prototype, 'mask', {
  12127. get: function() {
  12128. return this._mask;
  12129. },
  12130. set: function(value) {
  12131. if (this._mask) this._mask.isMask = false;
  12132. this._mask = value;
  12133. if (this._mask) this._mask.isMask = true;
  12134. }
  12135. });
  12136. /**
  12137. * Sets the filters for the displayObject.
  12138. * IMPORTANT: This is a webGL only feature and will be ignored by the Canvas renderer.
  12139. *
  12140. * To remove filters simply set this property to 'null'.
  12141. *
  12142. * You cannot have a filter and a multiply blend mode active at the same time. Setting a filter will reset
  12143. * this objects blend mode to NORMAL.
  12144. *
  12145. * @property filters
  12146. * @type Array(Filter)
  12147. */
  12148. Object.defineProperty(PIXI.DisplayObject.prototype, 'filters', {
  12149. get: function() {
  12150. return this._filters;
  12151. },
  12152. set: function(value) {
  12153. if (value)
  12154. {
  12155. // now put all the passes in one place..
  12156. var passes = [];
  12157. for (var i = 0; i < value.length; i++)
  12158. {
  12159. var filterPasses = value[i].passes;
  12160. for (var j = 0; j < filterPasses.length; j++)
  12161. {
  12162. passes.push(filterPasses[j]);
  12163. }
  12164. }
  12165. // TODO change this as it is legacy
  12166. this._filterBlock = { target: this, filterPasses: passes };
  12167. }
  12168. this._filters = value;
  12169. if (this.blendMode && this.blendMode === PIXI.blendModes.MULTIPLY)
  12170. {
  12171. this.blendMode = PIXI.blendModes.NORMAL;
  12172. }
  12173. }
  12174. });
  12175. /**
  12176. * Set if this display object is cached as a bitmap.
  12177. * This basically takes a snap shot of the display object as it is at that moment. It can provide a performance benefit for complex static displayObjects.
  12178. * To remove simply set this property to 'null'
  12179. * @property cacheAsBitmap
  12180. * @type Boolean
  12181. */
  12182. Object.defineProperty(PIXI.DisplayObject.prototype, 'cacheAsBitmap', {
  12183. get: function() {
  12184. return this._cacheAsBitmap;
  12185. },
  12186. set: function(value) {
  12187. if (this._cacheAsBitmap === value)
  12188. {
  12189. return;
  12190. }
  12191. if (value)
  12192. {
  12193. this._generateCachedSprite();
  12194. }
  12195. else
  12196. {
  12197. this._destroyCachedSprite();
  12198. }
  12199. this._cacheAsBitmap = value;
  12200. }
  12201. });
  12202. /*
  12203. * Updates the object transform for rendering.
  12204. *
  12205. * If the object has no parent, and no parent parameter is provided, it will default to Phaser.Game.World as the parent.
  12206. * If that is unavailable the transform fails to take place.
  12207. *
  12208. * The `parent` parameter has priority over the actual parent. Use it as a parent override.
  12209. * Setting it does **not** change the actual parent of this DisplayObject, it just uses the parent for the transform update.
  12210. *
  12211. * @method updateTransform
  12212. * @param {DisplayObject} [parent] - Optional parent to parent this DisplayObject transform from.
  12213. */
  12214. PIXI.DisplayObject.prototype.updateTransform = function(parent)
  12215. {
  12216. if (!parent && !this.parent && !this.game)
  12217. {
  12218. return;
  12219. }
  12220. var p = this.parent;
  12221. if (parent)
  12222. {
  12223. p = parent;
  12224. }
  12225. else if (!this.parent)
  12226. {
  12227. p = this.game.world;
  12228. }
  12229. // create some matrix refs for easy access
  12230. var pt = p.worldTransform;
  12231. var wt = this.worldTransform;
  12232. // temporary matrix variables
  12233. var a, b, c, d, tx, ty;
  12234. // so if rotation is between 0 then we can simplify the multiplication process..
  12235. if (this.rotation % PIXI.PI_2)
  12236. {
  12237. // check to see if the rotation is the same as the previous render. This means we only need to use sin and cos when rotation actually changes
  12238. if (this.rotation !== this.rotationCache)
  12239. {
  12240. this.rotationCache = this.rotation;
  12241. this._sr = Math.sin(this.rotation);
  12242. this._cr = Math.cos(this.rotation);
  12243. }
  12244. // get the matrix values of the displayobject based on its transform properties..
  12245. a = this._cr * this.scale.x;
  12246. b = this._sr * this.scale.x;
  12247. c = -this._sr * this.scale.y;
  12248. d = this._cr * this.scale.y;
  12249. tx = this.position.x;
  12250. ty = this.position.y;
  12251. // check for pivot.. not often used so geared towards that fact!
  12252. if (this.pivot.x || this.pivot.y)
  12253. {
  12254. tx -= this.pivot.x * a + this.pivot.y * c;
  12255. ty -= this.pivot.x * b + this.pivot.y * d;
  12256. }
  12257. // concat the parent matrix with the objects transform.
  12258. wt.a = a * pt.a + b * pt.c;
  12259. wt.b = a * pt.b + b * pt.d;
  12260. wt.c = c * pt.a + d * pt.c;
  12261. wt.d = c * pt.b + d * pt.d;
  12262. wt.tx = tx * pt.a + ty * pt.c + pt.tx;
  12263. wt.ty = tx * pt.b + ty * pt.d + pt.ty;
  12264. }
  12265. else
  12266. {
  12267. // lets do the fast version as we know there is no rotation..
  12268. a = this.scale.x;
  12269. d = this.scale.y;
  12270. tx = this.position.x - this.pivot.x * a;
  12271. ty = this.position.y - this.pivot.y * d;
  12272. wt.a = a * pt.a;
  12273. wt.b = a * pt.b;
  12274. wt.c = d * pt.c;
  12275. wt.d = d * pt.d;
  12276. wt.tx = tx * pt.a + ty * pt.c + pt.tx;
  12277. wt.ty = tx * pt.b + ty * pt.d + pt.ty;
  12278. }
  12279. // multiply the alphas..
  12280. this.worldAlpha = this.alpha * p.worldAlpha;
  12281. this.worldPosition.set(wt.tx, wt.ty);
  12282. this.worldScale.set(Math.sqrt(wt.a * wt.a + wt.b * wt.b), Math.sqrt(wt.c * wt.c + wt.d * wt.d));
  12283. this.worldRotation = Math.atan2(-wt.c, wt.d);
  12284. // reset the bounds each time this is called!
  12285. this._currentBounds = null;
  12286. // Custom callback?
  12287. if (this.transformCallback)
  12288. {
  12289. this.transformCallback.call(this.transformCallbackContext, wt, pt);
  12290. }
  12291. };
  12292. // performance increase to avoid using call.. (10x faster)
  12293. PIXI.DisplayObject.prototype.displayObjectUpdateTransform = PIXI.DisplayObject.prototype.updateTransform;
  12294. /**
  12295. * Retrieves the bounds of the displayObject as a rectangle object
  12296. *
  12297. * @method getBounds
  12298. * @param matrix {Matrix}
  12299. * @return {Rectangle} the rectangular bounding area
  12300. */
  12301. PIXI.DisplayObject.prototype.getBounds = function(matrix)
  12302. {
  12303. matrix = matrix;//just to get passed js hinting (and preserve inheritance)
  12304. return PIXI.EmptyRectangle;
  12305. };
  12306. /**
  12307. * Retrieves the local bounds of the displayObject as a rectangle object
  12308. *
  12309. * @method getLocalBounds
  12310. * @return {Rectangle} the rectangular bounding area
  12311. */
  12312. PIXI.DisplayObject.prototype.getLocalBounds = function()
  12313. {
  12314. return this.getBounds(PIXI.identityMatrix);///PIXI.EmptyRectangle();
  12315. };
  12316. /**
  12317. * Sets the object's stage reference, the stage this object is connected to
  12318. *
  12319. * @method setStageReference
  12320. * @param stage {Stage} the stage that the object will have as its current stage reference
  12321. */
  12322. PIXI.DisplayObject.prototype.setStageReference = function(stage)
  12323. {
  12324. this.stage = stage;
  12325. };
  12326. /**
  12327. * Empty, to be overridden by classes that require it.
  12328. *
  12329. * @method preUpdate
  12330. */
  12331. PIXI.DisplayObject.prototype.preUpdate = function()
  12332. {
  12333. };
  12334. /**
  12335. * Useful function that returns a texture of the displayObject object that can then be used to create sprites
  12336. * This can be quite useful if your displayObject is static / complicated and needs to be reused multiple times.
  12337. *
  12338. * @method generateTexture
  12339. * @param resolution {Number} The resolution of the texture being generated
  12340. * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values
  12341. * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture.
  12342. * @return {Texture} a texture of the graphics object
  12343. */
  12344. PIXI.DisplayObject.prototype.generateTexture = function(resolution, scaleMode, renderer)
  12345. {
  12346. var bounds = this.getLocalBounds();
  12347. var renderTexture = new PIXI.RenderTexture(bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution);
  12348. PIXI.DisplayObject._tempMatrix.tx = -bounds.x;
  12349. PIXI.DisplayObject._tempMatrix.ty = -bounds.y;
  12350. renderTexture.render(this, PIXI.DisplayObject._tempMatrix);
  12351. return renderTexture;
  12352. };
  12353. /**
  12354. * Generates and updates the cached sprite for this object.
  12355. *
  12356. * @method updateCache
  12357. */
  12358. PIXI.DisplayObject.prototype.updateCache = function()
  12359. {
  12360. this._generateCachedSprite();
  12361. };
  12362. /**
  12363. * Calculates the global position of the display object
  12364. *
  12365. * @method toGlobal
  12366. * @param position {Point} The world origin to calculate from
  12367. * @return {Point} A point object representing the position of this object
  12368. */
  12369. PIXI.DisplayObject.prototype.toGlobal = function(position)
  12370. {
  12371. // don't need to u[date the lot
  12372. this.displayObjectUpdateTransform();
  12373. return this.worldTransform.apply(position);
  12374. };
  12375. /**
  12376. * Calculates the local position of the display object relative to another point
  12377. *
  12378. * @method toLocal
  12379. * @param position {Point} The world origin to calculate from
  12380. * @param [from] {DisplayObject} The DisplayObject to calculate the global position from
  12381. * @return {Point} A point object representing the position of this object
  12382. */
  12383. PIXI.DisplayObject.prototype.toLocal = function(position, from)
  12384. {
  12385. if (from)
  12386. {
  12387. position = from.toGlobal(position);
  12388. }
  12389. // don't need to u[date the lot
  12390. this.displayObjectUpdateTransform();
  12391. return this.worldTransform.applyInverse(position);
  12392. };
  12393. /**
  12394. * Internal method.
  12395. *
  12396. * @method _renderCachedSprite
  12397. * @param renderSession {Object} The render session
  12398. * @private
  12399. */
  12400. PIXI.DisplayObject.prototype._renderCachedSprite = function(renderSession)
  12401. {
  12402. this._cachedSprite.worldAlpha = this.worldAlpha;
  12403. if (renderSession.gl)
  12404. {
  12405. PIXI.Sprite.prototype._renderWebGL.call(this._cachedSprite, renderSession);
  12406. }
  12407. else
  12408. {
  12409. PIXI.Sprite.prototype._renderCanvas.call(this._cachedSprite, renderSession);
  12410. }
  12411. };
  12412. /**
  12413. * Internal method.
  12414. *
  12415. * @method _generateCachedSprite
  12416. * @private
  12417. */
  12418. PIXI.DisplayObject.prototype._generateCachedSprite = function()
  12419. {
  12420. this._cacheAsBitmap = false;
  12421. var bounds = this.getLocalBounds();
  12422. // Round it off and force non-zero dimensions
  12423. bounds.width = Math.max(1, Math.ceil(bounds.width));
  12424. bounds.height = Math.max(1, Math.ceil(bounds.height));
  12425. this.updateTransform();
  12426. if (!this._cachedSprite)
  12427. {
  12428. var renderTexture = new PIXI.RenderTexture(bounds.width, bounds.height);
  12429. this._cachedSprite = new PIXI.Sprite(renderTexture);
  12430. this._cachedSprite.worldTransform = this.worldTransform;
  12431. }
  12432. else
  12433. {
  12434. this._cachedSprite.texture.resize(bounds.width, bounds.height);
  12435. }
  12436. // Remove filters
  12437. var tempFilters = this._filters;
  12438. this._filters = null;
  12439. this._cachedSprite.filters = tempFilters;
  12440. // PIXI.DisplayObject._tempMatrix.identity();
  12441. PIXI.DisplayObject._tempMatrix.tx = -bounds.x;
  12442. PIXI.DisplayObject._tempMatrix.ty = -bounds.y;
  12443. this._cachedSprite.texture.render(this, PIXI.DisplayObject._tempMatrix, true);
  12444. this._cachedSprite.anchor.x = -(bounds.x / bounds.width);
  12445. this._cachedSprite.anchor.y = -(bounds.y / bounds.height);
  12446. this._filters = tempFilters;
  12447. this._cacheAsBitmap = true;
  12448. };
  12449. /**
  12450. * Destroys the cached sprite.
  12451. *
  12452. * @method _destroyCachedSprite
  12453. * @private
  12454. */
  12455. PIXI.DisplayObject.prototype._destroyCachedSprite = function()
  12456. {
  12457. if (!this._cachedSprite) return;
  12458. this._cachedSprite.texture.destroy(true);
  12459. // TODO could be object pooled!
  12460. this._cachedSprite = null;
  12461. };
  12462. /**
  12463. * Renders the object using the WebGL renderer
  12464. *
  12465. * @method _renderWebGL
  12466. * @param renderSession {RenderSession}
  12467. * @private
  12468. */
  12469. PIXI.DisplayObject.prototype._renderWebGL = function(renderSession)
  12470. {
  12471. // OVERWRITE;
  12472. // this line is just here to pass jshinting :)
  12473. renderSession = renderSession;
  12474. };
  12475. /**
  12476. * Renders the object using the Canvas renderer
  12477. *
  12478. * @method _renderCanvas
  12479. * @param renderSession {RenderSession}
  12480. * @private
  12481. */
  12482. PIXI.DisplayObject.prototype._renderCanvas = function(renderSession)
  12483. {
  12484. // OVERWRITE;
  12485. // this line is just here to pass jshinting :)
  12486. renderSession = renderSession;
  12487. };
  12488. /**
  12489. * The position of the displayObject on the x axis relative to the local coordinates of the parent.
  12490. *
  12491. * @property x
  12492. * @type Number
  12493. */
  12494. Object.defineProperty(PIXI.DisplayObject.prototype, 'x', {
  12495. get: function() {
  12496. return this.position.x;
  12497. },
  12498. set: function(value) {
  12499. this.position.x = value;
  12500. }
  12501. });
  12502. /**
  12503. * The position of the displayObject on the y axis relative to the local coordinates of the parent.
  12504. *
  12505. * @property y
  12506. * @type Number
  12507. */
  12508. Object.defineProperty(PIXI.DisplayObject.prototype, 'y', {
  12509. get: function() {
  12510. return this.position.y;
  12511. },
  12512. set: function(value) {
  12513. this.position.y = value;
  12514. }
  12515. });
  12516. /**
  12517. * @author Mat Groves http://matgroves.com/ @Doormat23
  12518. */
  12519. /**
  12520. * A DisplayObjectContainer represents a collection of display objects.
  12521. * It is the base class of all display objects that act as a container for other objects.
  12522. *
  12523. * @class DisplayObjectContainer
  12524. * @extends DisplayObject
  12525. * @constructor
  12526. */
  12527. PIXI.DisplayObjectContainer = function()
  12528. {
  12529. PIXI.DisplayObject.call(this);
  12530. /**
  12531. * [read-only] The array of children of this container.
  12532. *
  12533. * @property children
  12534. * @type Array(DisplayObject)
  12535. * @readOnly
  12536. */
  12537. this.children = [];
  12538. };
  12539. // constructor
  12540. PIXI.DisplayObjectContainer.prototype = Object.create( PIXI.DisplayObject.prototype );
  12541. PIXI.DisplayObjectContainer.prototype.constructor = PIXI.DisplayObjectContainer;
  12542. /**
  12543. * The width of the displayObjectContainer, setting this will actually modify the scale to achieve the value set
  12544. *
  12545. * @property width
  12546. * @type Number
  12547. */
  12548. Object.defineProperty(PIXI.DisplayObjectContainer.prototype, 'width', {
  12549. get: function() {
  12550. return this.scale.x * this.getLocalBounds().width;
  12551. },
  12552. set: function(value) {
  12553. var width = this.getLocalBounds().width;
  12554. if (width !== 0)
  12555. {
  12556. this.scale.x = value / width;
  12557. }
  12558. else
  12559. {
  12560. this.scale.x = 1;
  12561. }
  12562. this._width = value;
  12563. }
  12564. });
  12565. /**
  12566. * The height of the displayObjectContainer, setting this will actually modify the scale to achieve the value set
  12567. *
  12568. * @property height
  12569. * @type Number
  12570. */
  12571. Object.defineProperty(PIXI.DisplayObjectContainer.prototype, 'height', {
  12572. get: function() {
  12573. return this.scale.y * this.getLocalBounds().height;
  12574. },
  12575. set: function(value) {
  12576. var height = this.getLocalBounds().height;
  12577. if (height !== 0)
  12578. {
  12579. this.scale.y = value / height;
  12580. }
  12581. else
  12582. {
  12583. this.scale.y = 1;
  12584. }
  12585. this._height = value;
  12586. }
  12587. });
  12588. /**
  12589. * Adds a child to the container.
  12590. *
  12591. * @method addChild
  12592. * @param child {DisplayObject} The DisplayObject to add to the container
  12593. * @return {DisplayObject} The child that was added.
  12594. */
  12595. PIXI.DisplayObjectContainer.prototype.addChild = function(child)
  12596. {
  12597. return this.addChildAt(child, this.children.length);
  12598. };
  12599. /**
  12600. * Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown
  12601. *
  12602. * @method addChildAt
  12603. * @param child {DisplayObject} The child to add
  12604. * @param index {Number} The index to place the child in
  12605. * @return {DisplayObject} The child that was added.
  12606. */
  12607. PIXI.DisplayObjectContainer.prototype.addChildAt = function(child, index)
  12608. {
  12609. if(index >= 0 && index <= this.children.length)
  12610. {
  12611. if(child.parent)
  12612. {
  12613. child.parent.removeChild(child);
  12614. }
  12615. child.parent = this;
  12616. this.children.splice(index, 0, child);
  12617. if(this.stage)child.setStageReference(this.stage);
  12618. return child;
  12619. }
  12620. else
  12621. {
  12622. throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length);
  12623. }
  12624. };
  12625. /**
  12626. * Swaps the position of 2 Display Objects within this container.
  12627. *
  12628. * @method swapChildren
  12629. * @param child {DisplayObject}
  12630. * @param child2 {DisplayObject}
  12631. */
  12632. PIXI.DisplayObjectContainer.prototype.swapChildren = function(child, child2)
  12633. {
  12634. if(child === child2) {
  12635. return;
  12636. }
  12637. var index1 = this.getChildIndex(child);
  12638. var index2 = this.getChildIndex(child2);
  12639. if(index1 < 0 || index2 < 0) {
  12640. throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.');
  12641. }
  12642. this.children[index1] = child2;
  12643. this.children[index2] = child;
  12644. };
  12645. /**
  12646. * Returns the index position of a child DisplayObject instance
  12647. *
  12648. * @method getChildIndex
  12649. * @param child {DisplayObject} The DisplayObject instance to identify
  12650. * @return {Number} The index position of the child display object to identify
  12651. */
  12652. PIXI.DisplayObjectContainer.prototype.getChildIndex = function(child)
  12653. {
  12654. var index = this.children.indexOf(child);
  12655. if (index === -1)
  12656. {
  12657. throw new Error('The supplied DisplayObject must be a child of the caller');
  12658. }
  12659. return index;
  12660. };
  12661. /**
  12662. * Changes the position of an existing child in the display object container
  12663. *
  12664. * @method setChildIndex
  12665. * @param child {DisplayObject} The child DisplayObject instance for which you want to change the index number
  12666. * @param index {Number} The resulting index number for the child display object
  12667. */
  12668. PIXI.DisplayObjectContainer.prototype.setChildIndex = function(child, index)
  12669. {
  12670. if (index < 0 || index >= this.children.length)
  12671. {
  12672. throw new Error('The supplied index is out of bounds');
  12673. }
  12674. var currentIndex = this.getChildIndex(child);
  12675. this.children.splice(currentIndex, 1); //remove from old position
  12676. this.children.splice(index, 0, child); //add at new position
  12677. };
  12678. /**
  12679. * Returns the child at the specified index
  12680. *
  12681. * @method getChildAt
  12682. * @param index {Number} The index to get the child from
  12683. * @return {DisplayObject} The child at the given index, if any.
  12684. */
  12685. PIXI.DisplayObjectContainer.prototype.getChildAt = function(index)
  12686. {
  12687. if (index < 0 || index >= this.children.length)
  12688. {
  12689. throw new Error('getChildAt: Supplied index '+ index +' does not exist in the child list, or the supplied DisplayObject must be a child of the caller');
  12690. }
  12691. return this.children[index];
  12692. };
  12693. /**
  12694. * Removes a child from the container.
  12695. *
  12696. * @method removeChild
  12697. * @param child {DisplayObject} The DisplayObject to remove
  12698. * @return {DisplayObject} The child that was removed.
  12699. */
  12700. PIXI.DisplayObjectContainer.prototype.removeChild = function(child)
  12701. {
  12702. var index = this.children.indexOf( child );
  12703. if(index === -1)return;
  12704. return this.removeChildAt( index );
  12705. };
  12706. /**
  12707. * Removes a child from the specified index position.
  12708. *
  12709. * @method removeChildAt
  12710. * @param index {Number} The index to get the child from
  12711. * @return {DisplayObject} The child that was removed.
  12712. */
  12713. PIXI.DisplayObjectContainer.prototype.removeChildAt = function(index)
  12714. {
  12715. var child = this.getChildAt( index );
  12716. if(this.stage)
  12717. child.removeStageReference();
  12718. child.parent = undefined;
  12719. this.children.splice( index, 1 );
  12720. return child;
  12721. };
  12722. /**
  12723. * Removes all children from this container that are within the begin and end indexes.
  12724. *
  12725. * @method removeChildren
  12726. * @param beginIndex {Number} The beginning position. Default value is 0.
  12727. * @param endIndex {Number} The ending position. Default value is size of the container.
  12728. */
  12729. PIXI.DisplayObjectContainer.prototype.removeChildren = function(beginIndex, endIndex)
  12730. {
  12731. var begin = beginIndex || 0;
  12732. var end = typeof endIndex === 'number' ? endIndex : this.children.length;
  12733. var range = end - begin;
  12734. if (range > 0 && range <= end)
  12735. {
  12736. var removed = this.children.splice(begin, range);
  12737. for (var i = 0; i < removed.length; i++) {
  12738. var child = removed[i];
  12739. if(this.stage)
  12740. child.removeStageReference();
  12741. child.parent = undefined;
  12742. }
  12743. return removed;
  12744. }
  12745. else if (range === 0 && this.children.length === 0)
  12746. {
  12747. return [];
  12748. }
  12749. else
  12750. {
  12751. throw new Error( 'removeChildren: Range Error, numeric values are outside the acceptable range' );
  12752. }
  12753. };
  12754. /*
  12755. * Updates the transform on all children of this container for rendering
  12756. *
  12757. * @method updateTransform
  12758. * @private
  12759. */
  12760. PIXI.DisplayObjectContainer.prototype.updateTransform = function()
  12761. {
  12762. if (!this.visible)
  12763. {
  12764. return;
  12765. }
  12766. this.displayObjectUpdateTransform();
  12767. if (this._cacheAsBitmap)
  12768. {
  12769. return;
  12770. }
  12771. for (var i = 0; i < this.children.length; i++)
  12772. {
  12773. this.children[i].updateTransform();
  12774. }
  12775. };
  12776. // performance increase to avoid using call.. (10x faster)
  12777. PIXI.DisplayObjectContainer.prototype.displayObjectContainerUpdateTransform = PIXI.DisplayObjectContainer.prototype.updateTransform;
  12778. /**
  12779. * Retrieves the bounds of the displayObjectContainer as a rectangle. The bounds calculation takes all visible children into consideration.
  12780. *
  12781. * @method getBounds
  12782. * @return {Rectangle} The rectangular bounding area
  12783. */
  12784. PIXI.DisplayObjectContainer.prototype.getBounds = function()
  12785. {
  12786. if (this.children.length === 0)
  12787. {
  12788. return PIXI.EmptyRectangle;
  12789. }
  12790. var minX = Infinity;
  12791. var minY = Infinity;
  12792. var maxX = -Infinity;
  12793. var maxY = -Infinity;
  12794. var childBounds;
  12795. var childMaxX;
  12796. var childMaxY;
  12797. var childVisible = false;
  12798. for (var i = 0; i < this.children.length; i++)
  12799. {
  12800. var child = this.children[i];
  12801. if (!child.visible)
  12802. {
  12803. continue;
  12804. }
  12805. childVisible = true;
  12806. childBounds = this.children[i].getBounds();
  12807. minX = minX < childBounds.x ? minX : childBounds.x;
  12808. minY = minY < childBounds.y ? minY : childBounds.y;
  12809. childMaxX = childBounds.width + childBounds.x;
  12810. childMaxY = childBounds.height + childBounds.y;
  12811. maxX = maxX > childMaxX ? maxX : childMaxX;
  12812. maxY = maxY > childMaxY ? maxY : childMaxY;
  12813. }
  12814. if (!childVisible)
  12815. {
  12816. return PIXI.EmptyRectangle;
  12817. }
  12818. var bounds = this._bounds;
  12819. bounds.x = minX;
  12820. bounds.y = minY;
  12821. bounds.width = maxX - minX;
  12822. bounds.height = maxY - minY;
  12823. return bounds;
  12824. };
  12825. /**
  12826. * Retrieves the non-global local bounds of the displayObjectContainer as a rectangle. The calculation takes all visible children into consideration.
  12827. *
  12828. * @method getLocalBounds
  12829. * @return {Rectangle} The rectangular bounding area
  12830. */
  12831. PIXI.DisplayObjectContainer.prototype.getLocalBounds = function()
  12832. {
  12833. var matrixCache = this.worldTransform;
  12834. this.worldTransform = PIXI.identityMatrix;
  12835. for (var i = 0; i < this.children.length; i++)
  12836. {
  12837. this.children[i].updateTransform();
  12838. }
  12839. var bounds = this.getBounds();
  12840. this.worldTransform = matrixCache;
  12841. for (i = 0; i < this.children.length; i++)
  12842. {
  12843. this.children[i].updateTransform();
  12844. }
  12845. return bounds;
  12846. };
  12847. /**
  12848. * Sets the containers Stage reference. This is the Stage that this object, and all of its children, is connected to.
  12849. *
  12850. * @method setStageReference
  12851. * @param stage {Stage} the stage that the container will have as its current stage reference
  12852. */
  12853. PIXI.DisplayObjectContainer.prototype.setStageReference = function(stage)
  12854. {
  12855. this.stage = stage;
  12856. for (var i=0; i < this.children.length; i++)
  12857. {
  12858. this.children[i].setStageReference(stage)
  12859. }
  12860. };
  12861. /**
  12862. * Removes the current stage reference from the container and all of its children.
  12863. *
  12864. * @method removeStageReference
  12865. */
  12866. PIXI.DisplayObjectContainer.prototype.removeStageReference = function()
  12867. {
  12868. for (var i = 0; i < this.children.length; i++)
  12869. {
  12870. this.children[i].removeStageReference();
  12871. }
  12872. this.stage = null;
  12873. };
  12874. /**
  12875. * Renders the object using the WebGL renderer
  12876. *
  12877. * @method _renderWebGL
  12878. * @param renderSession {RenderSession}
  12879. * @private
  12880. */
  12881. PIXI.DisplayObjectContainer.prototype._renderWebGL = function(renderSession)
  12882. {
  12883. if (!this.visible || this.alpha <= 0) return;
  12884. if (this._cacheAsBitmap)
  12885. {
  12886. this._renderCachedSprite(renderSession);
  12887. return;
  12888. }
  12889. var i;
  12890. if (this._mask || this._filters)
  12891. {
  12892. // push filter first as we need to ensure the stencil buffer is correct for any masking
  12893. if (this._filters)
  12894. {
  12895. renderSession.spriteBatch.flush();
  12896. renderSession.filterManager.pushFilter(this._filterBlock);
  12897. }
  12898. if (this._mask)
  12899. {
  12900. renderSession.spriteBatch.stop();
  12901. renderSession.maskManager.pushMask(this.mask, renderSession);
  12902. renderSession.spriteBatch.start();
  12903. }
  12904. // simple render children!
  12905. for (i = 0; i < this.children.length; i++)
  12906. {
  12907. this.children[i]._renderWebGL(renderSession);
  12908. }
  12909. renderSession.spriteBatch.stop();
  12910. if (this._mask) renderSession.maskManager.popMask(this._mask, renderSession);
  12911. if (this._filters) renderSession.filterManager.popFilter();
  12912. renderSession.spriteBatch.start();
  12913. }
  12914. else
  12915. {
  12916. // simple render children!
  12917. for (i = 0; i < this.children.length; i++)
  12918. {
  12919. this.children[i]._renderWebGL(renderSession);
  12920. }
  12921. }
  12922. };
  12923. /**
  12924. * Renders the object using the Canvas renderer
  12925. *
  12926. * @method _renderCanvas
  12927. * @param renderSession {RenderSession}
  12928. * @private
  12929. */
  12930. PIXI.DisplayObjectContainer.prototype._renderCanvas = function(renderSession)
  12931. {
  12932. if (this.visible === false || this.alpha === 0) return;
  12933. if (this._cacheAsBitmap)
  12934. {
  12935. this._renderCachedSprite(renderSession);
  12936. return;
  12937. }
  12938. if (this._mask)
  12939. {
  12940. renderSession.maskManager.pushMask(this._mask, renderSession);
  12941. }
  12942. for (var i = 0; i < this.children.length; i++)
  12943. {
  12944. this.children[i]._renderCanvas(renderSession);
  12945. }
  12946. if (this._mask)
  12947. {
  12948. renderSession.maskManager.popMask(renderSession);
  12949. }
  12950. };
  12951. /**
  12952. * @author Mat Groves http://matgroves.com/ @Doormat23
  12953. */
  12954. /**
  12955. * The Sprite object is the base for all textured objects that are rendered to the screen
  12956. *
  12957. * @class Sprite
  12958. * @extends DisplayObjectContainer
  12959. * @constructor
  12960. * @param texture {Texture} The texture for this sprite
  12961. *
  12962. * A sprite can be created directly from an image like this :
  12963. * var sprite = new PIXI.Sprite.fromImage('assets/image.png');
  12964. * yourStage.addChild(sprite);
  12965. * then obviously don't forget to add it to the stage you have already created
  12966. */
  12967. PIXI.Sprite = function(texture)
  12968. {
  12969. PIXI.DisplayObjectContainer.call(this);
  12970. /**
  12971. * The anchor sets the origin point of the texture.
  12972. * The default is 0,0 this means the texture's origin is the top left
  12973. * Setting than anchor to 0.5,0.5 means the textures origin is centered
  12974. * Setting the anchor to 1,1 would mean the textures origin points will be the bottom right corner
  12975. *
  12976. * @property anchor
  12977. * @type Point
  12978. */
  12979. this.anchor = new PIXI.Point();
  12980. /**
  12981. * The texture that the sprite is using
  12982. *
  12983. * @property texture
  12984. * @type Texture
  12985. */
  12986. this.texture = texture || PIXI.Texture.emptyTexture;
  12987. /**
  12988. * The width of the sprite (this is initially set by the texture)
  12989. *
  12990. * @property _width
  12991. * @type Number
  12992. * @private
  12993. */
  12994. this._width = 0;
  12995. /**
  12996. * The height of the sprite (this is initially set by the texture)
  12997. *
  12998. * @property _height
  12999. * @type Number
  13000. * @private
  13001. */
  13002. this._height = 0;
  13003. /**
  13004. * The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect.
  13005. *
  13006. * @property tint
  13007. * @type Number
  13008. * @default 0xFFFFFF
  13009. */
  13010. this.tint = 0xFFFFFF;
  13011. /**
  13012. * The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect.
  13013. *
  13014. * @property cachedTint
  13015. * @private
  13016. * @type Number
  13017. * @default -1
  13018. */
  13019. this.cachedTint = -1;
  13020. /**
  13021. * A canvas that contains the tinted version of the Sprite (in Canvas mode, WebGL doesn't populate this)
  13022. *
  13023. * @property tintedTexture
  13024. * @type Canvas
  13025. * @default null
  13026. */
  13027. this.tintedTexture = null;
  13028. /**
  13029. * The blend mode to be applied to the sprite. Set to PIXI.blendModes.NORMAL to remove any blend mode.
  13030. *
  13031. * Warning: You cannot have a blend mode and a filter active on the same Sprite. Doing so will render the sprite invisible.
  13032. *
  13033. * @property blendMode
  13034. * @type Number
  13035. * @default PIXI.blendModes.NORMAL;
  13036. */
  13037. this.blendMode = PIXI.blendModes.NORMAL;
  13038. /**
  13039. * The shader that will be used to render the texture to the stage. Set to null to remove a current shader.
  13040. *
  13041. * @property shader
  13042. * @type AbstractFilter
  13043. * @default null
  13044. */
  13045. this.shader = null;
  13046. if (this.texture.baseTexture.hasLoaded)
  13047. {
  13048. this.onTextureUpdate();
  13049. }
  13050. this.renderable = true;
  13051. };
  13052. // constructor
  13053. PIXI.Sprite.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
  13054. PIXI.Sprite.prototype.constructor = PIXI.Sprite;
  13055. /**
  13056. * The width of the sprite, setting this will actually modify the scale to achieve the value set
  13057. *
  13058. * @property width
  13059. * @type Number
  13060. */
  13061. Object.defineProperty(PIXI.Sprite.prototype, 'width', {
  13062. get: function() {
  13063. return this.scale.x * this.texture.frame.width;
  13064. },
  13065. set: function(value) {
  13066. this.scale.x = value / this.texture.frame.width;
  13067. this._width = value;
  13068. }
  13069. });
  13070. /**
  13071. * The height of the sprite, setting this will actually modify the scale to achieve the value set
  13072. *
  13073. * @property height
  13074. * @type Number
  13075. */
  13076. Object.defineProperty(PIXI.Sprite.prototype, 'height', {
  13077. get: function() {
  13078. return this.scale.y * this.texture.frame.height;
  13079. },
  13080. set: function(value) {
  13081. this.scale.y = value / this.texture.frame.height;
  13082. this._height = value;
  13083. }
  13084. });
  13085. /**
  13086. * Sets the texture of the sprite. Be warned that this doesn't remove or destroy the previous
  13087. * texture this Sprite was using.
  13088. *
  13089. * @method setTexture
  13090. * @param texture {Texture} The PIXI texture that is displayed by the sprite
  13091. * @param [destroy=false] {boolean} Call Texture.destroy on the current texture before replacing it with the new one?
  13092. */
  13093. PIXI.Sprite.prototype.setTexture = function(texture, destroyBase)
  13094. {
  13095. if (destroyBase !== undefined)
  13096. {
  13097. this.texture.baseTexture.destroy();
  13098. }
  13099. // Over-ridden by loadTexture as needed
  13100. this.texture.baseTexture.skipRender = false;
  13101. this.texture = texture;
  13102. this.texture.valid = true;
  13103. this.cachedTint = -1;
  13104. };
  13105. /**
  13106. * When the texture is updated, this event will fire to update the scale and frame
  13107. *
  13108. * @method onTextureUpdate
  13109. * @param event
  13110. * @private
  13111. */
  13112. PIXI.Sprite.prototype.onTextureUpdate = function()
  13113. {
  13114. // so if _width is 0 then width was not set..
  13115. if (this._width) this.scale.x = this._width / this.texture.frame.width;
  13116. if (this._height) this.scale.y = this._height / this.texture.frame.height;
  13117. };
  13118. /**
  13119. * Returns the bounds of the Sprite as a rectangle.
  13120. * The bounds calculation takes the worldTransform into account.
  13121. *
  13122. * It is important to note that the transform is not updated when you call this method.
  13123. * So if this Sprite is the child of a Display Object which has had its transform
  13124. * updated since the last render pass, those changes will not yet have been applied
  13125. * to this Sprites worldTransform. If you need to ensure that all parent transforms
  13126. * are factored into this getBounds operation then you should call `updateTransform`
  13127. * on the root most object in this Sprites display list first.
  13128. *
  13129. * @method getBounds
  13130. * @param matrix {Matrix} the transformation matrix of the sprite
  13131. * @return {Rectangle} the framing rectangle
  13132. */
  13133. PIXI.Sprite.prototype.getBounds = function(matrix)
  13134. {
  13135. var width = this.texture.frame.width;
  13136. var height = this.texture.frame.height;
  13137. var w0 = width * (1-this.anchor.x);
  13138. var w1 = width * -this.anchor.x;
  13139. var h0 = height * (1-this.anchor.y);
  13140. var h1 = height * -this.anchor.y;
  13141. var worldTransform = matrix || this.worldTransform;
  13142. var a = worldTransform.a;
  13143. var b = worldTransform.b;
  13144. var c = worldTransform.c;
  13145. var d = worldTransform.d;
  13146. var tx = worldTransform.tx;
  13147. var ty = worldTransform.ty;
  13148. var maxX = -Infinity;
  13149. var maxY = -Infinity;
  13150. var minX = Infinity;
  13151. var minY = Infinity;
  13152. if (b === 0 && c === 0)
  13153. {
  13154. // scale may be negative!
  13155. if (a < 0)
  13156. {
  13157. a *= -1;
  13158. var temp = w0;
  13159. w0 = -w1;
  13160. w1 = -temp;
  13161. }
  13162. if (d < 0)
  13163. {
  13164. d *= -1;
  13165. var temp = h0;
  13166. h0 = -h1;
  13167. h1 = -temp;
  13168. }
  13169. // this means there is no rotation going on right? RIGHT?
  13170. // if thats the case then we can avoid checking the bound values! yay
  13171. minX = a * w1 + tx;
  13172. maxX = a * w0 + tx;
  13173. minY = d * h1 + ty;
  13174. maxY = d * h0 + ty;
  13175. }
  13176. else
  13177. {
  13178. var x1 = a * w1 + c * h1 + tx;
  13179. var y1 = d * h1 + b * w1 + ty;
  13180. var x2 = a * w0 + c * h1 + tx;
  13181. var y2 = d * h1 + b * w0 + ty;
  13182. var x3 = a * w0 + c * h0 + tx;
  13183. var y3 = d * h0 + b * w0 + ty;
  13184. var x4 = a * w1 + c * h0 + tx;
  13185. var y4 = d * h0 + b * w1 + ty;
  13186. minX = x1 < minX ? x1 : minX;
  13187. minX = x2 < minX ? x2 : minX;
  13188. minX = x3 < minX ? x3 : minX;
  13189. minX = x4 < minX ? x4 : minX;
  13190. minY = y1 < minY ? y1 : minY;
  13191. minY = y2 < minY ? y2 : minY;
  13192. minY = y3 < minY ? y3 : minY;
  13193. minY = y4 < minY ? y4 : minY;
  13194. maxX = x1 > maxX ? x1 : maxX;
  13195. maxX = x2 > maxX ? x2 : maxX;
  13196. maxX = x3 > maxX ? x3 : maxX;
  13197. maxX = x4 > maxX ? x4 : maxX;
  13198. maxY = y1 > maxY ? y1 : maxY;
  13199. maxY = y2 > maxY ? y2 : maxY;
  13200. maxY = y3 > maxY ? y3 : maxY;
  13201. maxY = y4 > maxY ? y4 : maxY;
  13202. }
  13203. var bounds = this._bounds;
  13204. bounds.x = minX;
  13205. bounds.width = maxX - minX;
  13206. bounds.y = minY;
  13207. bounds.height = maxY - minY;
  13208. // store a reference so that if this function gets called again in the render cycle we do not have to recalculate
  13209. this._currentBounds = bounds;
  13210. return bounds;
  13211. };
  13212. /**
  13213. * Renders the object using the WebGL renderer
  13214. *
  13215. * @method _renderWebGL
  13216. * @param renderSession {RenderSession}
  13217. * @param {Matrix} [matrix] - Optional matrix. If provided the Display Object will be rendered using this matrix, otherwise it will use its worldTransform.
  13218. * @private
  13219. */
  13220. PIXI.Sprite.prototype._renderWebGL = function(renderSession, matrix)
  13221. {
  13222. // if the sprite is not visible or the alpha is 0 then no need to render this element
  13223. if (!this.visible || this.alpha <= 0 || !this.renderable) return;
  13224. // They provided an alternative rendering matrix, so use it
  13225. var wt = this.worldTransform;
  13226. if (matrix)
  13227. {
  13228. wt = matrix;
  13229. }
  13230. // A quick check to see if this element has a mask or a filter.
  13231. if (this._mask || this._filters)
  13232. {
  13233. var spriteBatch = renderSession.spriteBatch;
  13234. // push filter first as we need to ensure the stencil buffer is correct for any masking
  13235. if (this._filters)
  13236. {
  13237. spriteBatch.flush();
  13238. renderSession.filterManager.pushFilter(this._filterBlock);
  13239. }
  13240. if (this._mask)
  13241. {
  13242. spriteBatch.stop();
  13243. renderSession.maskManager.pushMask(this.mask, renderSession);
  13244. spriteBatch.start();
  13245. }
  13246. // add this sprite to the batch
  13247. spriteBatch.render(this);
  13248. // now loop through the children and make sure they get rendered
  13249. for (var i = 0; i < this.children.length; i++)
  13250. {
  13251. this.children[i]._renderWebGL(renderSession);
  13252. }
  13253. // time to stop the sprite batch as either a mask element or a filter draw will happen next
  13254. spriteBatch.stop();
  13255. if (this._mask) renderSession.maskManager.popMask(this._mask, renderSession);
  13256. if (this._filters) renderSession.filterManager.popFilter();
  13257. spriteBatch.start();
  13258. }
  13259. else
  13260. {
  13261. renderSession.spriteBatch.render(this);
  13262. // Render children!
  13263. for (var i = 0; i < this.children.length; i++)
  13264. {
  13265. this.children[i]._renderWebGL(renderSession, wt);
  13266. }
  13267. }
  13268. };
  13269. /**
  13270. * Renders the object using the Canvas renderer
  13271. *
  13272. * @method _renderCanvas
  13273. * @param renderSession {RenderSession}
  13274. * @param {Matrix} [matrix] - Optional matrix. If provided the Display Object will be rendered using this matrix, otherwise it will use its worldTransform.
  13275. * @private
  13276. */
  13277. PIXI.Sprite.prototype._renderCanvas = function(renderSession, matrix)
  13278. {
  13279. // If the sprite is not visible or the alpha is 0 then no need to render this element
  13280. if (!this.visible || this.alpha === 0 || !this.renderable || this.texture.crop.width <= 0 || this.texture.crop.height <= 0)
  13281. {
  13282. return;
  13283. }
  13284. var wt = this.worldTransform;
  13285. // If they provided an alternative rendering matrix then use it
  13286. if (matrix)
  13287. {
  13288. wt = matrix;
  13289. }
  13290. if (this.blendMode !== renderSession.currentBlendMode)
  13291. {
  13292. renderSession.currentBlendMode = this.blendMode;
  13293. renderSession.context.globalCompositeOperation = PIXI.blendModesCanvas[renderSession.currentBlendMode];
  13294. }
  13295. if (this._mask)
  13296. {
  13297. renderSession.maskManager.pushMask(this._mask, renderSession);
  13298. }
  13299. // Ignore null sources
  13300. if (this.texture.valid)
  13301. {
  13302. var resolution = this.texture.baseTexture.resolution / renderSession.resolution;
  13303. renderSession.context.globalAlpha = this.worldAlpha;
  13304. // If smoothingEnabled is supported and we need to change the smoothing property for this texture
  13305. if (renderSession.smoothProperty && renderSession.scaleMode !== this.texture.baseTexture.scaleMode)
  13306. {
  13307. renderSession.scaleMode = this.texture.baseTexture.scaleMode;
  13308. renderSession.context[renderSession.smoothProperty] = (renderSession.scaleMode === PIXI.scaleModes.LINEAR);
  13309. }
  13310. // If the texture is trimmed we offset by the trim x/y, otherwise we use the frame dimensions
  13311. var dx = (this.texture.trim) ? this.texture.trim.x - this.anchor.x * this.texture.trim.width : this.anchor.x * -this.texture.frame.width;
  13312. var dy = (this.texture.trim) ? this.texture.trim.y - this.anchor.y * this.texture.trim.height : this.anchor.y * -this.texture.frame.height;
  13313. var tx = (wt.tx * renderSession.resolution) + renderSession.shakeX;
  13314. var ty = (wt.ty * renderSession.resolution) + renderSession.shakeY;
  13315. // Allow for pixel rounding
  13316. if (renderSession.roundPixels)
  13317. {
  13318. renderSession.context.setTransform(wt.a, wt.b, wt.c, wt.d, tx | 0, ty | 0);
  13319. dx |= 0;
  13320. dy |= 0;
  13321. }
  13322. else
  13323. {
  13324. renderSession.context.setTransform(wt.a, wt.b, wt.c, wt.d, tx, ty);
  13325. }
  13326. var cw = this.texture.crop.width;
  13327. var ch = this.texture.crop.height;
  13328. dx /= resolution;
  13329. dy /= resolution;
  13330. if (this.tint !== 0xFFFFFF)
  13331. {
  13332. if (this.texture.requiresReTint || this.cachedTint !== this.tint)
  13333. {
  13334. this.tintedTexture = PIXI.CanvasTinter.getTintedTexture(this, this.tint);
  13335. this.cachedTint = this.tint;
  13336. }
  13337. renderSession.context.drawImage(this.tintedTexture, 0, 0, cw, ch, dx, dy, cw / resolution, ch / resolution);
  13338. }
  13339. else
  13340. {
  13341. var cx = this.texture.crop.x;
  13342. var cy = this.texture.crop.y;
  13343. renderSession.context.drawImage(this.texture.baseTexture.source, cx, cy, cw, ch, dx, dy, cw / resolution, ch / resolution);
  13344. }
  13345. }
  13346. for (var i = 0; i < this.children.length; i++)
  13347. {
  13348. this.children[i]._renderCanvas(renderSession);
  13349. }
  13350. if (this._mask)
  13351. {
  13352. renderSession.maskManager.popMask(renderSession);
  13353. }
  13354. };
  13355. // some helper functions..
  13356. /**
  13357. *
  13358. * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId
  13359. * The frame ids are created when a Texture packer file has been loaded
  13360. *
  13361. * @method fromFrame
  13362. * @static
  13363. * @param frameId {String} The frame Id of the texture in the cache
  13364. * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId
  13365. */
  13366. PIXI.Sprite.fromFrame = function(frameId)
  13367. {
  13368. var texture = PIXI.TextureCache[frameId];
  13369. if (!texture) throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this);
  13370. return new PIXI.Sprite(texture);
  13371. };
  13372. /**
  13373. *
  13374. * Helper function that creates a sprite that will contain a texture based on an image url
  13375. * If the image is not in the texture cache it will be loaded
  13376. *
  13377. * @method fromImage
  13378. * @static
  13379. * @param imageId {String} The image url of the texture
  13380. * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id
  13381. */
  13382. PIXI.Sprite.fromImage = function(imageId, crossorigin, scaleMode)
  13383. {
  13384. var texture = PIXI.Texture.fromImage(imageId, crossorigin, scaleMode);
  13385. return new PIXI.Sprite(texture);
  13386. };
  13387. /**
  13388. * @author Mat Groves http://matgroves.com/
  13389. */
  13390. /**
  13391. * The SpriteBatch class is a really fast version of the DisplayObjectContainer
  13392. * built solely for speed, so use when you need a lot of sprites or particles.
  13393. * And it's extremely easy to use :
  13394. var container = new PIXI.SpriteBatch();
  13395. stage.addChild(container);
  13396. for(var i = 0; i < 100; i++)
  13397. {
  13398. var sprite = new PIXI.Sprite.fromImage("myImage.png");
  13399. container.addChild(sprite);
  13400. }
  13401. * And here you have a hundred sprites that will be renderer at the speed of light
  13402. *
  13403. * @class SpriteBatch
  13404. * @constructor
  13405. * @param texture {Texture}
  13406. */
  13407. PIXI.SpriteBatch = function(texture)
  13408. {
  13409. PIXI.DisplayObjectContainer.call( this);
  13410. this.textureThing = texture;
  13411. this.ready = false;
  13412. };
  13413. PIXI.SpriteBatch.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
  13414. PIXI.SpriteBatch.prototype.constructor = PIXI.SpriteBatch;
  13415. /*
  13416. * Initialises the spriteBatch
  13417. *
  13418. * @method initWebGL
  13419. * @param gl {WebGLContext} the current WebGL drawing context
  13420. */
  13421. PIXI.SpriteBatch.prototype.initWebGL = function(gl)
  13422. {
  13423. // TODO only one needed for the whole engine really?
  13424. this.fastSpriteBatch = new PIXI.WebGLFastSpriteBatch(gl);
  13425. this.ready = true;
  13426. };
  13427. /*
  13428. * Updates the object transform for rendering
  13429. *
  13430. * @method updateTransform
  13431. * @private
  13432. */
  13433. PIXI.SpriteBatch.prototype.updateTransform = function()
  13434. {
  13435. // TODO don't need to!
  13436. this.displayObjectUpdateTransform();
  13437. // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this );
  13438. };
  13439. /**
  13440. * Renders the object using the WebGL renderer
  13441. *
  13442. * @method _renderWebGL
  13443. * @param renderSession {RenderSession}
  13444. * @private
  13445. */
  13446. PIXI.SpriteBatch.prototype._renderWebGL = function(renderSession)
  13447. {
  13448. if (!this.visible || this.alpha <= 0 || !this.children.length) return;
  13449. if (!this.ready)
  13450. {
  13451. this.initWebGL(renderSession.gl);
  13452. }
  13453. if (this.fastSpriteBatch.gl !== renderSession.gl)
  13454. {
  13455. this.fastSpriteBatch.setContext(renderSession.gl);
  13456. }
  13457. renderSession.spriteBatch.stop();
  13458. renderSession.shaderManager.setShader(renderSession.shaderManager.fastShader);
  13459. this.fastSpriteBatch.begin(this, renderSession);
  13460. this.fastSpriteBatch.render(this);
  13461. renderSession.spriteBatch.start();
  13462. };
  13463. /**
  13464. * Renders the object using the Canvas renderer
  13465. *
  13466. * @method _renderCanvas
  13467. * @param renderSession {RenderSession}
  13468. * @private
  13469. */
  13470. PIXI.SpriteBatch.prototype._renderCanvas = function(renderSession)
  13471. {
  13472. if (!this.visible || this.alpha <= 0 || !this.children.length) return;
  13473. var context = renderSession.context;
  13474. context.globalAlpha = this.worldAlpha;
  13475. this.displayObjectUpdateTransform();
  13476. var transform = this.worldTransform;
  13477. var isRotated = true;
  13478. for (var i = 0; i < this.children.length; i++)
  13479. {
  13480. var child = this.children[i];
  13481. if (!child.visible) continue;
  13482. var texture = child.texture;
  13483. var frame = texture.frame;
  13484. context.globalAlpha = this.worldAlpha * child.alpha;
  13485. if (child.rotation % (Math.PI * 2) === 0)
  13486. {
  13487. if (isRotated)
  13488. {
  13489. context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty);
  13490. isRotated = false;
  13491. }
  13492. // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call
  13493. context.drawImage(texture.baseTexture.source,
  13494. frame.x,
  13495. frame.y,
  13496. frame.width,
  13497. frame.height,
  13498. ((child.anchor.x) * (-frame.width * child.scale.x) + child.position.x + 0.5 + renderSession.shakeX) | 0,
  13499. ((child.anchor.y) * (-frame.height * child.scale.y) + child.position.y + 0.5 + renderSession.shakeY) | 0,
  13500. frame.width * child.scale.x,
  13501. frame.height * child.scale.y);
  13502. }
  13503. else
  13504. {
  13505. if (!isRotated) isRotated = true;
  13506. child.displayObjectUpdateTransform();
  13507. var childTransform = child.worldTransform;
  13508. var tx = (childTransform.tx * renderSession.resolution) + renderSession.shakeX;
  13509. var ty = (childTransform.ty * renderSession.resolution) + renderSession.shakeY;
  13510. // allow for trimming
  13511. if (renderSession.roundPixels)
  13512. {
  13513. context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, tx | 0, ty | 0);
  13514. }
  13515. else
  13516. {
  13517. context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, tx, ty);
  13518. }
  13519. context.drawImage(texture.baseTexture.source,
  13520. frame.x,
  13521. frame.y,
  13522. frame.width,
  13523. frame.height,
  13524. ((child.anchor.x) * (-frame.width) + 0.5) | 0,
  13525. ((child.anchor.y) * (-frame.height) + 0.5) | 0,
  13526. frame.width,
  13527. frame.height);
  13528. }
  13529. }
  13530. };
  13531. /**
  13532. * @author Mat Groves http://matgroves.com/ @Doormat23
  13533. */
  13534. /**
  13535. * Converts a hex color number to an [R, G, B] array
  13536. *
  13537. * @method hex2rgb
  13538. * @param hex {Number}
  13539. */
  13540. PIXI.hex2rgb = function(hex) {
  13541. return [(hex >> 16 & 0xFF) / 255, ( hex >> 8 & 0xFF) / 255, (hex & 0xFF)/ 255];
  13542. };
  13543. /**
  13544. * Converts a color as an [R, G, B] array to a hex number
  13545. *
  13546. * @method rgb2hex
  13547. * @param rgb {Array}
  13548. */
  13549. PIXI.rgb2hex = function(rgb) {
  13550. return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255);
  13551. };
  13552. /**
  13553. * Checks whether the Canvas BlendModes are supported by the current browser for drawImage
  13554. *
  13555. * @method canUseNewCanvasBlendModes
  13556. * @return {Boolean} whether they are supported
  13557. */
  13558. PIXI.canUseNewCanvasBlendModes = function()
  13559. {
  13560. if (document === undefined) return false;
  13561. var pngHead = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAABAQMAAADD8p2OAAAAA1BMVEX/';
  13562. var pngEnd = 'AAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJggg==';
  13563. var magenta = new Image();
  13564. magenta.src = pngHead + 'AP804Oa6' + pngEnd;
  13565. var yellow = new Image();
  13566. yellow.src = pngHead + '/wCKxvRF' + pngEnd;
  13567. var canvas = PIXI.CanvasPool.create(this, 6, 1);
  13568. var context = canvas.getContext('2d');
  13569. context.globalCompositeOperation = 'multiply';
  13570. context.drawImage(magenta, 0, 0);
  13571. context.drawImage(yellow, 2, 0);
  13572. if (!context.getImageData(2,0,1,1))
  13573. {
  13574. return false;
  13575. }
  13576. var data = context.getImageData(2,0,1,1).data;
  13577. PIXI.CanvasPool.remove(this);
  13578. return (data[0] === 255 && data[1] === 0 && data[2] === 0);
  13579. };
  13580. /**
  13581. * Given a number, this function returns the closest number that is a power of two
  13582. * this function is taken from Starling Framework as its pretty neat ;)
  13583. *
  13584. * @method getNextPowerOfTwo
  13585. * @param number {Number}
  13586. * @return {Number} the closest number that is a power of two
  13587. */
  13588. PIXI.getNextPowerOfTwo = function(number)
  13589. {
  13590. if (number > 0 && (number & (number - 1)) === 0) // see: http://goo.gl/D9kPj
  13591. return number;
  13592. else
  13593. {
  13594. var result = 1;
  13595. while (result < number) result <<= 1;
  13596. return result;
  13597. }
  13598. };
  13599. /**
  13600. * checks if the given width and height make a power of two texture
  13601. * @method isPowerOfTwo
  13602. * @param width {Number}
  13603. * @param height {Number}
  13604. * @return {Boolean}
  13605. */
  13606. PIXI.isPowerOfTwo = function(width, height)
  13607. {
  13608. return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0);
  13609. };
  13610. /**
  13611. * @author Richard Davey <rich@photonstorm.com>
  13612. * @copyright 2016 Photon Storm Ltd.
  13613. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  13614. */
  13615. /**
  13616. * The CanvasPool is a global static object that allows Pixi and Phaser to pool canvas DOM elements.
  13617. *
  13618. * @class CanvasPool
  13619. * @static
  13620. */
  13621. PIXI.CanvasPool = {
  13622. /**
  13623. * Creates a new Canvas DOM element, or pulls one from the pool if free.
  13624. *
  13625. * @method create
  13626. * @static
  13627. * @param parent {any} The parent of the canvas element.
  13628. * @param width {number} The width of the canvas element.
  13629. * @param height {number} The height of the canvas element.
  13630. * @return {HTMLCanvasElement} The canvas element.
  13631. */
  13632. create: function (parent, width, height) {
  13633. var idx = PIXI.CanvasPool.getFirst();
  13634. var canvas;
  13635. if (idx === -1)
  13636. {
  13637. var container = {
  13638. parent: parent,
  13639. canvas: document.createElement('canvas')
  13640. }
  13641. PIXI.CanvasPool.pool.push(container);
  13642. canvas = container.canvas;
  13643. }
  13644. else
  13645. {
  13646. PIXI.CanvasPool.pool[idx].parent = parent;
  13647. canvas = PIXI.CanvasPool.pool[idx].canvas;
  13648. }
  13649. if (width !== undefined)
  13650. {
  13651. canvas.width = width;
  13652. canvas.height = height;
  13653. }
  13654. return canvas;
  13655. },
  13656. /**
  13657. * Gets the first free canvas index from the pool.
  13658. *
  13659. * @method getFirst
  13660. * @static
  13661. * @return {number}
  13662. */
  13663. getFirst: function () {
  13664. var pool = PIXI.CanvasPool.pool;
  13665. for (var i = 0; i < pool.length; i++)
  13666. {
  13667. if (pool[i].parent === null)
  13668. {
  13669. return i;
  13670. }
  13671. }
  13672. return -1;
  13673. },
  13674. /**
  13675. * Removes the parent from a canvas element from the pool, freeing it up for re-use.
  13676. *
  13677. * @method remove
  13678. * @param parent {any} The parent of the canvas element.
  13679. * @static
  13680. */
  13681. remove: function (parent) {
  13682. var pool = PIXI.CanvasPool.pool;
  13683. for (var i = 0; i < pool.length; i++)
  13684. {
  13685. if (pool[i].parent === parent)
  13686. {
  13687. pool[i].parent = null;
  13688. }
  13689. }
  13690. },
  13691. /**
  13692. * Removes the parent from a canvas element from the pool, freeing it up for re-use.
  13693. *
  13694. * @method removeByCanvas
  13695. * @param canvas {HTMLCanvasElement} The canvas element to remove
  13696. * @static
  13697. */
  13698. removeByCanvas: function (canvas) {
  13699. var pool = PIXI.CanvasPool.pool;
  13700. for (var i = 0; i < pool.length; i++)
  13701. {
  13702. if (pool[i].canvas === canvas)
  13703. {
  13704. pool[i].parent = null;
  13705. }
  13706. }
  13707. },
  13708. /**
  13709. * Gets the total number of used canvas elements in the pool.
  13710. *
  13711. * @method getTotal
  13712. * @static
  13713. * @return {number} The number of in-use (parented) canvas elements in the pool.
  13714. */
  13715. getTotal: function () {
  13716. var pool = PIXI.CanvasPool.pool;
  13717. var c = 0;
  13718. for (var i = 0; i < pool.length; i++)
  13719. {
  13720. if (pool[i].parent !== null)
  13721. {
  13722. c++;
  13723. }
  13724. }
  13725. return c;
  13726. },
  13727. /**
  13728. * Gets the total number of free canvas elements in the pool.
  13729. *
  13730. * @method getFree
  13731. * @static
  13732. * @return {number} The number of free (un-parented) canvas elements in the pool.
  13733. */
  13734. getFree: function () {
  13735. var pool = PIXI.CanvasPool.pool;
  13736. var c = 0;
  13737. for (var i = 0; i < pool.length; i++)
  13738. {
  13739. if (pool[i].parent === null)
  13740. {
  13741. c++;
  13742. }
  13743. }
  13744. return c;
  13745. }
  13746. };
  13747. /**
  13748. * The pool into which the canvas dom elements are placed.
  13749. *
  13750. * @property pool
  13751. * @type Array
  13752. * @static
  13753. */
  13754. PIXI.CanvasPool.pool = [];
  13755. /**
  13756. * @author Mat Groves http://matgroves.com/ @Doormat23
  13757. */
  13758. /**
  13759. * @method initDefaultShaders
  13760. * @static
  13761. * @private
  13762. */
  13763. PIXI.initDefaultShaders = function()
  13764. {
  13765. };
  13766. /**
  13767. * @method CompileVertexShader
  13768. * @static
  13769. * @param gl {WebGLContext} the current WebGL drawing context
  13770. * @param shaderSrc {Array}
  13771. * @return {Any}
  13772. */
  13773. PIXI.CompileVertexShader = function(gl, shaderSrc)
  13774. {
  13775. return PIXI._CompileShader(gl, shaderSrc, gl.VERTEX_SHADER);
  13776. };
  13777. /**
  13778. * @method CompileFragmentShader
  13779. * @static
  13780. * @param gl {WebGLContext} the current WebGL drawing context
  13781. * @param shaderSrc {Array}
  13782. * @return {Any}
  13783. */
  13784. PIXI.CompileFragmentShader = function(gl, shaderSrc)
  13785. {
  13786. return PIXI._CompileShader(gl, shaderSrc, gl.FRAGMENT_SHADER);
  13787. };
  13788. /**
  13789. * @method _CompileShader
  13790. * @static
  13791. * @private
  13792. * @param gl {WebGLContext} the current WebGL drawing context
  13793. * @param shaderSrc {Array}
  13794. * @param shaderType {Number}
  13795. * @return {Any}
  13796. */
  13797. PIXI._CompileShader = function(gl, shaderSrc, shaderType)
  13798. {
  13799. var src = shaderSrc;
  13800. if (Array.isArray(shaderSrc))
  13801. {
  13802. src = shaderSrc.join("\n");
  13803. }
  13804. var shader = gl.createShader(shaderType);
  13805. gl.shaderSource(shader, src);
  13806. gl.compileShader(shader);
  13807. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS))
  13808. {
  13809. window.console.log(gl.getShaderInfoLog(shader));
  13810. return null;
  13811. }
  13812. return shader;
  13813. };
  13814. /**
  13815. * @method compileProgram
  13816. * @static
  13817. * @param gl {WebGLContext} the current WebGL drawing context
  13818. * @param vertexSrc {Array}
  13819. * @param fragmentSrc {Array}
  13820. * @return {Any}
  13821. */
  13822. PIXI.compileProgram = function(gl, vertexSrc, fragmentSrc)
  13823. {
  13824. var fragmentShader = PIXI.CompileFragmentShader(gl, fragmentSrc);
  13825. var vertexShader = PIXI.CompileVertexShader(gl, vertexSrc);
  13826. var shaderProgram = gl.createProgram();
  13827. gl.attachShader(shaderProgram, vertexShader);
  13828. gl.attachShader(shaderProgram, fragmentShader);
  13829. gl.linkProgram(shaderProgram);
  13830. if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS))
  13831. {
  13832. window.console.log("Could not initialise shaders");
  13833. }
  13834. return shaderProgram;
  13835. };
  13836. /**
  13837. * @author Mat Groves http://matgroves.com/ @Doormat23
  13838. * @author Richard Davey http://www.photonstorm.com @photonstorm
  13839. */
  13840. /**
  13841. * @class PixiShader
  13842. * @constructor
  13843. * @param gl {WebGLContext} the current WebGL drawing context
  13844. */
  13845. PIXI.PixiShader = function(gl)
  13846. {
  13847. /**
  13848. * @property _UID
  13849. * @type Number
  13850. * @private
  13851. */
  13852. this._UID = PIXI._UID++;
  13853. /**
  13854. * @property gl
  13855. * @type WebGLContext
  13856. */
  13857. this.gl = gl;
  13858. /**
  13859. * The WebGL program.
  13860. * @property program
  13861. * @type Any
  13862. */
  13863. this.program = null;
  13864. /**
  13865. * The fragment shader.
  13866. * @property fragmentSrc
  13867. * @type Array
  13868. */
  13869. this.fragmentSrc = [
  13870. 'precision lowp float;',
  13871. 'varying vec2 vTextureCoord;',
  13872. 'varying vec4 vColor;',
  13873. 'uniform sampler2D uSampler;',
  13874. 'void main(void) {',
  13875. ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;',
  13876. '}'
  13877. ];
  13878. /**
  13879. * A local texture counter for multi-texture shaders.
  13880. * @property textureCount
  13881. * @type Number
  13882. */
  13883. this.textureCount = 0;
  13884. /**
  13885. * A local flag
  13886. * @property firstRun
  13887. * @type Boolean
  13888. * @private
  13889. */
  13890. this.firstRun = true;
  13891. /**
  13892. * A dirty flag
  13893. * @property dirty
  13894. * @type Boolean
  13895. */
  13896. this.dirty = true;
  13897. /**
  13898. * Uniform attributes cache.
  13899. * @property attributes
  13900. * @type Array
  13901. * @private
  13902. */
  13903. this.attributes = [];
  13904. this.init();
  13905. };
  13906. PIXI.PixiShader.prototype.constructor = PIXI.PixiShader;
  13907. /**
  13908. * Initialises the shader.
  13909. *
  13910. * @method init
  13911. */
  13912. PIXI.PixiShader.prototype.init = function()
  13913. {
  13914. var gl = this.gl;
  13915. var program = PIXI.compileProgram(gl, this.vertexSrc || PIXI.PixiShader.defaultVertexSrc, this.fragmentSrc);
  13916. gl.useProgram(program);
  13917. // get and store the uniforms for the shader
  13918. this.uSampler = gl.getUniformLocation(program, 'uSampler');
  13919. this.projectionVector = gl.getUniformLocation(program, 'projectionVector');
  13920. this.offsetVector = gl.getUniformLocation(program, 'offsetVector');
  13921. this.dimensions = gl.getUniformLocation(program, 'dimensions');
  13922. // get and store the attributes
  13923. this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition');
  13924. this.aTextureCoord = gl.getAttribLocation(program, 'aTextureCoord');
  13925. this.colorAttribute = gl.getAttribLocation(program, 'aColor');
  13926. // Begin worst hack eva //
  13927. // WHY??? ONLY on my chrome pixel the line above returns -1 when using filters?
  13928. // maybe its something to do with the current state of the gl context.
  13929. // I'm convinced this is a bug in the chrome browser as there is NO reason why this should be returning -1 especially as it only manifests on my chrome pixel
  13930. // If theres any webGL people that know why could happen please help :)
  13931. if(this.colorAttribute === -1)
  13932. {
  13933. this.colorAttribute = 2;
  13934. }
  13935. this.attributes = [this.aVertexPosition, this.aTextureCoord, this.colorAttribute];
  13936. // End worst hack eva //
  13937. // add those custom shaders!
  13938. for (var key in this.uniforms)
  13939. {
  13940. // get the uniform locations..
  13941. this.uniforms[key].uniformLocation = gl.getUniformLocation(program, key);
  13942. }
  13943. this.initUniforms();
  13944. this.program = program;
  13945. };
  13946. /**
  13947. * Initialises the shader uniform values.
  13948. *
  13949. * Uniforms are specified in the GLSL_ES Specification: http://www.khronos.org/registry/webgl/specs/latest/1.0/
  13950. * http://www.khronos.org/registry/gles/specs/2.0/GLSL_ES_Specification_1.0.17.pdf
  13951. *
  13952. * @method initUniforms
  13953. */
  13954. PIXI.PixiShader.prototype.initUniforms = function()
  13955. {
  13956. this.textureCount = 1;
  13957. var gl = this.gl;
  13958. var uniform;
  13959. for (var key in this.uniforms)
  13960. {
  13961. uniform = this.uniforms[key];
  13962. var type = uniform.type;
  13963. if (type === 'sampler2D')
  13964. {
  13965. uniform._init = false;
  13966. if (uniform.value !== null)
  13967. {
  13968. this.initSampler2D(uniform);
  13969. }
  13970. }
  13971. else if (type === 'mat2' || type === 'mat3' || type === 'mat4')
  13972. {
  13973. // These require special handling
  13974. uniform.glMatrix = true;
  13975. uniform.glValueLength = 1;
  13976. if (type === 'mat2')
  13977. {
  13978. uniform.glFunc = gl.uniformMatrix2fv;
  13979. }
  13980. else if (type === 'mat3')
  13981. {
  13982. uniform.glFunc = gl.uniformMatrix3fv;
  13983. }
  13984. else if (type === 'mat4')
  13985. {
  13986. uniform.glFunc = gl.uniformMatrix4fv;
  13987. }
  13988. }
  13989. else
  13990. {
  13991. // GL function reference
  13992. uniform.glFunc = gl['uniform' + type];
  13993. if (type === '2f' || type === '2i')
  13994. {
  13995. uniform.glValueLength = 2;
  13996. }
  13997. else if (type === '3f' || type === '3i')
  13998. {
  13999. uniform.glValueLength = 3;
  14000. }
  14001. else if (type === '4f' || type === '4i')
  14002. {
  14003. uniform.glValueLength = 4;
  14004. }
  14005. else
  14006. {
  14007. uniform.glValueLength = 1;
  14008. }
  14009. }
  14010. }
  14011. };
  14012. /**
  14013. * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded)
  14014. *
  14015. * @method initSampler2D
  14016. */
  14017. PIXI.PixiShader.prototype.initSampler2D = function(uniform)
  14018. {
  14019. if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded)
  14020. {
  14021. return;
  14022. }
  14023. var gl = this.gl;
  14024. gl.activeTexture(gl['TEXTURE' + this.textureCount]);
  14025. gl.bindTexture(gl.TEXTURE_2D, uniform.value.baseTexture._glTextures[gl.id]);
  14026. // Extended texture data
  14027. if (uniform.textureData)
  14028. {
  14029. var data = uniform.textureData;
  14030. // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D);
  14031. // GLTextureLinear = mag/min linear, wrap clamp
  14032. // GLTextureNearestRepeat = mag/min NEAREST, wrap repeat
  14033. // GLTextureNearest = mag/min nearest, wrap clamp
  14034. // AudioTexture = whatever + luminance + width 512, height 2, border 0
  14035. // KeyTexture = whatever + luminance + width 256, height 2, border 0
  14036. // magFilter can be: gl.LINEAR, gl.LINEAR_MIPMAP_LINEAR or gl.NEAREST
  14037. // wrapS/T can be: gl.CLAMP_TO_EDGE or gl.REPEAT
  14038. var magFilter = (data.magFilter) ? data.magFilter : gl.LINEAR;
  14039. var minFilter = (data.minFilter) ? data.minFilter : gl.LINEAR;
  14040. var wrapS = (data.wrapS) ? data.wrapS : gl.CLAMP_TO_EDGE;
  14041. var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE;
  14042. var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA;
  14043. if (data.repeat)
  14044. {
  14045. wrapS = gl.REPEAT;
  14046. wrapT = gl.REPEAT;
  14047. }
  14048. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY);
  14049. if (data.width)
  14050. {
  14051. var width = (data.width) ? data.width : 512;
  14052. var height = (data.height) ? data.height : 2;
  14053. var border = (data.border) ? data.border : 0;
  14054. // void texImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, ArrayBufferView? pixels);
  14055. gl.texImage2D(gl.TEXTURE_2D, 0, format, width, height, border, format, gl.UNSIGNED_BYTE, null);
  14056. }
  14057. else
  14058. {
  14059. // void texImage2D(GLenum target, GLint level, GLenum internalformat, GLenum format, GLenum type, ImageData? pixels);
  14060. gl.texImage2D(gl.TEXTURE_2D, 0, format, gl.RGBA, gl.UNSIGNED_BYTE, uniform.value.baseTexture.source);
  14061. }
  14062. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  14063. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  14064. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, wrapS);
  14065. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, wrapT);
  14066. }
  14067. gl.uniform1i(uniform.uniformLocation, this.textureCount);
  14068. uniform._init = true;
  14069. this.textureCount++;
  14070. };
  14071. /**
  14072. * Updates the shader uniform values.
  14073. *
  14074. * @method syncUniforms
  14075. */
  14076. PIXI.PixiShader.prototype.syncUniforms = function()
  14077. {
  14078. this.textureCount = 1;
  14079. var uniform;
  14080. var gl = this.gl;
  14081. // This would probably be faster in an array and it would guarantee key order
  14082. for (var key in this.uniforms)
  14083. {
  14084. uniform = this.uniforms[key];
  14085. if (uniform.glValueLength === 1)
  14086. {
  14087. if (uniform.glMatrix === true)
  14088. {
  14089. uniform.glFunc.call(gl, uniform.uniformLocation, uniform.transpose, uniform.value);
  14090. }
  14091. else
  14092. {
  14093. uniform.glFunc.call(gl, uniform.uniformLocation, uniform.value);
  14094. }
  14095. }
  14096. else if (uniform.glValueLength === 2)
  14097. {
  14098. uniform.glFunc.call(gl, uniform.uniformLocation, uniform.value.x, uniform.value.y);
  14099. }
  14100. else if (uniform.glValueLength === 3)
  14101. {
  14102. uniform.glFunc.call(gl, uniform.uniformLocation, uniform.value.x, uniform.value.y, uniform.value.z);
  14103. }
  14104. else if (uniform.glValueLength === 4)
  14105. {
  14106. uniform.glFunc.call(gl, uniform.uniformLocation, uniform.value.x, uniform.value.y, uniform.value.z, uniform.value.w);
  14107. }
  14108. else if (uniform.type === 'sampler2D')
  14109. {
  14110. if (uniform._init)
  14111. {
  14112. gl.activeTexture(gl['TEXTURE' + this.textureCount]);
  14113. if(uniform.value.baseTexture._dirty[gl.id])
  14114. {
  14115. PIXI.instances[gl.id].updateTexture(uniform.value.baseTexture);
  14116. }
  14117. else
  14118. {
  14119. // bind the current texture
  14120. gl.bindTexture(gl.TEXTURE_2D, uniform.value.baseTexture._glTextures[gl.id]);
  14121. }
  14122. // gl.bindTexture(gl.TEXTURE_2D, uniform.value.baseTexture._glTextures[gl.id] || PIXI.createWebGLTexture( uniform.value.baseTexture, gl));
  14123. gl.uniform1i(uniform.uniformLocation, this.textureCount);
  14124. this.textureCount++;
  14125. }
  14126. else
  14127. {
  14128. this.initSampler2D(uniform);
  14129. }
  14130. }
  14131. }
  14132. };
  14133. /**
  14134. * Destroys the shader.
  14135. *
  14136. * @method destroy
  14137. */
  14138. PIXI.PixiShader.prototype.destroy = function()
  14139. {
  14140. this.gl.deleteProgram( this.program );
  14141. this.uniforms = null;
  14142. this.gl = null;
  14143. this.attributes = null;
  14144. };
  14145. /**
  14146. * The Default Vertex shader source.
  14147. *
  14148. * @property defaultVertexSrc
  14149. * @type String
  14150. */
  14151. PIXI.PixiShader.defaultVertexSrc = [
  14152. 'attribute vec2 aVertexPosition;',
  14153. 'attribute vec2 aTextureCoord;',
  14154. 'attribute vec4 aColor;',
  14155. 'uniform vec2 projectionVector;',
  14156. 'uniform vec2 offsetVector;',
  14157. 'varying vec2 vTextureCoord;',
  14158. 'varying vec4 vColor;',
  14159. 'const vec2 center = vec2(-1.0, 1.0);',
  14160. 'void main(void) {',
  14161. ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);',
  14162. ' vTextureCoord = aTextureCoord;',
  14163. ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);',
  14164. '}'
  14165. ];
  14166. /**
  14167. * @author Mat Groves http://matgroves.com/ @Doormat23
  14168. */
  14169. /**
  14170. * @class PixiFastShader
  14171. * @constructor
  14172. * @param gl {WebGLContext} the current WebGL drawing context
  14173. */
  14174. PIXI.PixiFastShader = function(gl)
  14175. {
  14176. /**
  14177. * @property _UID
  14178. * @type Number
  14179. * @private
  14180. */
  14181. this._UID = PIXI._UID++;
  14182. /**
  14183. * @property gl
  14184. * @type WebGLContext
  14185. */
  14186. this.gl = gl;
  14187. /**
  14188. * The WebGL program.
  14189. * @property program
  14190. * @type Any
  14191. */
  14192. this.program = null;
  14193. /**
  14194. * The fragment shader.
  14195. * @property fragmentSrc
  14196. * @type Array
  14197. */
  14198. this.fragmentSrc = [
  14199. 'precision lowp float;',
  14200. 'varying vec2 vTextureCoord;',
  14201. 'varying float vColor;',
  14202. 'uniform sampler2D uSampler;',
  14203. 'void main(void) {',
  14204. ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;',
  14205. '}'
  14206. ];
  14207. /**
  14208. * The vertex shader.
  14209. * @property vertexSrc
  14210. * @type Array
  14211. */
  14212. this.vertexSrc = [
  14213. 'attribute vec2 aVertexPosition;',
  14214. 'attribute vec2 aPositionCoord;',
  14215. 'attribute vec2 aScale;',
  14216. 'attribute float aRotation;',
  14217. 'attribute vec2 aTextureCoord;',
  14218. 'attribute float aColor;',
  14219. 'uniform vec2 projectionVector;',
  14220. 'uniform vec2 offsetVector;',
  14221. 'uniform mat3 uMatrix;',
  14222. 'varying vec2 vTextureCoord;',
  14223. 'varying float vColor;',
  14224. 'const vec2 center = vec2(-1.0, 1.0);',
  14225. 'void main(void) {',
  14226. ' vec2 v;',
  14227. ' vec2 sv = aVertexPosition * aScale;',
  14228. ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);',
  14229. ' v.y = (sv.x) * sin(aRotation) + (sv.y) * cos(aRotation);',
  14230. ' v = ( uMatrix * vec3(v + aPositionCoord , 1.0) ).xy ;',
  14231. ' gl_Position = vec4( ( v / projectionVector) + center , 0.0, 1.0);',
  14232. ' vTextureCoord = aTextureCoord;',
  14233. // ' vec3 color = mod(vec3(aColor.y/65536.0, aColor.y/256.0, aColor.y), 256.0) / 256.0;',
  14234. ' vColor = aColor;',
  14235. '}'
  14236. ];
  14237. /**
  14238. * A local texture counter for multi-texture shaders.
  14239. * @property textureCount
  14240. * @type Number
  14241. */
  14242. this.textureCount = 0;
  14243. this.init();
  14244. };
  14245. PIXI.PixiFastShader.prototype.constructor = PIXI.PixiFastShader;
  14246. /**
  14247. * Initialises the shader.
  14248. *
  14249. * @method init
  14250. */
  14251. PIXI.PixiFastShader.prototype.init = function()
  14252. {
  14253. var gl = this.gl;
  14254. var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc);
  14255. gl.useProgram(program);
  14256. // get and store the uniforms for the shader
  14257. this.uSampler = gl.getUniformLocation(program, 'uSampler');
  14258. this.projectionVector = gl.getUniformLocation(program, 'projectionVector');
  14259. this.offsetVector = gl.getUniformLocation(program, 'offsetVector');
  14260. this.dimensions = gl.getUniformLocation(program, 'dimensions');
  14261. this.uMatrix = gl.getUniformLocation(program, 'uMatrix');
  14262. // get and store the attributes
  14263. this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition');
  14264. this.aPositionCoord = gl.getAttribLocation(program, 'aPositionCoord');
  14265. this.aScale = gl.getAttribLocation(program, 'aScale');
  14266. this.aRotation = gl.getAttribLocation(program, 'aRotation');
  14267. this.aTextureCoord = gl.getAttribLocation(program, 'aTextureCoord');
  14268. this.colorAttribute = gl.getAttribLocation(program, 'aColor');
  14269. // Begin worst hack eva //
  14270. // WHY??? ONLY on my chrome pixel the line above returns -1 when using filters?
  14271. // maybe its somthing to do with the current state of the gl context.
  14272. // Im convinced this is a bug in the chrome browser as there is NO reason why this should be returning -1 especially as it only manifests on my chrome pixel
  14273. // If theres any webGL people that know why could happen please help :)
  14274. if(this.colorAttribute === -1)
  14275. {
  14276. this.colorAttribute = 2;
  14277. }
  14278. this.attributes = [this.aVertexPosition, this.aPositionCoord, this.aScale, this.aRotation, this.aTextureCoord, this.colorAttribute];
  14279. // End worst hack eva //
  14280. this.program = program;
  14281. };
  14282. /**
  14283. * Destroys the shader.
  14284. *
  14285. * @method destroy
  14286. */
  14287. PIXI.PixiFastShader.prototype.destroy = function()
  14288. {
  14289. this.gl.deleteProgram( this.program );
  14290. this.uniforms = null;
  14291. this.gl = null;
  14292. this.attributes = null;
  14293. };
  14294. /**
  14295. * @author Mat Groves http://matgroves.com/ @Doormat23
  14296. */
  14297. /**
  14298. * @class StripShader
  14299. * @constructor
  14300. * @param gl {WebGLContext} the current WebGL drawing context
  14301. */
  14302. PIXI.StripShader = function(gl)
  14303. {
  14304. /**
  14305. * @property _UID
  14306. * @type Number
  14307. * @private
  14308. */
  14309. this._UID = PIXI._UID++;
  14310. /**
  14311. * @property gl
  14312. * @type WebGLContext
  14313. */
  14314. this.gl = gl;
  14315. /**
  14316. * The WebGL program.
  14317. * @property program
  14318. * @type Any
  14319. */
  14320. this.program = null;
  14321. /**
  14322. * The fragment shader.
  14323. * @property fragmentSrc
  14324. * @type Array
  14325. */
  14326. this.fragmentSrc = [
  14327. 'precision mediump float;',
  14328. 'varying vec2 vTextureCoord;',
  14329. // 'varying float vColor;',
  14330. 'uniform float alpha;',
  14331. 'uniform sampler2D uSampler;',
  14332. 'void main(void) {',
  14333. ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;',
  14334. // ' gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);',//gl_FragColor * alpha;',
  14335. '}'
  14336. ];
  14337. /**
  14338. * The vertex shader.
  14339. * @property vertexSrc
  14340. * @type Array
  14341. */
  14342. this.vertexSrc = [
  14343. 'attribute vec2 aVertexPosition;',
  14344. 'attribute vec2 aTextureCoord;',
  14345. 'uniform mat3 translationMatrix;',
  14346. 'uniform vec2 projectionVector;',
  14347. 'uniform vec2 offsetVector;',
  14348. // 'uniform float alpha;',
  14349. // 'uniform vec3 tint;',
  14350. 'varying vec2 vTextureCoord;',
  14351. // 'varying vec4 vColor;',
  14352. 'void main(void) {',
  14353. ' vec3 v = translationMatrix * vec3(aVertexPosition , 1.0);',
  14354. ' v -= offsetVector.xyx;',
  14355. ' gl_Position = vec4( v.x / projectionVector.x -1.0, v.y / -projectionVector.y + 1.0 , 0.0, 1.0);',
  14356. ' vTextureCoord = aTextureCoord;',
  14357. // ' vColor = aColor * vec4(tint * alpha, alpha);',
  14358. '}'
  14359. ];
  14360. this.init();
  14361. };
  14362. PIXI.StripShader.prototype.constructor = PIXI.StripShader;
  14363. /**
  14364. * Initialises the shader.
  14365. *
  14366. * @method init
  14367. */
  14368. PIXI.StripShader.prototype.init = function()
  14369. {
  14370. var gl = this.gl;
  14371. var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc);
  14372. gl.useProgram(program);
  14373. // get and store the uniforms for the shader
  14374. this.uSampler = gl.getUniformLocation(program, 'uSampler');
  14375. this.projectionVector = gl.getUniformLocation(program, 'projectionVector');
  14376. this.offsetVector = gl.getUniformLocation(program, 'offsetVector');
  14377. this.colorAttribute = gl.getAttribLocation(program, 'aColor');
  14378. //this.dimensions = gl.getUniformLocation(this.program, 'dimensions');
  14379. // get and store the attributes
  14380. this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition');
  14381. this.aTextureCoord = gl.getAttribLocation(program, 'aTextureCoord');
  14382. this.attributes = [this.aVertexPosition, this.aTextureCoord];
  14383. this.translationMatrix = gl.getUniformLocation(program, 'translationMatrix');
  14384. this.alpha = gl.getUniformLocation(program, 'alpha');
  14385. this.program = program;
  14386. };
  14387. /**
  14388. * Destroys the shader.
  14389. *
  14390. * @method destroy
  14391. */
  14392. PIXI.StripShader.prototype.destroy = function()
  14393. {
  14394. this.gl.deleteProgram( this.program );
  14395. this.uniforms = null;
  14396. this.gl = null;
  14397. this.attribute = null;
  14398. };
  14399. /**
  14400. * @author Mat Groves http://matgroves.com/ @Doormat23
  14401. */
  14402. /**
  14403. * @class PrimitiveShader
  14404. * @constructor
  14405. * @param gl {WebGLContext} the current WebGL drawing context
  14406. */
  14407. PIXI.PrimitiveShader = function(gl)
  14408. {
  14409. /**
  14410. * @property _UID
  14411. * @type Number
  14412. * @private
  14413. */
  14414. this._UID = PIXI._UID++;
  14415. /**
  14416. * @property gl
  14417. * @type WebGLContext
  14418. */
  14419. this.gl = gl;
  14420. /**
  14421. * The WebGL program.
  14422. * @property program
  14423. * @type Any
  14424. */
  14425. this.program = null;
  14426. /**
  14427. * The fragment shader.
  14428. * @property fragmentSrc
  14429. * @type Array
  14430. */
  14431. this.fragmentSrc = [
  14432. 'precision mediump float;',
  14433. 'varying vec4 vColor;',
  14434. 'void main(void) {',
  14435. ' gl_FragColor = vColor;',
  14436. '}'
  14437. ];
  14438. /**
  14439. * The vertex shader.
  14440. * @property vertexSrc
  14441. * @type Array
  14442. */
  14443. this.vertexSrc = [
  14444. 'attribute vec2 aVertexPosition;',
  14445. 'attribute vec4 aColor;',
  14446. 'uniform mat3 translationMatrix;',
  14447. 'uniform vec2 projectionVector;',
  14448. 'uniform vec2 offsetVector;',
  14449. 'uniform float alpha;',
  14450. 'uniform float flipY;',
  14451. 'uniform vec3 tint;',
  14452. 'varying vec4 vColor;',
  14453. 'void main(void) {',
  14454. ' vec3 v = translationMatrix * vec3(aVertexPosition , 1.0);',
  14455. ' v -= offsetVector.xyx;',
  14456. ' gl_Position = vec4( v.x / projectionVector.x -1.0, (v.y / projectionVector.y * -flipY) + flipY , 0.0, 1.0);',
  14457. ' vColor = aColor * vec4(tint * alpha, alpha);',
  14458. '}'
  14459. ];
  14460. this.init();
  14461. };
  14462. PIXI.PrimitiveShader.prototype.constructor = PIXI.PrimitiveShader;
  14463. /**
  14464. * Initialises the shader.
  14465. *
  14466. * @method init
  14467. */
  14468. PIXI.PrimitiveShader.prototype.init = function()
  14469. {
  14470. var gl = this.gl;
  14471. var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc);
  14472. gl.useProgram(program);
  14473. // get and store the uniforms for the shader
  14474. this.projectionVector = gl.getUniformLocation(program, 'projectionVector');
  14475. this.offsetVector = gl.getUniformLocation(program, 'offsetVector');
  14476. this.tintColor = gl.getUniformLocation(program, 'tint');
  14477. this.flipY = gl.getUniformLocation(program, 'flipY');
  14478. // get and store the attributes
  14479. this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition');
  14480. this.colorAttribute = gl.getAttribLocation(program, 'aColor');
  14481. this.attributes = [this.aVertexPosition, this.colorAttribute];
  14482. this.translationMatrix = gl.getUniformLocation(program, 'translationMatrix');
  14483. this.alpha = gl.getUniformLocation(program, 'alpha');
  14484. this.program = program;
  14485. };
  14486. /**
  14487. * Destroys the shader.
  14488. *
  14489. * @method destroy
  14490. */
  14491. PIXI.PrimitiveShader.prototype.destroy = function()
  14492. {
  14493. this.gl.deleteProgram( this.program );
  14494. this.uniforms = null;
  14495. this.gl = null;
  14496. this.attributes = null;
  14497. };
  14498. /**
  14499. * @author Mat Groves http://matgroves.com/ @Doormat23
  14500. */
  14501. /**
  14502. * @class ComplexPrimitiveShader
  14503. * @constructor
  14504. * @param gl {WebGLContext} the current WebGL drawing context
  14505. */
  14506. PIXI.ComplexPrimitiveShader = function(gl)
  14507. {
  14508. /**
  14509. * @property _UID
  14510. * @type Number
  14511. * @private
  14512. */
  14513. this._UID = PIXI._UID++;
  14514. /**
  14515. * @property gl
  14516. * @type WebGLContext
  14517. */
  14518. this.gl = gl;
  14519. /**
  14520. * The WebGL program.
  14521. * @property program
  14522. * @type Any
  14523. */
  14524. this.program = null;
  14525. /**
  14526. * The fragment shader.
  14527. * @property fragmentSrc
  14528. * @type Array
  14529. */
  14530. this.fragmentSrc = [
  14531. 'precision mediump float;',
  14532. 'varying vec4 vColor;',
  14533. 'void main(void) {',
  14534. ' gl_FragColor = vColor;',
  14535. '}'
  14536. ];
  14537. /**
  14538. * The vertex shader.
  14539. * @property vertexSrc
  14540. * @type Array
  14541. */
  14542. this.vertexSrc = [
  14543. 'attribute vec2 aVertexPosition;',
  14544. //'attribute vec4 aColor;',
  14545. 'uniform mat3 translationMatrix;',
  14546. 'uniform vec2 projectionVector;',
  14547. 'uniform vec2 offsetVector;',
  14548. 'uniform vec3 tint;',
  14549. 'uniform float alpha;',
  14550. 'uniform vec3 color;',
  14551. 'uniform float flipY;',
  14552. 'varying vec4 vColor;',
  14553. 'void main(void) {',
  14554. ' vec3 v = translationMatrix * vec3(aVertexPosition , 1.0);',
  14555. ' v -= offsetVector.xyx;',
  14556. ' gl_Position = vec4( v.x / projectionVector.x -1.0, (v.y / projectionVector.y * -flipY) + flipY , 0.0, 1.0);',
  14557. ' vColor = vec4(color * alpha * tint, alpha);',//" * vec4(tint * alpha, alpha);',
  14558. '}'
  14559. ];
  14560. this.init();
  14561. };
  14562. PIXI.ComplexPrimitiveShader.prototype.constructor = PIXI.ComplexPrimitiveShader;
  14563. /**
  14564. * Initialises the shader.
  14565. *
  14566. * @method init
  14567. */
  14568. PIXI.ComplexPrimitiveShader.prototype.init = function()
  14569. {
  14570. var gl = this.gl;
  14571. var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc);
  14572. gl.useProgram(program);
  14573. // get and store the uniforms for the shader
  14574. this.projectionVector = gl.getUniformLocation(program, 'projectionVector');
  14575. this.offsetVector = gl.getUniformLocation(program, 'offsetVector');
  14576. this.tintColor = gl.getUniformLocation(program, 'tint');
  14577. this.color = gl.getUniformLocation(program, 'color');
  14578. this.flipY = gl.getUniformLocation(program, 'flipY');
  14579. // get and store the attributes
  14580. this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition');
  14581. // this.colorAttribute = gl.getAttribLocation(program, 'aColor');
  14582. this.attributes = [this.aVertexPosition, this.colorAttribute];
  14583. this.translationMatrix = gl.getUniformLocation(program, 'translationMatrix');
  14584. this.alpha = gl.getUniformLocation(program, 'alpha');
  14585. this.program = program;
  14586. };
  14587. /**
  14588. * Destroys the shader.
  14589. *
  14590. * @method destroy
  14591. */
  14592. PIXI.ComplexPrimitiveShader.prototype.destroy = function()
  14593. {
  14594. this.gl.deleteProgram( this.program );
  14595. this.uniforms = null;
  14596. this.gl = null;
  14597. this.attribute = null;
  14598. };
  14599. /**
  14600. * @author Mat Groves http://matgroves.com/ @Doormat23
  14601. */
  14602. PIXI.glContexts = []; // this is where we store the webGL contexts for easy access.
  14603. PIXI.instances = [];
  14604. /**
  14605. * The WebGLRenderer draws the stage and all its content onto a webGL enabled canvas. This renderer
  14606. * should be used for browsers that support webGL. This Render works by automatically managing webGLBatchs.
  14607. * So no need for Sprite Batches or Sprite Clouds.
  14608. * Don't forget to add the view to your DOM or you will not see anything :)
  14609. *
  14610. * @class WebGLRenderer
  14611. * @constructor
  14612. * @param game {Phaser.Game} A reference to the Phaser Game instance
  14613. */
  14614. PIXI.WebGLRenderer = function(game) {
  14615. /**
  14616. * @property {Phaser.Game} game - A reference to the Phaser Game instance.
  14617. */
  14618. this.game = game;
  14619. if (!PIXI.defaultRenderer)
  14620. {
  14621. PIXI.defaultRenderer = this;
  14622. }
  14623. /**
  14624. * @property type
  14625. * @type Number
  14626. */
  14627. this.type = PIXI.WEBGL_RENDERER;
  14628. /**
  14629. * The resolution of the renderer
  14630. *
  14631. * @property resolution
  14632. * @type Number
  14633. * @default 1
  14634. */
  14635. this.resolution = game.resolution;
  14636. /**
  14637. * Whether the render view is transparent
  14638. *
  14639. * @property transparent
  14640. * @type Boolean
  14641. */
  14642. this.transparent = game.transparent;
  14643. /**
  14644. * Whether the render view should be resized automatically
  14645. *
  14646. * @property autoResize
  14647. * @type Boolean
  14648. */
  14649. this.autoResize = false;
  14650. /**
  14651. * The value of the preserveDrawingBuffer flag affects whether or not the contents of the stencil buffer is retained after rendering.
  14652. *
  14653. * @property preserveDrawingBuffer
  14654. * @type Boolean
  14655. */
  14656. this.preserveDrawingBuffer = game.preserveDrawingBuffer;
  14657. /**
  14658. * This sets if the WebGLRenderer will clear the context texture or not before the new render pass. If true:
  14659. * If the Stage is NOT transparent, Pixi will clear to alpha (0, 0, 0, 0).
  14660. * If the Stage is transparent, Pixi will clear to the target Stage's background color.
  14661. * Disable this by setting this to false. For example: if your game has a canvas filling background image, you often don't need this set.
  14662. *
  14663. * @property clearBeforeRender
  14664. * @type Boolean
  14665. * @default
  14666. */
  14667. this.clearBeforeRender = game.clearBeforeRender;
  14668. /**
  14669. * The width of the canvas view
  14670. *
  14671. * @property width
  14672. * @type Number
  14673. */
  14674. this.width = game.width;
  14675. /**
  14676. * The height of the canvas view
  14677. *
  14678. * @property height
  14679. * @type Number
  14680. */
  14681. this.height = game.height;
  14682. /**
  14683. * The canvas element that everything is drawn to
  14684. *
  14685. * @property view
  14686. * @type HTMLCanvasElement
  14687. */
  14688. this.view = game.canvas;
  14689. /**
  14690. * @property _contextOptions
  14691. * @type Object
  14692. * @private
  14693. */
  14694. this._contextOptions = {
  14695. alpha: this.transparent,
  14696. antialias: game.antialias,
  14697. premultipliedAlpha: this.transparent && this.transparent !== 'notMultiplied',
  14698. stencil: true,
  14699. preserveDrawingBuffer: this.preserveDrawingBuffer
  14700. };
  14701. /**
  14702. * @property projection
  14703. * @type Point
  14704. */
  14705. this.projection = new PIXI.Point();
  14706. /**
  14707. * @property offset
  14708. * @type Point
  14709. */
  14710. this.offset = new PIXI.Point();
  14711. // time to create the render managers! each one focuses on managing a state in webGL
  14712. /**
  14713. * Deals with managing the shader programs and their attribs
  14714. * @property shaderManager
  14715. * @type WebGLShaderManager
  14716. */
  14717. this.shaderManager = new PIXI.WebGLShaderManager();
  14718. /**
  14719. * Manages the rendering of sprites
  14720. * @property spriteBatch
  14721. * @type WebGLSpriteBatch
  14722. */
  14723. this.spriteBatch = new PIXI.WebGLSpriteBatch();
  14724. /**
  14725. * Manages the masks using the stencil buffer
  14726. * @property maskManager
  14727. * @type WebGLMaskManager
  14728. */
  14729. this.maskManager = new PIXI.WebGLMaskManager();
  14730. /**
  14731. * Manages the filters
  14732. * @property filterManager
  14733. * @type WebGLFilterManager
  14734. */
  14735. this.filterManager = new PIXI.WebGLFilterManager();
  14736. /**
  14737. * Manages the stencil buffer
  14738. * @property stencilManager
  14739. * @type WebGLStencilManager
  14740. */
  14741. this.stencilManager = new PIXI.WebGLStencilManager();
  14742. /**
  14743. * Manages the blendModes
  14744. * @property blendModeManager
  14745. * @type WebGLBlendModeManager
  14746. */
  14747. this.blendModeManager = new PIXI.WebGLBlendModeManager();
  14748. /**
  14749. * @property renderSession
  14750. * @type Object
  14751. */
  14752. this.renderSession = {};
  14753. // Needed?
  14754. this.renderSession.game = this.game;
  14755. this.renderSession.gl = this.gl;
  14756. this.renderSession.drawCount = 0;
  14757. this.renderSession.shaderManager = this.shaderManager;
  14758. this.renderSession.maskManager = this.maskManager;
  14759. this.renderSession.filterManager = this.filterManager;
  14760. this.renderSession.blendModeManager = this.blendModeManager;
  14761. this.renderSession.spriteBatch = this.spriteBatch;
  14762. this.renderSession.stencilManager = this.stencilManager;
  14763. this.renderSession.renderer = this;
  14764. this.renderSession.resolution = this.resolution;
  14765. // time init the context..
  14766. this.initContext();
  14767. // map some webGL blend modes..
  14768. this.mapBlendModes();
  14769. };
  14770. // constructor
  14771. PIXI.WebGLRenderer.prototype.constructor = PIXI.WebGLRenderer;
  14772. /**
  14773. * @method initContext
  14774. */
  14775. PIXI.WebGLRenderer.prototype.initContext = function()
  14776. {
  14777. var gl = this.view.getContext('webgl', this._contextOptions) || this.view.getContext('experimental-webgl', this._contextOptions);
  14778. this.gl = gl;
  14779. if (!gl) {
  14780. // fail, not able to get a context
  14781. throw new Error('This browser does not support webGL. Try using the canvas renderer');
  14782. }
  14783. this.glContextId = gl.id = PIXI.WebGLRenderer.glContextId++;
  14784. PIXI.glContexts[this.glContextId] = gl;
  14785. PIXI.instances[this.glContextId] = this;
  14786. // set up the default pixi settings..
  14787. gl.disable(gl.DEPTH_TEST);
  14788. gl.disable(gl.CULL_FACE);
  14789. gl.enable(gl.BLEND);
  14790. // need to set the context for all the managers...
  14791. this.shaderManager.setContext(gl);
  14792. this.spriteBatch.setContext(gl);
  14793. this.maskManager.setContext(gl);
  14794. this.filterManager.setContext(gl);
  14795. this.blendModeManager.setContext(gl);
  14796. this.stencilManager.setContext(gl);
  14797. this.renderSession.gl = this.gl;
  14798. // now resize and we are good to go!
  14799. this.resize(this.width, this.height);
  14800. };
  14801. /**
  14802. * Renders the stage to its webGL view
  14803. *
  14804. * @method render
  14805. * @param stage {Stage} the Stage element to be rendered
  14806. */
  14807. PIXI.WebGLRenderer.prototype.render = function(stage)
  14808. {
  14809. // no point rendering if our context has been blown up!
  14810. if (this.contextLost)
  14811. {
  14812. return;
  14813. }
  14814. // update the scene graph
  14815. stage.updateTransform();
  14816. var gl = this.gl;
  14817. // -- Does this need to be set every frame? -- //
  14818. gl.viewport(0, 0, this.width, this.height);
  14819. // make sure we are bound to the main frame buffer
  14820. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14821. if (this.game.clearBeforeRender)
  14822. {
  14823. gl.clearColor(stage._bgColor.r, stage._bgColor.g, stage._bgColor.b, stage._bgColor.a);
  14824. gl.clear(gl.COLOR_BUFFER_BIT);
  14825. }
  14826. this.offset.x = this.game.camera._shake.x;
  14827. this.offset.y = this.game.camera._shake.y;
  14828. this.renderDisplayObject(stage, this.projection);
  14829. };
  14830. /**
  14831. * Renders a Display Object.
  14832. *
  14833. * @method renderDisplayObject
  14834. * @param displayObject {DisplayObject} The DisplayObject to render
  14835. * @param projection {Point} The projection
  14836. * @param buffer {Array} a standard WebGL buffer
  14837. */
  14838. PIXI.WebGLRenderer.prototype.renderDisplayObject = function(displayObject, projection, buffer, matrix)
  14839. {
  14840. this.renderSession.blendModeManager.setBlendMode(PIXI.blendModes.NORMAL);
  14841. // reset the render session data..
  14842. this.renderSession.drawCount = 0;
  14843. // make sure to flip the Y if using a render texture..
  14844. this.renderSession.flipY = buffer ? -1 : 1;
  14845. // set the default projection
  14846. this.renderSession.projection = projection;
  14847. //set the default offset
  14848. this.renderSession.offset = this.offset;
  14849. // start the sprite batch
  14850. this.spriteBatch.begin(this.renderSession);
  14851. // start the filter manager
  14852. this.filterManager.begin(this.renderSession, buffer);
  14853. // render the scene!
  14854. displayObject._renderWebGL(this.renderSession, matrix);
  14855. // finish the sprite batch
  14856. this.spriteBatch.end();
  14857. };
  14858. /**
  14859. * Resizes the webGL view to the specified width and height.
  14860. *
  14861. * @method resize
  14862. * @param width {Number} the new width of the webGL view
  14863. * @param height {Number} the new height of the webGL view
  14864. */
  14865. PIXI.WebGLRenderer.prototype.resize = function(width, height)
  14866. {
  14867. this.width = width * this.resolution;
  14868. this.height = height * this.resolution;
  14869. this.view.width = this.width;
  14870. this.view.height = this.height;
  14871. if (this.autoResize) {
  14872. this.view.style.width = this.width / this.resolution + 'px';
  14873. this.view.style.height = this.height / this.resolution + 'px';
  14874. }
  14875. this.gl.viewport(0, 0, this.width, this.height);
  14876. this.projection.x = this.width / 2 / this.resolution;
  14877. this.projection.y = -this.height / 2 / this.resolution;
  14878. };
  14879. /**
  14880. * Updates and Creates a WebGL texture for the renderers context.
  14881. *
  14882. * @method updateTexture
  14883. * @param texture {Texture} the texture to update
  14884. * @return {boolean} True if the texture was successfully bound, otherwise false.
  14885. */
  14886. PIXI.WebGLRenderer.prototype.updateTexture = function(texture)
  14887. {
  14888. if (!texture.hasLoaded)
  14889. {
  14890. return false;
  14891. }
  14892. var gl = this.gl;
  14893. if (!texture._glTextures[gl.id])
  14894. {
  14895. texture._glTextures[gl.id] = gl.createTexture();
  14896. }
  14897. gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]);
  14898. gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultipliedAlpha);
  14899. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, texture.source);
  14900. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, texture.scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST);
  14901. if (texture.mipmap && PIXI.isPowerOfTwo(texture.width, texture.height))
  14902. {
  14903. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, texture.scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST);
  14904. gl.generateMipmap(gl.TEXTURE_2D);
  14905. }
  14906. else
  14907. {
  14908. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, texture.scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST);
  14909. }
  14910. if (!texture._powerOf2)
  14911. {
  14912. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14913. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14914. }
  14915. else
  14916. {
  14917. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
  14918. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
  14919. }
  14920. texture._dirty[gl.id] = false;
  14921. // return texture._glTextures[gl.id];
  14922. return true;
  14923. };
  14924. /**
  14925. * Removes everything from the renderer (event listeners, spritebatch, etc...)
  14926. *
  14927. * @method destroy
  14928. */
  14929. PIXI.WebGLRenderer.prototype.destroy = function()
  14930. {
  14931. PIXI.glContexts[this.glContextId] = null;
  14932. this.projection = null;
  14933. this.offset = null;
  14934. this.shaderManager.destroy();
  14935. this.spriteBatch.destroy();
  14936. this.maskManager.destroy();
  14937. this.filterManager.destroy();
  14938. this.shaderManager = null;
  14939. this.spriteBatch = null;
  14940. this.maskManager = null;
  14941. this.filterManager = null;
  14942. this.gl = null;
  14943. this.renderSession = null;
  14944. PIXI.CanvasPool.remove(this);
  14945. PIXI.instances[this.glContextId] = null;
  14946. PIXI.WebGLRenderer.glContextId--;
  14947. };
  14948. /**
  14949. * Maps Pixi blend modes to WebGL blend modes.
  14950. *
  14951. * @method mapBlendModes
  14952. */
  14953. PIXI.WebGLRenderer.prototype.mapBlendModes = function()
  14954. {
  14955. var gl = this.gl;
  14956. if (!PIXI.blendModesWebGL)
  14957. {
  14958. var b = [];
  14959. var modes = PIXI.blendModes;
  14960. b[modes.NORMAL] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  14961. b[modes.ADD] = [gl.SRC_ALPHA, gl.DST_ALPHA];
  14962. b[modes.MULTIPLY] = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA];
  14963. b[modes.SCREEN] = [gl.SRC_ALPHA, gl.ONE];
  14964. b[modes.OVERLAY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  14965. b[modes.DARKEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  14966. b[modes.LIGHTEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  14967. b[modes.COLOR_DODGE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  14968. b[modes.COLOR_BURN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  14969. b[modes.HARD_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  14970. b[modes.SOFT_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  14971. b[modes.DIFFERENCE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  14972. b[modes.EXCLUSION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  14973. b[modes.HUE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  14974. b[modes.SATURATION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  14975. b[modes.COLOR] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  14976. b[modes.LUMINOSITY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  14977. PIXI.blendModesWebGL = b;
  14978. }
  14979. };
  14980. PIXI.WebGLRenderer.glContextId = 0;
  14981. /**
  14982. * @author Mat Groves http://matgroves.com/ @Doormat23
  14983. */
  14984. /**
  14985. * @class WebGLBlendModeManager
  14986. * @constructor
  14987. * @param gl {WebGLContext} the current WebGL drawing context
  14988. */
  14989. PIXI.WebGLBlendModeManager = function()
  14990. {
  14991. /**
  14992. * @property currentBlendMode
  14993. * @type Number
  14994. */
  14995. this.currentBlendMode = 99999;
  14996. };
  14997. PIXI.WebGLBlendModeManager.prototype.constructor = PIXI.WebGLBlendModeManager;
  14998. /**
  14999. * Sets the WebGL Context.
  15000. *
  15001. * @method setContext
  15002. * @param gl {WebGLContext} the current WebGL drawing context
  15003. */
  15004. PIXI.WebGLBlendModeManager.prototype.setContext = function(gl)
  15005. {
  15006. this.gl = gl;
  15007. };
  15008. /**
  15009. * Sets-up the given blendMode from WebGL's point of view.
  15010. *
  15011. * @method setBlendMode
  15012. * @param blendMode {Number} the blendMode, should be a Pixi const, such as PIXI.BlendModes.ADD
  15013. */
  15014. PIXI.WebGLBlendModeManager.prototype.setBlendMode = function(blendMode)
  15015. {
  15016. if(this.currentBlendMode === blendMode)return false;
  15017. this.currentBlendMode = blendMode;
  15018. var blendModeWebGL = PIXI.blendModesWebGL[this.currentBlendMode];
  15019. if (blendModeWebGL)
  15020. {
  15021. this.gl.blendFunc(blendModeWebGL[0], blendModeWebGL[1]);
  15022. }
  15023. return true;
  15024. };
  15025. /**
  15026. * Destroys this object.
  15027. *
  15028. * @method destroy
  15029. */
  15030. PIXI.WebGLBlendModeManager.prototype.destroy = function()
  15031. {
  15032. this.gl = null;
  15033. };
  15034. /**
  15035. * @author Mat Groves http://matgroves.com/ @Doormat23
  15036. */
  15037. /**
  15038. * @class WebGLMaskManager
  15039. * @constructor
  15040. * @private
  15041. */
  15042. PIXI.WebGLMaskManager = function()
  15043. {
  15044. };
  15045. PIXI.WebGLMaskManager.prototype.constructor = PIXI.WebGLMaskManager;
  15046. /**
  15047. * Sets the drawing context to the one given in parameter.
  15048. *
  15049. * @method setContext
  15050. * @param gl {WebGLContext} the current WebGL drawing context
  15051. */
  15052. PIXI.WebGLMaskManager.prototype.setContext = function(gl)
  15053. {
  15054. this.gl = gl;
  15055. };
  15056. /**
  15057. * Applies the Mask and adds it to the current filter stack.
  15058. *
  15059. * @method pushMask
  15060. * @param maskData {Array}
  15061. * @param renderSession {Object}
  15062. */
  15063. PIXI.WebGLMaskManager.prototype.pushMask = function(maskData, renderSession)
  15064. {
  15065. var gl = renderSession.gl;
  15066. if (maskData.dirty)
  15067. {
  15068. PIXI.WebGLGraphics.updateGraphics(maskData, gl);
  15069. }
  15070. if (maskData._webGL[gl.id] === undefined || maskData._webGL[gl.id].data === undefined || maskData._webGL[gl.id].data.length === 0)
  15071. {
  15072. return;
  15073. }
  15074. renderSession.stencilManager.pushStencil(maskData, maskData._webGL[gl.id].data[0], renderSession);
  15075. };
  15076. /**
  15077. * Removes the last filter from the filter stack and doesn't return it.
  15078. *
  15079. * @method popMask
  15080. * @param maskData {Array}
  15081. * @param renderSession {Object} an object containing all the useful parameters
  15082. */
  15083. PIXI.WebGLMaskManager.prototype.popMask = function(maskData, renderSession)
  15084. {
  15085. var gl = this.gl;
  15086. if (maskData._webGL[gl.id] === undefined || maskData._webGL[gl.id].data === undefined || maskData._webGL[gl.id].data.length === 0)
  15087. {
  15088. return;
  15089. }
  15090. renderSession.stencilManager.popStencil(maskData, maskData._webGL[gl.id].data[0], renderSession);
  15091. };
  15092. /**
  15093. * Destroys the mask stack.
  15094. *
  15095. * @method destroy
  15096. */
  15097. PIXI.WebGLMaskManager.prototype.destroy = function()
  15098. {
  15099. this.gl = null;
  15100. };
  15101. /**
  15102. * @author Mat Groves http://matgroves.com/ @Doormat23
  15103. */
  15104. /**
  15105. * @class WebGLStencilManager
  15106. * @constructor
  15107. * @private
  15108. */
  15109. PIXI.WebGLStencilManager = function()
  15110. {
  15111. this.stencilStack = [];
  15112. this.reverse = true;
  15113. this.count = 0;
  15114. };
  15115. /**
  15116. * Sets the drawing context to the one given in parameter.
  15117. *
  15118. * @method setContext
  15119. * @param gl {WebGLContext} the current WebGL drawing context
  15120. */
  15121. PIXI.WebGLStencilManager.prototype.setContext = function(gl)
  15122. {
  15123. this.gl = gl;
  15124. };
  15125. /**
  15126. * Applies the Mask and adds it to the current filter stack.
  15127. *
  15128. * @method pushMask
  15129. * @param graphics {Graphics}
  15130. * @param webGLData {Array}
  15131. * @param renderSession {Object}
  15132. */
  15133. PIXI.WebGLStencilManager.prototype.pushStencil = function(graphics, webGLData, renderSession)
  15134. {
  15135. var gl = this.gl;
  15136. this.bindGraphics(graphics, webGLData, renderSession);
  15137. if(this.stencilStack.length === 0)
  15138. {
  15139. gl.enable(gl.STENCIL_TEST);
  15140. gl.clear(gl.STENCIL_BUFFER_BIT);
  15141. this.reverse = true;
  15142. this.count = 0;
  15143. }
  15144. this.stencilStack.push(webGLData);
  15145. var level = this.count;
  15146. gl.colorMask(false, false, false, false);
  15147. gl.stencilFunc(gl.ALWAYS,0,0xFF);
  15148. gl.stencilOp(gl.KEEP,gl.KEEP,gl.INVERT);
  15149. // draw the triangle strip!
  15150. if(webGLData.mode === 1)
  15151. {
  15152. gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 );
  15153. if(this.reverse)
  15154. {
  15155. gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF);
  15156. gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR);
  15157. }
  15158. else
  15159. {
  15160. gl.stencilFunc(gl.EQUAL,level, 0xFF);
  15161. gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR);
  15162. }
  15163. // draw a quad to increment..
  15164. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 );
  15165. if(this.reverse)
  15166. {
  15167. gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF);
  15168. }
  15169. else
  15170. {
  15171. gl.stencilFunc(gl.EQUAL,level+1, 0xFF);
  15172. }
  15173. this.reverse = !this.reverse;
  15174. }
  15175. else
  15176. {
  15177. if(!this.reverse)
  15178. {
  15179. gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF);
  15180. gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR);
  15181. }
  15182. else
  15183. {
  15184. gl.stencilFunc(gl.EQUAL,level, 0xFF);
  15185. gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR);
  15186. }
  15187. gl.drawElements(gl.TRIANGLE_STRIP, webGLData.indices.length, gl.UNSIGNED_SHORT, 0 );
  15188. if(!this.reverse)
  15189. {
  15190. gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF);
  15191. }
  15192. else
  15193. {
  15194. gl.stencilFunc(gl.EQUAL,level+1, 0xFF);
  15195. }
  15196. }
  15197. gl.colorMask(true, true, true, true);
  15198. gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP);
  15199. this.count++;
  15200. };
  15201. /**
  15202. * TODO this does not belong here!
  15203. *
  15204. * @method bindGraphics
  15205. * @param graphics {Graphics}
  15206. * @param webGLData {Array}
  15207. * @param renderSession {Object}
  15208. */
  15209. PIXI.WebGLStencilManager.prototype.bindGraphics = function(graphics, webGLData, renderSession)
  15210. {
  15211. //if(this._currentGraphics === graphics)return;
  15212. this._currentGraphics = graphics;
  15213. var gl = this.gl;
  15214. // bind the graphics object..
  15215. var projection = renderSession.projection,
  15216. offset = renderSession.offset,
  15217. shader;// = renderSession.shaderManager.primitiveShader;
  15218. if(webGLData.mode === 1)
  15219. {
  15220. shader = renderSession.shaderManager.complexPrimitiveShader;
  15221. renderSession.shaderManager.setShader( shader );
  15222. gl.uniform1f(shader.flipY, renderSession.flipY);
  15223. gl.uniformMatrix3fv(shader.translationMatrix, false, graphics.worldTransform.toArray(true));
  15224. gl.uniform2f(shader.projectionVector, projection.x, -projection.y);
  15225. gl.uniform2f(shader.offsetVector, -offset.x, -offset.y);
  15226. gl.uniform3fv(shader.tintColor, PIXI.hex2rgb(graphics.tint));
  15227. gl.uniform3fv(shader.color, webGLData.color);
  15228. gl.uniform1f(shader.alpha, graphics.worldAlpha * webGLData.alpha);
  15229. gl.bindBuffer(gl.ARRAY_BUFFER, webGLData.buffer);
  15230. gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 4 * 2, 0);
  15231. // now do the rest..
  15232. // set the index buffer!
  15233. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer);
  15234. }
  15235. else
  15236. {
  15237. //renderSession.shaderManager.activatePrimitiveShader();
  15238. shader = renderSession.shaderManager.primitiveShader;
  15239. renderSession.shaderManager.setShader( shader );
  15240. gl.uniformMatrix3fv(shader.translationMatrix, false, graphics.worldTransform.toArray(true));
  15241. gl.uniform1f(shader.flipY, renderSession.flipY);
  15242. gl.uniform2f(shader.projectionVector, projection.x, -projection.y);
  15243. gl.uniform2f(shader.offsetVector, -offset.x, -offset.y);
  15244. gl.uniform3fv(shader.tintColor, PIXI.hex2rgb(graphics.tint));
  15245. gl.uniform1f(shader.alpha, graphics.worldAlpha);
  15246. gl.bindBuffer(gl.ARRAY_BUFFER, webGLData.buffer);
  15247. gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 4 * 6, 0);
  15248. gl.vertexAttribPointer(shader.colorAttribute, 4, gl.FLOAT, false,4 * 6, 2 * 4);
  15249. // set the index buffer!
  15250. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer);
  15251. }
  15252. };
  15253. /**
  15254. * @method popStencil
  15255. * @param graphics {Graphics}
  15256. * @param webGLData {Array}
  15257. * @param renderSession {Object}
  15258. */
  15259. PIXI.WebGLStencilManager.prototype.popStencil = function(graphics, webGLData, renderSession)
  15260. {
  15261. var gl = this.gl;
  15262. this.stencilStack.pop();
  15263. this.count--;
  15264. if(this.stencilStack.length === 0)
  15265. {
  15266. // the stack is empty!
  15267. gl.disable(gl.STENCIL_TEST);
  15268. }
  15269. else
  15270. {
  15271. var level = this.count;
  15272. this.bindGraphics(graphics, webGLData, renderSession);
  15273. gl.colorMask(false, false, false, false);
  15274. if(webGLData.mode === 1)
  15275. {
  15276. this.reverse = !this.reverse;
  15277. if(this.reverse)
  15278. {
  15279. gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF);
  15280. gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR);
  15281. }
  15282. else
  15283. {
  15284. gl.stencilFunc(gl.EQUAL,level+1, 0xFF);
  15285. gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR);
  15286. }
  15287. // draw a quad to increment..
  15288. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 );
  15289. gl.stencilFunc(gl.ALWAYS,0,0xFF);
  15290. gl.stencilOp(gl.KEEP,gl.KEEP,gl.INVERT);
  15291. // draw the triangle strip!
  15292. gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 );
  15293. if(!this.reverse)
  15294. {
  15295. gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF);
  15296. }
  15297. else
  15298. {
  15299. gl.stencilFunc(gl.EQUAL,level, 0xFF);
  15300. }
  15301. }
  15302. else
  15303. {
  15304. // console.log("<<>>")
  15305. if(!this.reverse)
  15306. {
  15307. gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF);
  15308. gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR);
  15309. }
  15310. else
  15311. {
  15312. gl.stencilFunc(gl.EQUAL,level+1, 0xFF);
  15313. gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR);
  15314. }
  15315. gl.drawElements(gl.TRIANGLE_STRIP, webGLData.indices.length, gl.UNSIGNED_SHORT, 0 );
  15316. if(!this.reverse)
  15317. {
  15318. gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF);
  15319. }
  15320. else
  15321. {
  15322. gl.stencilFunc(gl.EQUAL,level, 0xFF);
  15323. }
  15324. }
  15325. gl.colorMask(true, true, true, true);
  15326. gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP);
  15327. }
  15328. };
  15329. /**
  15330. * Destroys the mask stack.
  15331. *
  15332. * @method destroy
  15333. */
  15334. PIXI.WebGLStencilManager.prototype.destroy = function()
  15335. {
  15336. this.stencilStack = null;
  15337. this.gl = null;
  15338. };
  15339. /**
  15340. * @author Mat Groves http://matgroves.com/ @Doormat23
  15341. */
  15342. /**
  15343. * @class WebGLShaderManager
  15344. * @constructor
  15345. * @private
  15346. */
  15347. PIXI.WebGLShaderManager = function()
  15348. {
  15349. /**
  15350. * @property maxAttibs
  15351. * @type Number
  15352. */
  15353. this.maxAttibs = 10;
  15354. /**
  15355. * @property attribState
  15356. * @type Array
  15357. */
  15358. this.attribState = [];
  15359. /**
  15360. * @property tempAttribState
  15361. * @type Array
  15362. */
  15363. this.tempAttribState = [];
  15364. for (var i = 0; i < this.maxAttibs; i++)
  15365. {
  15366. this.attribState[i] = false;
  15367. }
  15368. /**
  15369. * @property stack
  15370. * @type Array
  15371. */
  15372. this.stack = [];
  15373. };
  15374. PIXI.WebGLShaderManager.prototype.constructor = PIXI.WebGLShaderManager;
  15375. /**
  15376. * Initialises the context and the properties.
  15377. *
  15378. * @method setContext
  15379. * @param gl {WebGLContext} the current WebGL drawing context
  15380. */
  15381. PIXI.WebGLShaderManager.prototype.setContext = function(gl)
  15382. {
  15383. this.gl = gl;
  15384. // the next one is used for rendering primitives
  15385. this.primitiveShader = new PIXI.PrimitiveShader(gl);
  15386. // the next one is used for rendering triangle strips
  15387. this.complexPrimitiveShader = new PIXI.ComplexPrimitiveShader(gl);
  15388. // this shader is used for the default sprite rendering
  15389. this.defaultShader = new PIXI.PixiShader(gl);
  15390. // this shader is used for the fast sprite rendering
  15391. this.fastShader = new PIXI.PixiFastShader(gl);
  15392. // the next one is used for rendering triangle strips
  15393. this.stripShader = new PIXI.StripShader(gl);
  15394. this.setShader(this.defaultShader);
  15395. };
  15396. /**
  15397. * Takes the attributes given in parameters.
  15398. *
  15399. * @method setAttribs
  15400. * @param attribs {Array} attribs
  15401. */
  15402. PIXI.WebGLShaderManager.prototype.setAttribs = function(attribs)
  15403. {
  15404. // reset temp state
  15405. var i;
  15406. for (i = 0; i < this.tempAttribState.length; i++)
  15407. {
  15408. this.tempAttribState[i] = false;
  15409. }
  15410. // set the new attribs
  15411. for (i = 0; i < attribs.length; i++)
  15412. {
  15413. var attribId = attribs[i];
  15414. this.tempAttribState[attribId] = true;
  15415. }
  15416. var gl = this.gl;
  15417. for (i = 0; i < this.attribState.length; i++)
  15418. {
  15419. if(this.attribState[i] !== this.tempAttribState[i])
  15420. {
  15421. this.attribState[i] = this.tempAttribState[i];
  15422. if(this.tempAttribState[i])
  15423. {
  15424. gl.enableVertexAttribArray(i);
  15425. }
  15426. else
  15427. {
  15428. gl.disableVertexAttribArray(i);
  15429. }
  15430. }
  15431. }
  15432. };
  15433. /**
  15434. * Sets the current shader.
  15435. *
  15436. * @method setShader
  15437. * @param shader {Any}
  15438. */
  15439. PIXI.WebGLShaderManager.prototype.setShader = function(shader)
  15440. {
  15441. if(this._currentId === shader._UID)return false;
  15442. this._currentId = shader._UID;
  15443. this.currentShader = shader;
  15444. this.gl.useProgram(shader.program);
  15445. this.setAttribs(shader.attributes);
  15446. return true;
  15447. };
  15448. /**
  15449. * Destroys this object.
  15450. *
  15451. * @method destroy
  15452. */
  15453. PIXI.WebGLShaderManager.prototype.destroy = function()
  15454. {
  15455. this.attribState = null;
  15456. this.tempAttribState = null;
  15457. this.primitiveShader.destroy();
  15458. this.complexPrimitiveShader.destroy();
  15459. this.defaultShader.destroy();
  15460. this.fastShader.destroy();
  15461. this.stripShader.destroy();
  15462. this.gl = null;
  15463. };
  15464. /**
  15465. * @author Mat Groves
  15466. *
  15467. * Big thanks to the very clever Matt DesLauriers <mattdesl> https://github.com/mattdesl/
  15468. * for creating the original pixi version!
  15469. * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now share 4 bytes on the vertex buffer
  15470. *
  15471. * Heavily inspired by LibGDX's WebGLSpriteBatch:
  15472. * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/WebGLSpriteBatch.java
  15473. */
  15474. /**
  15475. *
  15476. * @class WebGLSpriteBatch
  15477. * @private
  15478. * @constructor
  15479. */
  15480. PIXI.WebGLSpriteBatch = function()
  15481. {
  15482. /**
  15483. * @property vertSize
  15484. * @type Number
  15485. */
  15486. this.vertSize = 5;
  15487. /**
  15488. * The number of images in the SpriteBatch before it flushes
  15489. * @property size
  15490. * @type Number
  15491. */
  15492. this.size = 2000;//Math.pow(2, 16) / this.vertSize;
  15493. //the total number of bytes in our batch
  15494. var numVerts = this.size * 4 * 4 * this.vertSize;
  15495. //the total number of indices in our batch
  15496. var numIndices = this.size * 6;
  15497. /**
  15498. * Holds the vertices
  15499. *
  15500. * @property vertices
  15501. * @type ArrayBuffer
  15502. */
  15503. this.vertices = new PIXI.ArrayBuffer(numVerts);
  15504. /**
  15505. * View on the vertices as a Float32Array
  15506. *
  15507. * @property positions
  15508. * @type Float32Array
  15509. */
  15510. this.positions = new PIXI.Float32Array(this.vertices);
  15511. /**
  15512. * View on the vertices as a Uint32Array
  15513. *
  15514. * @property colors
  15515. * @type Uint32Array
  15516. */
  15517. this.colors = new PIXI.Uint32Array(this.vertices);
  15518. /**
  15519. * Holds the indices
  15520. *
  15521. * @property indices
  15522. * @type Uint16Array
  15523. */
  15524. this.indices = new PIXI.Uint16Array(numIndices);
  15525. /**
  15526. * @property lastIndexCount
  15527. * @type Number
  15528. */
  15529. this.lastIndexCount = 0;
  15530. for (var i=0, j=0; i < numIndices; i += 6, j += 4)
  15531. {
  15532. this.indices[i + 0] = j + 0;
  15533. this.indices[i + 1] = j + 1;
  15534. this.indices[i + 2] = j + 2;
  15535. this.indices[i + 3] = j + 0;
  15536. this.indices[i + 4] = j + 2;
  15537. this.indices[i + 5] = j + 3;
  15538. }
  15539. /**
  15540. * @property drawing
  15541. * @type Boolean
  15542. */
  15543. this.drawing = false;
  15544. /**
  15545. * @property currentBatchSize
  15546. * @type Number
  15547. */
  15548. this.currentBatchSize = 0;
  15549. /**
  15550. * @property currentBaseTexture
  15551. * @type BaseTexture
  15552. */
  15553. this.currentBaseTexture = null;
  15554. /**
  15555. * @property dirty
  15556. * @type Boolean
  15557. */
  15558. this.dirty = true;
  15559. /**
  15560. * @property textures
  15561. * @type Array
  15562. */
  15563. this.textures = [];
  15564. /**
  15565. * @property blendModes
  15566. * @type Array
  15567. */
  15568. this.blendModes = [];
  15569. /**
  15570. * @property shaders
  15571. * @type Array
  15572. */
  15573. this.shaders = [];
  15574. /**
  15575. * @property sprites
  15576. * @type Array
  15577. */
  15578. this.sprites = [];
  15579. /**
  15580. * @property defaultShader
  15581. * @type AbstractFilter
  15582. */
  15583. this.defaultShader = new PIXI.AbstractFilter([
  15584. 'precision lowp float;',
  15585. 'varying vec2 vTextureCoord;',
  15586. 'varying vec4 vColor;',
  15587. 'uniform sampler2D uSampler;',
  15588. 'void main(void) {',
  15589. ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;',
  15590. '}'
  15591. ]);
  15592. };
  15593. /**
  15594. * @method setContext
  15595. * @param gl {WebGLContext} the current WebGL drawing context
  15596. */
  15597. PIXI.WebGLSpriteBatch.prototype.setContext = function(gl)
  15598. {
  15599. this.gl = gl;
  15600. // create a couple of buffers
  15601. this.vertexBuffer = gl.createBuffer();
  15602. this.indexBuffer = gl.createBuffer();
  15603. // 65535 is max index, so 65535 / 6 = 10922.
  15604. //upload the index data
  15605. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
  15606. gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW);
  15607. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  15608. gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.DYNAMIC_DRAW);
  15609. this.currentBlendMode = 99999;
  15610. var shader = new PIXI.PixiShader(gl);
  15611. shader.fragmentSrc = this.defaultShader.fragmentSrc;
  15612. shader.uniforms = {};
  15613. shader.init();
  15614. this.defaultShader.shaders[gl.id] = shader;
  15615. };
  15616. /**
  15617. * @method begin
  15618. * @param renderSession {Object} The RenderSession object
  15619. */
  15620. PIXI.WebGLSpriteBatch.prototype.begin = function(renderSession)
  15621. {
  15622. this.renderSession = renderSession;
  15623. this.shader = this.renderSession.shaderManager.defaultShader;
  15624. this.start();
  15625. };
  15626. /**
  15627. * @method end
  15628. */
  15629. PIXI.WebGLSpriteBatch.prototype.end = function()
  15630. {
  15631. this.flush();
  15632. };
  15633. /**
  15634. * @method render
  15635. * @param sprite {Sprite} the sprite to render when using this spritebatch
  15636. * @param {Matrix} [matrix] - Optional matrix. If provided the Display Object will be rendered using this matrix, otherwise it will use its worldTransform.
  15637. */
  15638. PIXI.WebGLSpriteBatch.prototype.render = function(sprite, matrix)
  15639. {
  15640. var texture = sprite.texture;
  15641. // They provided an alternative rendering matrix, so use it
  15642. var wt = sprite.worldTransform;
  15643. if (matrix)
  15644. {
  15645. wt = matrix;
  15646. }
  15647. // check texture..
  15648. if (this.currentBatchSize >= this.size)
  15649. {
  15650. this.flush();
  15651. this.currentBaseTexture = texture.baseTexture;
  15652. }
  15653. // get the uvs for the texture
  15654. var uvs = texture._uvs;
  15655. // if the uvs have not updated then no point rendering just yet!
  15656. if (!uvs)
  15657. {
  15658. return;
  15659. }
  15660. var aX = sprite.anchor.x;
  15661. var aY = sprite.anchor.y;
  15662. var w0, w1, h0, h1;
  15663. if (texture.trim)
  15664. {
  15665. // if the sprite is trimmed then we need to add the extra space before transforming the sprite coords.
  15666. var trim = texture.trim;
  15667. w1 = trim.x - aX * trim.width;
  15668. w0 = w1 + texture.crop.width;
  15669. h1 = trim.y - aY * trim.height;
  15670. h0 = h1 + texture.crop.height;
  15671. }
  15672. else
  15673. {
  15674. w0 = (texture.frame.width) * (1-aX);
  15675. w1 = (texture.frame.width) * -aX;
  15676. h0 = texture.frame.height * (1-aY);
  15677. h1 = texture.frame.height * -aY;
  15678. }
  15679. var i = this.currentBatchSize * 4 * this.vertSize;
  15680. var resolution = texture.baseTexture.resolution;
  15681. var a = wt.a / resolution;
  15682. var b = wt.b / resolution;
  15683. var c = wt.c / resolution;
  15684. var d = wt.d / resolution;
  15685. var tx = wt.tx;
  15686. var ty = wt.ty;
  15687. var colors = this.colors;
  15688. var positions = this.positions;
  15689. if (this.renderSession.roundPixels)
  15690. {
  15691. // xy
  15692. positions[i] = a * w1 + c * h1 + tx | 0;
  15693. positions[i+1] = d * h1 + b * w1 + ty | 0;
  15694. // xy
  15695. positions[i+5] = a * w0 + c * h1 + tx | 0;
  15696. positions[i+6] = d * h1 + b * w0 + ty | 0;
  15697. // xy
  15698. positions[i+10] = a * w0 + c * h0 + tx | 0;
  15699. positions[i+11] = d * h0 + b * w0 + ty | 0;
  15700. // xy
  15701. positions[i+15] = a * w1 + c * h0 + tx | 0;
  15702. positions[i+16] = d * h0 + b * w1 + ty | 0;
  15703. }
  15704. else
  15705. {
  15706. // xy
  15707. positions[i] = a * w1 + c * h1 + tx;
  15708. positions[i+1] = d * h1 + b * w1 + ty;
  15709. // xy
  15710. positions[i+5] = a * w0 + c * h1 + tx;
  15711. positions[i+6] = d * h1 + b * w0 + ty;
  15712. // xy
  15713. positions[i+10] = a * w0 + c * h0 + tx;
  15714. positions[i+11] = d * h0 + b * w0 + ty;
  15715. // xy
  15716. positions[i+15] = a * w1 + c * h0 + tx;
  15717. positions[i+16] = d * h0 + b * w1 + ty;
  15718. }
  15719. // uv
  15720. positions[i+2] = uvs.x0;
  15721. positions[i+3] = uvs.y0;
  15722. // uv
  15723. positions[i+7] = uvs.x1;
  15724. positions[i+8] = uvs.y1;
  15725. // uv
  15726. positions[i+12] = uvs.x2;
  15727. positions[i+13] = uvs.y2;
  15728. // uv
  15729. positions[i+17] = uvs.x3;
  15730. positions[i+18] = uvs.y3;
  15731. // color and alpha
  15732. var tint = sprite.tint;
  15733. colors[i+4] = colors[i+9] = colors[i+14] = colors[i+19] = (tint >> 16) + (tint & 0xff00) + ((tint & 0xff) << 16) + (sprite.worldAlpha * 255 << 24);
  15734. // increment the batchsize
  15735. this.sprites[this.currentBatchSize++] = sprite;
  15736. };
  15737. /**
  15738. * Renders a TilingSprite using the spriteBatch.
  15739. *
  15740. * @method renderTilingSprite
  15741. * @param sprite {TilingSprite} the sprite to render
  15742. */
  15743. PIXI.WebGLSpriteBatch.prototype.renderTilingSprite = function(sprite)
  15744. {
  15745. var texture = sprite.tilingTexture;
  15746. // check texture..
  15747. if (this.currentBatchSize >= this.size)
  15748. {
  15749. this.flush();
  15750. this.currentBaseTexture = texture.baseTexture;
  15751. }
  15752. // set the textures uvs temporarily
  15753. if (!sprite._uvs)
  15754. {
  15755. sprite._uvs = new PIXI.TextureUvs();
  15756. }
  15757. var uvs = sprite._uvs;
  15758. var w = texture.baseTexture.width;
  15759. var h = texture.baseTexture.height;
  15760. // var w = sprite._frame.sourceSizeW;
  15761. // var h = sprite._frame.sourceSizeH;
  15762. // w = 16;
  15763. // h = 16;
  15764. sprite.tilePosition.x %= w * sprite.tileScaleOffset.x;
  15765. sprite.tilePosition.y %= h * sprite.tileScaleOffset.y;
  15766. var offsetX = sprite.tilePosition.x / (w * sprite.tileScaleOffset.x);
  15767. var offsetY = sprite.tilePosition.y / (h * sprite.tileScaleOffset.y);
  15768. var scaleX = (sprite.width / w) / (sprite.tileScale.x * sprite.tileScaleOffset.x);
  15769. var scaleY = (sprite.height / h) / (sprite.tileScale.y * sprite.tileScaleOffset.y);
  15770. uvs.x0 = 0 - offsetX;
  15771. uvs.y0 = 0 - offsetY;
  15772. uvs.x1 = (1 * scaleX) - offsetX;
  15773. uvs.y1 = 0 - offsetY;
  15774. uvs.x2 = (1 * scaleX) - offsetX;
  15775. uvs.y2 = (1 * scaleY) - offsetY;
  15776. uvs.x3 = 0 - offsetX;
  15777. uvs.y3 = (1 * scaleY) - offsetY;
  15778. // Get the sprites current alpha and tint and combine them into a single color
  15779. var tint = sprite.tint;
  15780. var color = (tint >> 16) + (tint & 0xff00) + ((tint & 0xff) << 16) + (sprite.worldAlpha * 255 << 24);
  15781. var positions = this.positions;
  15782. var colors = this.colors;
  15783. var width = sprite.width;
  15784. var height = sprite.height;
  15785. // TODO trim??
  15786. var aX = sprite.anchor.x;
  15787. var aY = sprite.anchor.y;
  15788. var w0 = width * (1-aX);
  15789. var w1 = width * -aX;
  15790. var h0 = height * (1-aY);
  15791. var h1 = height * -aY;
  15792. var i = this.currentBatchSize * 4 * this.vertSize;
  15793. var resolution = texture.baseTexture.resolution;
  15794. var wt = sprite.worldTransform;
  15795. var a = wt.a / resolution;
  15796. var b = wt.b / resolution;
  15797. var c = wt.c / resolution;
  15798. var d = wt.d / resolution;
  15799. var tx = wt.tx;
  15800. var ty = wt.ty;
  15801. // xy
  15802. positions[i++] = a * w1 + c * h1 + tx;
  15803. positions[i++] = d * h1 + b * w1 + ty;
  15804. // uv
  15805. positions[i++] = uvs.x0;
  15806. positions[i++] = uvs.y0;
  15807. // color
  15808. colors[i++] = color;
  15809. // xy
  15810. positions[i++] = (a * w0 + c * h1 + tx);
  15811. positions[i++] = d * h1 + b * w0 + ty;
  15812. // uv
  15813. positions[i++] = uvs.x1;
  15814. positions[i++] = uvs.y1;
  15815. // color
  15816. colors[i++] = color;
  15817. // xy
  15818. positions[i++] = a * w0 + c * h0 + tx;
  15819. positions[i++] = d * h0 + b * w0 + ty;
  15820. // uv
  15821. positions[i++] = uvs.x2;
  15822. positions[i++] = uvs.y2;
  15823. // color
  15824. colors[i++] = color;
  15825. // xy
  15826. positions[i++] = a * w1 + c * h0 + tx;
  15827. positions[i++] = d * h0 + b * w1 + ty;
  15828. // uv
  15829. positions[i++] = uvs.x3;
  15830. positions[i++] = uvs.y3;
  15831. // color
  15832. colors[i++] = color;
  15833. // increment the batchsize
  15834. this.sprites[this.currentBatchSize++] = sprite;
  15835. };
  15836. /**
  15837. * Renders the content and empties the current batch.
  15838. *
  15839. * @method flush
  15840. */
  15841. PIXI.WebGLSpriteBatch.prototype.flush = function()
  15842. {
  15843. // If the batch is length 0 then return as there is nothing to draw
  15844. if (this.currentBatchSize === 0)
  15845. {
  15846. return;
  15847. }
  15848. var gl = this.gl;
  15849. var shader;
  15850. if (this.dirty)
  15851. {
  15852. this.dirty = false;
  15853. // bind the main texture
  15854. gl.activeTexture(gl.TEXTURE0);
  15855. // bind the buffers
  15856. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  15857. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
  15858. shader = this.defaultShader.shaders[gl.id];
  15859. // this is the same for each shader?
  15860. var stride = this.vertSize * 4;
  15861. gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, stride, 0);
  15862. gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, stride, 2 * 4);
  15863. // color attributes will be interpreted as unsigned bytes and normalized
  15864. gl.vertexAttribPointer(shader.colorAttribute, 4, gl.UNSIGNED_BYTE, true, stride, 4 * 4);
  15865. }
  15866. // upload the verts to the buffer
  15867. if (this.currentBatchSize > (this.size * 0.5))
  15868. {
  15869. gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices);
  15870. }
  15871. else
  15872. {
  15873. var view = this.positions.subarray(0, this.currentBatchSize * 4 * this.vertSize);
  15874. gl.bufferSubData(gl.ARRAY_BUFFER, 0, view);
  15875. }
  15876. var nextTexture, nextBlendMode, nextShader;
  15877. var batchSize = 0;
  15878. var start = 0;
  15879. var currentBaseTexture = null;
  15880. var currentBlendMode = this.renderSession.blendModeManager.currentBlendMode;
  15881. var currentShader = null;
  15882. var blendSwap = false;
  15883. var shaderSwap = false;
  15884. var sprite;
  15885. for (var i = 0, j = this.currentBatchSize; i < j; i++) {
  15886. sprite = this.sprites[i];
  15887. if (sprite.tilingTexture)
  15888. {
  15889. nextTexture = sprite.tilingTexture.baseTexture;
  15890. }
  15891. else
  15892. {
  15893. nextTexture = sprite.texture.baseTexture;
  15894. }
  15895. nextBlendMode = sprite.blendMode;
  15896. nextShader = sprite.shader || this.defaultShader;
  15897. blendSwap = currentBlendMode !== nextBlendMode;
  15898. shaderSwap = currentShader !== nextShader; // should I use _UIDS???
  15899. var skip = nextTexture.skipRender;
  15900. if (skip && sprite.children.length > 0)
  15901. {
  15902. skip = false;
  15903. }
  15904. if ((currentBaseTexture !== nextTexture && !skip) || blendSwap || shaderSwap)
  15905. {
  15906. this.renderBatch(currentBaseTexture, batchSize, start);
  15907. start = i;
  15908. batchSize = 0;
  15909. currentBaseTexture = nextTexture;
  15910. if (blendSwap)
  15911. {
  15912. currentBlendMode = nextBlendMode;
  15913. this.renderSession.blendModeManager.setBlendMode(currentBlendMode);
  15914. }
  15915. if (shaderSwap)
  15916. {
  15917. currentShader = nextShader;
  15918. shader = currentShader.shaders[gl.id];
  15919. if (!shader)
  15920. {
  15921. shader = new PIXI.PixiShader(gl);
  15922. shader.fragmentSrc = currentShader.fragmentSrc;
  15923. shader.uniforms = currentShader.uniforms;
  15924. shader.init();
  15925. currentShader.shaders[gl.id] = shader;
  15926. }
  15927. // set shader function???
  15928. this.renderSession.shaderManager.setShader(shader);
  15929. if (shader.dirty)
  15930. {
  15931. shader.syncUniforms();
  15932. }
  15933. // both these only need to be set if they are changing..
  15934. // set the projection
  15935. var projection = this.renderSession.projection;
  15936. gl.uniform2f(shader.projectionVector, projection.x, projection.y);
  15937. // TODO - this is temporary!
  15938. var offsetVector = this.renderSession.offset;
  15939. gl.uniform2f(shader.offsetVector, offsetVector.x, offsetVector.y);
  15940. // set the pointers
  15941. }
  15942. }
  15943. batchSize++;
  15944. }
  15945. this.renderBatch(currentBaseTexture, batchSize, start);
  15946. // then reset the batch!
  15947. this.currentBatchSize = 0;
  15948. };
  15949. /**
  15950. * @method renderBatch
  15951. * @param texture {Texture}
  15952. * @param size {Number}
  15953. * @param startIndex {Number}
  15954. */
  15955. PIXI.WebGLSpriteBatch.prototype.renderBatch = function(texture, size, startIndex)
  15956. {
  15957. if (size === 0)
  15958. {
  15959. return;
  15960. }
  15961. var gl = this.gl;
  15962. // check if a texture is dirty..
  15963. if (texture._dirty[gl.id])
  15964. {
  15965. if (!this.renderSession.renderer.updateTexture(texture))
  15966. {
  15967. // If updateTexture returns false then we cannot render it, so bail out now
  15968. return;
  15969. }
  15970. }
  15971. else
  15972. {
  15973. // bind the current texture
  15974. gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]);
  15975. }
  15976. // now draw those suckas!
  15977. gl.drawElements(gl.TRIANGLES, size * 6, gl.UNSIGNED_SHORT, startIndex * 6 * 2);
  15978. // increment the draw count
  15979. this.renderSession.drawCount++;
  15980. };
  15981. /**
  15982. * @method stop
  15983. */
  15984. PIXI.WebGLSpriteBatch.prototype.stop = function()
  15985. {
  15986. this.flush();
  15987. this.dirty = true;
  15988. };
  15989. /**
  15990. * @method start
  15991. */
  15992. PIXI.WebGLSpriteBatch.prototype.start = function()
  15993. {
  15994. this.dirty = true;
  15995. };
  15996. /**
  15997. * Destroys the SpriteBatch.
  15998. *
  15999. * @method destroy
  16000. */
  16001. PIXI.WebGLSpriteBatch.prototype.destroy = function()
  16002. {
  16003. this.vertices = null;
  16004. this.indices = null;
  16005. this.gl.deleteBuffer(this.vertexBuffer);
  16006. this.gl.deleteBuffer(this.indexBuffer);
  16007. this.currentBaseTexture = null;
  16008. this.gl = null;
  16009. };
  16010. /**
  16011. * @author Mat Groves
  16012. *
  16013. * Big thanks to the very clever Matt DesLauriers <mattdesl> https://github.com/mattdesl/
  16014. * for creating the original pixi version!
  16015. *
  16016. * Heavily inspired by LibGDX's WebGLSpriteBatch:
  16017. * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/WebGLSpriteBatch.java
  16018. */
  16019. /**
  16020. * @class WebGLFastSpriteBatch
  16021. * @constructor
  16022. */
  16023. PIXI.WebGLFastSpriteBatch = function(gl)
  16024. {
  16025. /**
  16026. * @property vertSize
  16027. * @type Number
  16028. */
  16029. this.vertSize = 10;
  16030. /**
  16031. * @property maxSize
  16032. * @type Number
  16033. */
  16034. this.maxSize = 6000;//Math.pow(2, 16) / this.vertSize;
  16035. /**
  16036. * @property size
  16037. * @type Number
  16038. */
  16039. this.size = this.maxSize;
  16040. //the total number of floats in our batch
  16041. var numVerts = this.size * 4 * this.vertSize;
  16042. //the total number of indices in our batch
  16043. var numIndices = this.maxSize * 6;
  16044. /**
  16045. * Vertex data
  16046. * @property vertices
  16047. * @type Float32Array
  16048. */
  16049. this.vertices = new PIXI.Float32Array(numVerts);
  16050. /**
  16051. * Index data
  16052. * @property indices
  16053. * @type Uint16Array
  16054. */
  16055. this.indices = new PIXI.Uint16Array(numIndices);
  16056. /**
  16057. * @property vertexBuffer
  16058. * @type Object
  16059. */
  16060. this.vertexBuffer = null;
  16061. /**
  16062. * @property indexBuffer
  16063. * @type Object
  16064. */
  16065. this.indexBuffer = null;
  16066. /**
  16067. * @property lastIndexCount
  16068. * @type Number
  16069. */
  16070. this.lastIndexCount = 0;
  16071. for (var i=0, j=0; i < numIndices; i += 6, j += 4)
  16072. {
  16073. this.indices[i + 0] = j + 0;
  16074. this.indices[i + 1] = j + 1;
  16075. this.indices[i + 2] = j + 2;
  16076. this.indices[i + 3] = j + 0;
  16077. this.indices[i + 4] = j + 2;
  16078. this.indices[i + 5] = j + 3;
  16079. }
  16080. /**
  16081. * @property drawing
  16082. * @type Boolean
  16083. */
  16084. this.drawing = false;
  16085. /**
  16086. * @property currentBatchSize
  16087. * @type Number
  16088. */
  16089. this.currentBatchSize = 0;
  16090. /**
  16091. * @property currentBaseTexture
  16092. * @type BaseTexture
  16093. */
  16094. this.currentBaseTexture = null;
  16095. /**
  16096. * @property currentBlendMode
  16097. * @type Number
  16098. */
  16099. this.currentBlendMode = 0;
  16100. /**
  16101. * @property renderSession
  16102. * @type Object
  16103. */
  16104. this.renderSession = null;
  16105. /**
  16106. * @property shader
  16107. * @type Object
  16108. */
  16109. this.shader = null;
  16110. /**
  16111. * @property matrix
  16112. * @type Matrix
  16113. */
  16114. this.matrix = null;
  16115. this.setContext(gl);
  16116. };
  16117. PIXI.WebGLFastSpriteBatch.prototype.constructor = PIXI.WebGLFastSpriteBatch;
  16118. /**
  16119. * Sets the WebGL Context.
  16120. *
  16121. * @method setContext
  16122. * @param gl {WebGLContext} the current WebGL drawing context
  16123. */
  16124. PIXI.WebGLFastSpriteBatch.prototype.setContext = function(gl)
  16125. {
  16126. this.gl = gl;
  16127. // create a couple of buffers
  16128. this.vertexBuffer = gl.createBuffer();
  16129. this.indexBuffer = gl.createBuffer();
  16130. // 65535 is max index, so 65535 / 6 = 10922.
  16131. //upload the index data
  16132. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
  16133. gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW);
  16134. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  16135. gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.DYNAMIC_DRAW);
  16136. };
  16137. /**
  16138. * @method begin
  16139. * @param spriteBatch {WebGLSpriteBatch}
  16140. * @param renderSession {Object}
  16141. */
  16142. PIXI.WebGLFastSpriteBatch.prototype.begin = function(spriteBatch, renderSession)
  16143. {
  16144. this.renderSession = renderSession;
  16145. this.shader = this.renderSession.shaderManager.fastShader;
  16146. this.matrix = spriteBatch.worldTransform.toArray(true);
  16147. this.start();
  16148. };
  16149. /**
  16150. * @method end
  16151. */
  16152. PIXI.WebGLFastSpriteBatch.prototype.end = function()
  16153. {
  16154. this.flush();
  16155. };
  16156. /**
  16157. * @method render
  16158. * @param spriteBatch {WebGLSpriteBatch}
  16159. */
  16160. PIXI.WebGLFastSpriteBatch.prototype.render = function(spriteBatch)
  16161. {
  16162. var children = spriteBatch.children;
  16163. var sprite = children[0];
  16164. // if the uvs have not updated then no point rendering just yet!
  16165. // check texture.
  16166. if(!sprite.texture._uvs)return;
  16167. this.currentBaseTexture = sprite.texture.baseTexture;
  16168. // check blend mode
  16169. if(sprite.blendMode !== this.renderSession.blendModeManager.currentBlendMode)
  16170. {
  16171. this.flush();
  16172. this.renderSession.blendModeManager.setBlendMode(sprite.blendMode);
  16173. }
  16174. for(var i=0,j= children.length; i<j; i++)
  16175. {
  16176. this.renderSprite(children[i]);
  16177. }
  16178. this.flush();
  16179. };
  16180. /**
  16181. * @method renderSprite
  16182. * @param sprite {Sprite}
  16183. */
  16184. PIXI.WebGLFastSpriteBatch.prototype.renderSprite = function(sprite)
  16185. {
  16186. //sprite = children[i];
  16187. if(!sprite.visible)return;
  16188. // TODO trim??
  16189. if(sprite.texture.baseTexture !== this.currentBaseTexture && !sprite.texture.baseTexture.skipRender)
  16190. {
  16191. this.flush();
  16192. this.currentBaseTexture = sprite.texture.baseTexture;
  16193. if(!sprite.texture._uvs)return;
  16194. }
  16195. var uvs, vertices = this.vertices, width, height, w0, w1, h0, h1, index;
  16196. uvs = sprite.texture._uvs;
  16197. width = sprite.texture.frame.width;
  16198. height = sprite.texture.frame.height;
  16199. if (sprite.texture.trim)
  16200. {
  16201. // if the sprite is trimmed then we need to add the extra space before transforming the sprite coords..
  16202. var trim = sprite.texture.trim;
  16203. w1 = trim.x - sprite.anchor.x * trim.width;
  16204. w0 = w1 + sprite.texture.crop.width;
  16205. h1 = trim.y - sprite.anchor.y * trim.height;
  16206. h0 = h1 + sprite.texture.crop.height;
  16207. }
  16208. else
  16209. {
  16210. w0 = (sprite.texture.frame.width ) * (1-sprite.anchor.x);
  16211. w1 = (sprite.texture.frame.width ) * -sprite.anchor.x;
  16212. h0 = sprite.texture.frame.height * (1-sprite.anchor.y);
  16213. h1 = sprite.texture.frame.height * -sprite.anchor.y;
  16214. }
  16215. index = this.currentBatchSize * 4 * this.vertSize;
  16216. // xy
  16217. vertices[index++] = w1;
  16218. vertices[index++] = h1;
  16219. vertices[index++] = sprite.position.x;
  16220. vertices[index++] = sprite.position.y;
  16221. //scale
  16222. vertices[index++] = sprite.scale.x;
  16223. vertices[index++] = sprite.scale.y;
  16224. //rotation
  16225. vertices[index++] = sprite.rotation;
  16226. // uv
  16227. vertices[index++] = uvs.x0;
  16228. vertices[index++] = uvs.y1;
  16229. // color
  16230. vertices[index++] = sprite.alpha;
  16231. // xy
  16232. vertices[index++] = w0;
  16233. vertices[index++] = h1;
  16234. vertices[index++] = sprite.position.x;
  16235. vertices[index++] = sprite.position.y;
  16236. //scale
  16237. vertices[index++] = sprite.scale.x;
  16238. vertices[index++] = sprite.scale.y;
  16239. //rotation
  16240. vertices[index++] = sprite.rotation;
  16241. // uv
  16242. vertices[index++] = uvs.x1;
  16243. vertices[index++] = uvs.y1;
  16244. // color
  16245. vertices[index++] = sprite.alpha;
  16246. // xy
  16247. vertices[index++] = w0;
  16248. vertices[index++] = h0;
  16249. vertices[index++] = sprite.position.x;
  16250. vertices[index++] = sprite.position.y;
  16251. //scale
  16252. vertices[index++] = sprite.scale.x;
  16253. vertices[index++] = sprite.scale.y;
  16254. //rotation
  16255. vertices[index++] = sprite.rotation;
  16256. // uv
  16257. vertices[index++] = uvs.x2;
  16258. vertices[index++] = uvs.y2;
  16259. // color
  16260. vertices[index++] = sprite.alpha;
  16261. // xy
  16262. vertices[index++] = w1;
  16263. vertices[index++] = h0;
  16264. vertices[index++] = sprite.position.x;
  16265. vertices[index++] = sprite.position.y;
  16266. //scale
  16267. vertices[index++] = sprite.scale.x;
  16268. vertices[index++] = sprite.scale.y;
  16269. //rotation
  16270. vertices[index++] = sprite.rotation;
  16271. // uv
  16272. vertices[index++] = uvs.x3;
  16273. vertices[index++] = uvs.y3;
  16274. // color
  16275. vertices[index++] = sprite.alpha;
  16276. // increment the batchs
  16277. this.currentBatchSize++;
  16278. if(this.currentBatchSize >= this.size)
  16279. {
  16280. this.flush();
  16281. }
  16282. };
  16283. /**
  16284. * @method flush
  16285. */
  16286. PIXI.WebGLFastSpriteBatch.prototype.flush = function()
  16287. {
  16288. // If the batch is length 0 then return as there is nothing to draw
  16289. if (this.currentBatchSize===0)return;
  16290. var gl = this.gl;
  16291. // bind the current texture
  16292. if(!this.currentBaseTexture._glTextures[gl.id])this.renderSession.renderer.updateTexture(this.currentBaseTexture, gl);
  16293. gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]);
  16294. // upload the verts to the buffer
  16295. if(this.currentBatchSize > ( this.size * 0.5 ) )
  16296. {
  16297. gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices);
  16298. }
  16299. else
  16300. {
  16301. var view = this.vertices.subarray(0, this.currentBatchSize * 4 * this.vertSize);
  16302. gl.bufferSubData(gl.ARRAY_BUFFER, 0, view);
  16303. }
  16304. // now draw those suckas!
  16305. gl.drawElements(gl.TRIANGLES, this.currentBatchSize * 6, gl.UNSIGNED_SHORT, 0);
  16306. // then reset the batch!
  16307. this.currentBatchSize = 0;
  16308. // increment the draw count
  16309. this.renderSession.drawCount++;
  16310. };
  16311. /**
  16312. * @method stop
  16313. */
  16314. PIXI.WebGLFastSpriteBatch.prototype.stop = function()
  16315. {
  16316. this.flush();
  16317. };
  16318. /**
  16319. * @method start
  16320. */
  16321. PIXI.WebGLFastSpriteBatch.prototype.start = function()
  16322. {
  16323. var gl = this.gl;
  16324. // bind the main texture
  16325. gl.activeTexture(gl.TEXTURE0);
  16326. // bind the buffers
  16327. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  16328. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
  16329. // set the projection
  16330. var projection = this.renderSession.projection;
  16331. gl.uniform2f(this.shader.projectionVector, projection.x, projection.y);
  16332. // set the matrix
  16333. gl.uniformMatrix3fv(this.shader.uMatrix, false, this.matrix);
  16334. // set the pointers
  16335. var stride = this.vertSize * 4;
  16336. gl.vertexAttribPointer(this.shader.aVertexPosition, 2, gl.FLOAT, false, stride, 0);
  16337. gl.vertexAttribPointer(this.shader.aPositionCoord, 2, gl.FLOAT, false, stride, 2 * 4);
  16338. gl.vertexAttribPointer(this.shader.aScale, 2, gl.FLOAT, false, stride, 4 * 4);
  16339. gl.vertexAttribPointer(this.shader.aRotation, 1, gl.FLOAT, false, stride, 6 * 4);
  16340. gl.vertexAttribPointer(this.shader.aTextureCoord, 2, gl.FLOAT, false, stride, 7 * 4);
  16341. gl.vertexAttribPointer(this.shader.colorAttribute, 1, gl.FLOAT, false, stride, 9 * 4);
  16342. };
  16343. /**
  16344. * @author Mat Groves http://matgroves.com/ @Doormat23
  16345. */
  16346. /**
  16347. * @class WebGLFilterManager
  16348. * @constructor
  16349. */
  16350. PIXI.WebGLFilterManager = function()
  16351. {
  16352. /**
  16353. * @property filterStack
  16354. * @type Array
  16355. */
  16356. this.filterStack = [];
  16357. /**
  16358. * @property offsetX
  16359. * @type Number
  16360. */
  16361. this.offsetX = 0;
  16362. /**
  16363. * @property offsetY
  16364. * @type Number
  16365. */
  16366. this.offsetY = 0;
  16367. };
  16368. PIXI.WebGLFilterManager.prototype.constructor = PIXI.WebGLFilterManager;
  16369. /**
  16370. * Initialises the context and the properties.
  16371. *
  16372. * @method setContext
  16373. * @param gl {WebGLContext} the current WebGL drawing context
  16374. */
  16375. PIXI.WebGLFilterManager.prototype.setContext = function(gl)
  16376. {
  16377. this.gl = gl;
  16378. this.texturePool = [];
  16379. this.initShaderBuffers();
  16380. };
  16381. /**
  16382. * @method begin
  16383. * @param renderSession {RenderSession}
  16384. * @param buffer {ArrayBuffer}
  16385. */
  16386. PIXI.WebGLFilterManager.prototype.begin = function(renderSession, buffer)
  16387. {
  16388. this.renderSession = renderSession;
  16389. this.defaultShader = renderSession.shaderManager.defaultShader;
  16390. var projection = this.renderSession.projection;
  16391. this.width = projection.x * 2;
  16392. this.height = -projection.y * 2;
  16393. this.buffer = buffer;
  16394. };
  16395. /**
  16396. * Applies the filter and adds it to the current filter stack.
  16397. *
  16398. * @method pushFilter
  16399. * @param filterBlock {Object} the filter that will be pushed to the current filter stack
  16400. */
  16401. PIXI.WebGLFilterManager.prototype.pushFilter = function(filterBlock)
  16402. {
  16403. var gl = this.gl;
  16404. var projection = this.renderSession.projection;
  16405. var offset = this.renderSession.offset;
  16406. filterBlock._filterArea = filterBlock.target.filterArea || filterBlock.target.getBounds();
  16407. // >>> modify by nextht
  16408. filterBlock._previous_stencil_mgr = this.renderSession.stencilManager;
  16409. this.renderSession.stencilManager = new PIXI.WebGLStencilManager();
  16410. this.renderSession.stencilManager.setContext(gl);
  16411. gl.disable(gl.STENCIL_TEST);
  16412. // <<< modify by nextht
  16413. // filter program
  16414. // OPTIMISATION - the first filter is free if its a simple color change?
  16415. this.filterStack.push(filterBlock);
  16416. var filter = filterBlock.filterPasses[0];
  16417. this.offsetX += filterBlock._filterArea.x;
  16418. this.offsetY += filterBlock._filterArea.y;
  16419. var texture = this.texturePool.pop();
  16420. if(!texture)
  16421. {
  16422. texture = new PIXI.FilterTexture(this.gl, this.width * this.renderSession.resolution, this.height * this.renderSession.resolution);
  16423. }
  16424. else
  16425. {
  16426. texture.resize(this.width * this.renderSession.resolution, this.height * this.renderSession.resolution);
  16427. }
  16428. gl.bindTexture(gl.TEXTURE_2D, texture.texture);
  16429. var filterArea = filterBlock._filterArea;// filterBlock.target.getBounds();///filterBlock.target.filterArea;
  16430. var padding = filter.padding;
  16431. filterArea.x -= padding;
  16432. filterArea.y -= padding;
  16433. filterArea.width += padding * 2;
  16434. filterArea.height += padding * 2;
  16435. // cap filter to screen size..
  16436. if(filterArea.x < 0)filterArea.x = 0;
  16437. if(filterArea.width > this.width)filterArea.width = this.width;
  16438. if(filterArea.y < 0)filterArea.y = 0;
  16439. if(filterArea.height > this.height)filterArea.height = this.height;
  16440. //gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, filterArea.width, filterArea.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  16441. gl.bindFramebuffer(gl.FRAMEBUFFER, texture.frameBuffer);
  16442. // set view port
  16443. gl.viewport(0, 0, filterArea.width * this.renderSession.resolution, filterArea.height * this.renderSession.resolution);
  16444. projection.x = filterArea.width/2;
  16445. projection.y = -filterArea.height/2;
  16446. offset.x = -filterArea.x;
  16447. offset.y = -filterArea.y;
  16448. // update projection
  16449. // now restore the regular shader..
  16450. // this.renderSession.shaderManager.setShader(this.defaultShader);
  16451. //gl.uniform2f(this.defaultShader.projectionVector, filterArea.width/2, -filterArea.height/2);
  16452. //gl.uniform2f(this.defaultShader.offsetVector, -filterArea.x, -filterArea.y);
  16453. gl.colorMask(true, true, true, true);
  16454. gl.clearColor(0,0,0, 0);
  16455. gl.clear(gl.COLOR_BUFFER_BIT);
  16456. filterBlock._glFilterTexture = texture;
  16457. };
  16458. /**
  16459. * Removes the last filter from the filter stack and doesn't return it.
  16460. *
  16461. * @method popFilter
  16462. */
  16463. PIXI.WebGLFilterManager.prototype.popFilter = function()
  16464. {
  16465. var gl = this.gl;
  16466. var filterBlock = this.filterStack.pop();
  16467. var filterArea = filterBlock._filterArea;
  16468. var texture = filterBlock._glFilterTexture;
  16469. var projection = this.renderSession.projection;
  16470. var offset = this.renderSession.offset;
  16471. if(filterBlock.filterPasses.length > 1)
  16472. {
  16473. gl.viewport(0, 0, filterArea.width * this.renderSession.resolution, filterArea.height * this.renderSession.resolution);
  16474. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  16475. this.vertexArray[0] = 0;
  16476. this.vertexArray[1] = filterArea.height;
  16477. this.vertexArray[2] = filterArea.width;
  16478. this.vertexArray[3] = filterArea.height;
  16479. this.vertexArray[4] = 0;
  16480. this.vertexArray[5] = 0;
  16481. this.vertexArray[6] = filterArea.width;
  16482. this.vertexArray[7] = 0;
  16483. gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertexArray);
  16484. gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer);
  16485. // now set the uvs..
  16486. this.uvArray[2] = filterArea.width/this.width;
  16487. this.uvArray[5] = filterArea.height/this.height;
  16488. this.uvArray[6] = filterArea.width/this.width;
  16489. this.uvArray[7] = filterArea.height/this.height;
  16490. gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.uvArray);
  16491. var inputTexture = texture;
  16492. var outputTexture = this.texturePool.pop();
  16493. if(!outputTexture)outputTexture = new PIXI.FilterTexture(this.gl, this.width * this.renderSession.resolution, this.height * this.renderSession.resolution);
  16494. outputTexture.resize(this.width * this.renderSession.resolution, this.height * this.renderSession.resolution);
  16495. // need to clear this FBO as it may have some left over elements from a previous filter.
  16496. gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer );
  16497. gl.clear(gl.COLOR_BUFFER_BIT);
  16498. gl.disable(gl.BLEND);
  16499. for (var i = 0; i < filterBlock.filterPasses.length-1; i++)
  16500. {
  16501. var filterPass = filterBlock.filterPasses[i];
  16502. gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer );
  16503. // set texture
  16504. gl.activeTexture(gl.TEXTURE0);
  16505. gl.bindTexture(gl.TEXTURE_2D, inputTexture.texture);
  16506. // draw texture..
  16507. //filterPass.applyFilterPass(filterArea.width, filterArea.height);
  16508. this.applyFilterPass(filterPass, filterArea, filterArea.width, filterArea.height);
  16509. // swap the textures..
  16510. var temp = inputTexture;
  16511. inputTexture = outputTexture;
  16512. outputTexture = temp;
  16513. }
  16514. gl.enable(gl.BLEND);
  16515. texture = inputTexture;
  16516. this.texturePool.push(outputTexture);
  16517. }
  16518. var filter = filterBlock.filterPasses[filterBlock.filterPasses.length-1];
  16519. this.offsetX -= filterArea.x;
  16520. this.offsetY -= filterArea.y;
  16521. var sizeX = this.width;
  16522. var sizeY = this.height;
  16523. var offsetX = 0;
  16524. var offsetY = 0;
  16525. var buffer = this.buffer;
  16526. // time to render the filters texture to the previous scene
  16527. if(this.filterStack.length === 0)
  16528. {
  16529. gl.colorMask(true, true, true, true);//this.transparent);
  16530. }
  16531. else
  16532. {
  16533. var currentFilter = this.filterStack[this.filterStack.length-1];
  16534. filterArea = currentFilter._filterArea;
  16535. sizeX = filterArea.width;
  16536. sizeY = filterArea.height;
  16537. offsetX = filterArea.x;
  16538. offsetY = filterArea.y;
  16539. buffer = currentFilter._glFilterTexture.frameBuffer;
  16540. }
  16541. // TODO need to remove these global elements..
  16542. projection.x = sizeX/2;
  16543. projection.y = -sizeY/2;
  16544. offset.x = offsetX;
  16545. offset.y = offsetY;
  16546. filterArea = filterBlock._filterArea;
  16547. var x = filterArea.x-offsetX;
  16548. var y = filterArea.y-offsetY;
  16549. // update the buffers..
  16550. // make sure to flip the y!
  16551. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  16552. this.vertexArray[0] = x;
  16553. this.vertexArray[1] = y + filterArea.height;
  16554. this.vertexArray[2] = x + filterArea.width;
  16555. this.vertexArray[3] = y + filterArea.height;
  16556. this.vertexArray[4] = x;
  16557. this.vertexArray[5] = y;
  16558. this.vertexArray[6] = x + filterArea.width;
  16559. this.vertexArray[7] = y;
  16560. gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertexArray);
  16561. gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer);
  16562. this.uvArray[2] = filterArea.width/this.width;
  16563. this.uvArray[5] = filterArea.height/this.height;
  16564. this.uvArray[6] = filterArea.width/this.width;
  16565. this.uvArray[7] = filterArea.height/this.height;
  16566. gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.uvArray);
  16567. gl.viewport(0, 0, sizeX * this.renderSession.resolution, sizeY * this.renderSession.resolution);
  16568. // bind the buffer
  16569. gl.bindFramebuffer(gl.FRAMEBUFFER, buffer );
  16570. // set the blend mode!
  16571. //gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA)
  16572. // set texture
  16573. gl.activeTexture(gl.TEXTURE0);
  16574. gl.bindTexture(gl.TEXTURE_2D, texture.texture);
  16575. // >>> modify by nextht
  16576. if (this.renderSession.stencilManager) {
  16577. this.renderSession.stencilManager.destroy();
  16578. }
  16579. this.renderSession.stencilManager = filterBlock._previous_stencil_mgr;
  16580. filterBlock._previous_stencil_mgr = null;
  16581. if (this.renderSession.stencilManager.count > 0) {
  16582. gl.enable(gl.STENCIL_TEST);
  16583. }
  16584. else {
  16585. gl.disable(gl.STENCIL_TEST);
  16586. }
  16587. // <<< modify by nextht
  16588. // apply!
  16589. this.applyFilterPass(filter, filterArea, sizeX, sizeY);
  16590. // now restore the regular shader.. should happen automatically now..
  16591. // this.renderSession.shaderManager.setShader(this.defaultShader);
  16592. // gl.uniform2f(this.defaultShader.projectionVector, sizeX/2, -sizeY/2);
  16593. // gl.uniform2f(this.defaultShader.offsetVector, -offsetX, -offsetY);
  16594. // return the texture to the pool
  16595. this.texturePool.push(texture);
  16596. filterBlock._glFilterTexture = null;
  16597. };
  16598. /**
  16599. * Applies the filter to the specified area.
  16600. *
  16601. * @method applyFilterPass
  16602. * @param filter {AbstractFilter} the filter that needs to be applied
  16603. * @param filterArea {Texture} TODO - might need an update
  16604. * @param width {Number} the horizontal range of the filter
  16605. * @param height {Number} the vertical range of the filter
  16606. */
  16607. PIXI.WebGLFilterManager.prototype.applyFilterPass = function(filter, filterArea, width, height)
  16608. {
  16609. // use program
  16610. var gl = this.gl;
  16611. var shader = filter.shaders[gl.id];
  16612. if(!shader)
  16613. {
  16614. shader = new PIXI.PixiShader(gl);
  16615. shader.fragmentSrc = filter.fragmentSrc;
  16616. shader.uniforms = filter.uniforms;
  16617. shader.init();
  16618. filter.shaders[gl.id] = shader;
  16619. }
  16620. // set the shader
  16621. this.renderSession.shaderManager.setShader(shader);
  16622. // gl.useProgram(shader.program);
  16623. gl.uniform2f(shader.projectionVector, width/2, -height/2);
  16624. gl.uniform2f(shader.offsetVector, 0,0);
  16625. if(filter.uniforms.dimensions)
  16626. {
  16627. filter.uniforms.dimensions.value[0] = this.width;//width;
  16628. filter.uniforms.dimensions.value[1] = this.height;//height;
  16629. filter.uniforms.dimensions.value[2] = this.vertexArray[0];
  16630. filter.uniforms.dimensions.value[3] = this.vertexArray[5];//filterArea.height;
  16631. }
  16632. shader.syncUniforms();
  16633. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  16634. gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0);
  16635. gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer);
  16636. gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0);
  16637. gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer);
  16638. gl.vertexAttribPointer(shader.colorAttribute, 2, gl.FLOAT, false, 0, 0);
  16639. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
  16640. // draw the filter...
  16641. gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  16642. this.renderSession.drawCount++;
  16643. };
  16644. /**
  16645. * Initialises the shader buffers.
  16646. *
  16647. * @method initShaderBuffers
  16648. */
  16649. PIXI.WebGLFilterManager.prototype.initShaderBuffers = function()
  16650. {
  16651. var gl = this.gl;
  16652. // create some buffers
  16653. this.vertexBuffer = gl.createBuffer();
  16654. this.uvBuffer = gl.createBuffer();
  16655. this.colorBuffer = gl.createBuffer();
  16656. this.indexBuffer = gl.createBuffer();
  16657. // bind and upload the vertexs..
  16658. // keep a reference to the vertexFloatData..
  16659. this.vertexArray = new PIXI.Float32Array([0.0, 0.0,
  16660. 1.0, 0.0,
  16661. 0.0, 1.0,
  16662. 1.0, 1.0]);
  16663. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  16664. gl.bufferData(gl.ARRAY_BUFFER, this.vertexArray, gl.STATIC_DRAW);
  16665. // bind and upload the uv buffer
  16666. this.uvArray = new PIXI.Float32Array([0.0, 0.0,
  16667. 1.0, 0.0,
  16668. 0.0, 1.0,
  16669. 1.0, 1.0]);
  16670. gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer);
  16671. gl.bufferData(gl.ARRAY_BUFFER, this.uvArray, gl.STATIC_DRAW);
  16672. this.colorArray = new PIXI.Float32Array([1.0, 0xFFFFFF,
  16673. 1.0, 0xFFFFFF,
  16674. 1.0, 0xFFFFFF,
  16675. 1.0, 0xFFFFFF]);
  16676. gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer);
  16677. gl.bufferData(gl.ARRAY_BUFFER, this.colorArray, gl.STATIC_DRAW);
  16678. // bind and upload the index
  16679. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
  16680. gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array([0, 1, 2, 1, 3, 2]), gl.STATIC_DRAW);
  16681. };
  16682. /**
  16683. * Destroys the filter and removes it from the filter stack.
  16684. *
  16685. * @method destroy
  16686. */
  16687. PIXI.WebGLFilterManager.prototype.destroy = function()
  16688. {
  16689. var gl = this.gl;
  16690. this.filterStack = null;
  16691. this.offsetX = 0;
  16692. this.offsetY = 0;
  16693. // destroy textures
  16694. for (var i = 0; i < this.texturePool.length; i++) {
  16695. this.texturePool[i].destroy();
  16696. }
  16697. this.texturePool = null;
  16698. //destroy buffers..
  16699. gl.deleteBuffer(this.vertexBuffer);
  16700. gl.deleteBuffer(this.uvBuffer);
  16701. gl.deleteBuffer(this.colorBuffer);
  16702. gl.deleteBuffer(this.indexBuffer);
  16703. };
  16704. /**
  16705. * @author Mat Groves http://matgroves.com/ @Doormat23
  16706. */
  16707. /**
  16708. * @class FilterTexture
  16709. * @constructor
  16710. * @param gl {WebGLContext} the current WebGL drawing context
  16711. * @param width {Number} the horizontal range of the filter
  16712. * @param height {Number} the vertical range of the filter
  16713. * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values
  16714. */
  16715. PIXI.FilterTexture = function(gl, width, height, scaleMode)
  16716. {
  16717. /**
  16718. * @property gl
  16719. * @type WebGLContext
  16720. */
  16721. this.gl = gl;
  16722. // next time to create a frame buffer and texture
  16723. /**
  16724. * @property frameBuffer
  16725. * @type Any
  16726. */
  16727. this.frameBuffer = gl.createFramebuffer();
  16728. /**
  16729. * @property texture
  16730. * @type Any
  16731. */
  16732. this.texture = gl.createTexture();
  16733. /**
  16734. * @property scaleMode
  16735. * @type Number
  16736. */
  16737. scaleMode = scaleMode || PIXI.scaleModes.DEFAULT;
  16738. gl.bindTexture(gl.TEXTURE_2D, this.texture);
  16739. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST);
  16740. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST);
  16741. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16742. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16743. gl.bindFramebuffer(gl.FRAMEBUFFER, this.frameBuffer );
  16744. gl.bindFramebuffer(gl.FRAMEBUFFER, this.frameBuffer );
  16745. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture, 0);
  16746. // required for masking a mask??
  16747. this.renderBuffer = gl.createRenderbuffer();
  16748. gl.bindRenderbuffer(gl.RENDERBUFFER, this.renderBuffer);
  16749. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, this.renderBuffer);
  16750. this.resize(width, height);
  16751. };
  16752. PIXI.FilterTexture.prototype.constructor = PIXI.FilterTexture;
  16753. /**
  16754. * Clears the filter texture.
  16755. *
  16756. * @method clear
  16757. */
  16758. PIXI.FilterTexture.prototype.clear = function()
  16759. {
  16760. var gl = this.gl;
  16761. gl.clearColor(0,0,0, 0);
  16762. gl.clear(gl.COLOR_BUFFER_BIT);
  16763. };
  16764. /**
  16765. * Resizes the texture to the specified width and height
  16766. *
  16767. * @method resize
  16768. * @param width {Number} the new width of the texture
  16769. * @param height {Number} the new height of the texture
  16770. */
  16771. PIXI.FilterTexture.prototype.resize = function(width, height)
  16772. {
  16773. if(this.width === width && this.height === height) return;
  16774. this.width = width;
  16775. this.height = height;
  16776. var gl = this.gl;
  16777. gl.bindTexture(gl.TEXTURE_2D, this.texture);
  16778. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width , height , 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  16779. // update the stencil buffer width and height
  16780. gl.bindRenderbuffer(gl.RENDERBUFFER, this.renderBuffer);
  16781. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width , height );
  16782. };
  16783. /**
  16784. * Destroys the filter texture.
  16785. *
  16786. * @method destroy
  16787. */
  16788. PIXI.FilterTexture.prototype.destroy = function()
  16789. {
  16790. var gl = this.gl;
  16791. gl.deleteFramebuffer( this.frameBuffer );
  16792. gl.deleteTexture( this.texture );
  16793. this.frameBuffer = null;
  16794. this.texture = null;
  16795. };
  16796. /**
  16797. * @author Mat Groves http://matgroves.com/ @Doormat23
  16798. */
  16799. /**
  16800. * Creates a Canvas element of the given size.
  16801. *
  16802. * @class CanvasBuffer
  16803. * @constructor
  16804. * @param width {Number} the width for the newly created canvas
  16805. * @param height {Number} the height for the newly created canvas
  16806. */
  16807. PIXI.CanvasBuffer = function(width, height)
  16808. {
  16809. /**
  16810. * The width of the Canvas in pixels.
  16811. *
  16812. * @property width
  16813. * @type Number
  16814. */
  16815. this.width = width;
  16816. /**
  16817. * The height of the Canvas in pixels.
  16818. *
  16819. * @property height
  16820. * @type Number
  16821. */
  16822. this.height = height;
  16823. /**
  16824. * The Canvas object that belongs to this CanvasBuffer.
  16825. *
  16826. * @property canvas
  16827. * @type HTMLCanvasElement
  16828. */
  16829. this.canvas = PIXI.CanvasPool.create(this, this.width, this.height);
  16830. /**
  16831. * A CanvasRenderingContext2D object representing a two-dimensional rendering context.
  16832. *
  16833. * @property context
  16834. * @type CanvasRenderingContext2D
  16835. */
  16836. this.context = this.canvas.getContext("2d");
  16837. this.canvas.width = width;
  16838. this.canvas.height = height;
  16839. };
  16840. PIXI.CanvasBuffer.prototype.constructor = PIXI.CanvasBuffer;
  16841. /**
  16842. * Clears the canvas that was created by the CanvasBuffer class.
  16843. *
  16844. * @method clear
  16845. * @private
  16846. */
  16847. PIXI.CanvasBuffer.prototype.clear = function()
  16848. {
  16849. this.context.setTransform(1, 0, 0, 1, 0, 0);
  16850. this.context.clearRect(0,0, this.width, this.height);
  16851. };
  16852. /**
  16853. * Resizes the canvas to the specified width and height.
  16854. *
  16855. * @method resize
  16856. * @param width {Number} the new width of the canvas
  16857. * @param height {Number} the new height of the canvas
  16858. */
  16859. PIXI.CanvasBuffer.prototype.resize = function(width, height)
  16860. {
  16861. this.width = this.canvas.width = width;
  16862. this.height = this.canvas.height = height;
  16863. };
  16864. /**
  16865. * Frees the canvas up for use again.
  16866. *
  16867. * @method destroy
  16868. */
  16869. PIXI.CanvasBuffer.prototype.destroy = function()
  16870. {
  16871. PIXI.CanvasPool.remove(this);
  16872. };
  16873. /**
  16874. * @author Mat Groves http://matgroves.com/ @Doormat23
  16875. */
  16876. /**
  16877. * A set of functions used to handle masking.
  16878. *
  16879. * @class CanvasMaskManager
  16880. * @constructor
  16881. */
  16882. PIXI.CanvasMaskManager = function()
  16883. {
  16884. };
  16885. PIXI.CanvasMaskManager.prototype.constructor = PIXI.CanvasMaskManager;
  16886. /**
  16887. * This method adds it to the current stack of masks.
  16888. *
  16889. * @method pushMask
  16890. * @param maskData {Object} the maskData that will be pushed
  16891. * @param renderSession {Object} The renderSession whose context will be used for this mask manager.
  16892. */
  16893. PIXI.CanvasMaskManager.prototype.pushMask = function(maskData, renderSession) {
  16894. var context = renderSession.context;
  16895. context.save();
  16896. var cacheAlpha = maskData.alpha;
  16897. var transform = maskData.worldTransform;
  16898. var resolution = renderSession.resolution;
  16899. context.setTransform(transform.a * resolution,
  16900. transform.b * resolution,
  16901. transform.c * resolution,
  16902. transform.d * resolution,
  16903. transform.tx * resolution,
  16904. transform.ty * resolution);
  16905. PIXI.CanvasGraphics.renderGraphicsMask(maskData, context);
  16906. context.clip();
  16907. maskData.worldAlpha = cacheAlpha;
  16908. };
  16909. /**
  16910. * Restores the current drawing context to the state it was before the mask was applied.
  16911. *
  16912. * @method popMask
  16913. * @param renderSession {Object} The renderSession whose context will be used for this mask manager.
  16914. */
  16915. PIXI.CanvasMaskManager.prototype.popMask = function(renderSession)
  16916. {
  16917. renderSession.context.restore();
  16918. };
  16919. /**
  16920. * @author Mat Groves http://matgroves.com/ @Doormat23
  16921. */
  16922. /**
  16923. * Utility methods for Sprite/Texture tinting.
  16924. *
  16925. * @class CanvasTinter
  16926. * @static
  16927. */
  16928. PIXI.CanvasTinter = function() {};
  16929. /**
  16930. * Basically this method just needs a sprite and a color and tints the sprite with the given color.
  16931. *
  16932. * @method getTintedTexture
  16933. * @static
  16934. * @param sprite {Sprite} the sprite to tint
  16935. * @param color {Number} the color to use to tint the sprite with
  16936. * @return {HTMLCanvasElement} The tinted canvas
  16937. */
  16938. PIXI.CanvasTinter.getTintedTexture = function(sprite, color)
  16939. {
  16940. var canvas = sprite.tintedTexture || PIXI.CanvasPool.create(this);
  16941. PIXI.CanvasTinter.tintMethod(sprite.texture, color, canvas);
  16942. return canvas;
  16943. };
  16944. /**
  16945. * Tint a texture using the "multiply" operation.
  16946. *
  16947. * @method tintWithMultiply
  16948. * @static
  16949. * @param texture {Texture} the texture to tint
  16950. * @param color {Number} the color to use to tint the sprite with
  16951. * @param canvas {HTMLCanvasElement} the current canvas
  16952. */
  16953. PIXI.CanvasTinter.tintWithMultiply = function(texture, color, canvas)
  16954. {
  16955. var context = canvas.getContext("2d");
  16956. var crop = texture.crop;
  16957. if (canvas.width !== crop.width || canvas.height !== crop.height)
  16958. {
  16959. canvas.width = crop.width;
  16960. canvas.height = crop.height;
  16961. }
  16962. context.clearRect(0, 0, crop.width, crop.height);
  16963. context.fillStyle = "#" + ("00000" + (color | 0).toString(16)).substr(-6);
  16964. context.fillRect(0, 0, crop.width, crop.height);
  16965. context.globalCompositeOperation = "multiply";
  16966. context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height);
  16967. context.globalCompositeOperation = "destination-atop";
  16968. context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height);
  16969. };
  16970. /**
  16971. * Tint a texture pixel per pixel.
  16972. *
  16973. * @method tintPerPixel
  16974. * @static
  16975. * @param texture {Texture} the texture to tint
  16976. * @param color {Number} the color to use to tint the sprite with
  16977. * @param canvas {HTMLCanvasElement} the current canvas
  16978. */
  16979. PIXI.CanvasTinter.tintWithPerPixel = function(texture, color, canvas)
  16980. {
  16981. var context = canvas.getContext("2d");
  16982. var crop = texture.crop;
  16983. canvas.width = crop.width;
  16984. canvas.height = crop.height;
  16985. context.globalCompositeOperation = "copy";
  16986. context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height);
  16987. var rgbValues = PIXI.hex2rgb(color);
  16988. var r = rgbValues[0], g = rgbValues[1], b = rgbValues[2];
  16989. var pixelData = context.getImageData(0, 0, crop.width, crop.height);
  16990. var pixels = pixelData.data;
  16991. for (var i = 0; i < pixels.length; i += 4)
  16992. {
  16993. pixels[i + 0] *= r;
  16994. pixels[i + 1] *= g;
  16995. pixels[i + 2] *= b;
  16996. if (!PIXI.CanvasTinter.canHandleAlpha)
  16997. {
  16998. var alpha = pixels[i + 3];
  16999. pixels[i + 0] /= 255 / alpha;
  17000. pixels[i + 1] /= 255 / alpha;
  17001. pixels[i + 2] /= 255 / alpha;
  17002. }
  17003. }
  17004. context.putImageData(pixelData, 0, 0);
  17005. };
  17006. /**
  17007. * Checks if the browser correctly supports putImageData alpha channels.
  17008. *
  17009. * @method checkInverseAlpha
  17010. * @static
  17011. */
  17012. PIXI.CanvasTinter.checkInverseAlpha = function()
  17013. {
  17014. var canvas = new PIXI.CanvasBuffer(2, 1);
  17015. canvas.context.fillStyle = "rgba(10, 20, 30, 0.5)";
  17016. // Draw a single pixel
  17017. canvas.context.fillRect(0, 0, 1, 1);
  17018. // Get the color values
  17019. var s1 = canvas.context.getImageData(0, 0, 1, 1);
  17020. if (s1 === null)
  17021. {
  17022. return false;
  17023. }
  17024. // Plot them to x2
  17025. canvas.context.putImageData(s1, 1, 0);
  17026. // Get those values
  17027. var s2 = canvas.context.getImageData(1, 0, 1, 1);
  17028. // Compare and return
  17029. return (s2.data[0] === s1.data[0] && s2.data[1] === s1.data[1] && s2.data[2] === s1.data[2] && s2.data[3] === s1.data[3]);
  17030. };
  17031. /**
  17032. * If the browser isn't capable of handling tinting with alpha this will be false.
  17033. * This property is only applicable if using tintWithPerPixel.
  17034. *
  17035. * @property canHandleAlpha
  17036. * @type Boolean
  17037. * @static
  17038. */
  17039. PIXI.CanvasTinter.canHandleAlpha = PIXI.CanvasTinter.checkInverseAlpha();
  17040. /**
  17041. * Whether or not the Canvas BlendModes are supported, consequently the ability to tint using the multiply method.
  17042. *
  17043. * @property canUseMultiply
  17044. * @type Boolean
  17045. * @static
  17046. */
  17047. PIXI.CanvasTinter.canUseMultiply = PIXI.canUseNewCanvasBlendModes();
  17048. /**
  17049. * The tinting method that will be used.
  17050. *
  17051. * @method tintMethod
  17052. * @static
  17053. */
  17054. PIXI.CanvasTinter.tintMethod = PIXI.CanvasTinter.canUseMultiply ? PIXI.CanvasTinter.tintWithMultiply : PIXI.CanvasTinter.tintWithPerPixel;
  17055. /**
  17056. * @author Mat Groves http://matgroves.com/ @Doormat23
  17057. */
  17058. /**
  17059. * 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.
  17060. * Don't forget to add the CanvasRenderer.view to your DOM or you will not see anything :)
  17061. *
  17062. * @class CanvasRenderer
  17063. * @constructor
  17064. * @param game {Phaser.Game} A reference to the Phaser Game instance
  17065. */
  17066. PIXI.CanvasRenderer = function (game) {
  17067. /**
  17068. * @property {Phaser.Game} game - A reference to the Phaser Game instance.
  17069. */
  17070. this.game = game;
  17071. if (!PIXI.defaultRenderer)
  17072. {
  17073. PIXI.defaultRenderer = this;
  17074. }
  17075. /**
  17076. * The renderer type.
  17077. *
  17078. * @property type
  17079. * @type Number
  17080. */
  17081. this.type = PIXI.CANVAS_RENDERER;
  17082. /**
  17083. * The resolution of the canvas.
  17084. *
  17085. * @property resolution
  17086. * @type Number
  17087. */
  17088. this.resolution = game.resolution;
  17089. /**
  17090. * This sets if the CanvasRenderer will clear the canvas or not before the new render pass.
  17091. * If the Stage is NOT transparent Pixi will use a canvas sized fillRect operation every frame to set the canvas background color.
  17092. * If the Stage is transparent Pixi will use clearRect to clear the canvas every frame.
  17093. * Disable this by setting this to false. For example if your game has a canvas filling background image you often don't need this set.
  17094. *
  17095. * @property clearBeforeRender
  17096. * @type Boolean
  17097. * @default
  17098. */
  17099. this.clearBeforeRender = game.clearBeforeRender;
  17100. /**
  17101. * Whether the render view is transparent
  17102. *
  17103. * @property transparent
  17104. * @type Boolean
  17105. */
  17106. this.transparent = game.transparent;
  17107. /**
  17108. * Whether the render view should be resized automatically
  17109. *
  17110. * @property autoResize
  17111. * @type Boolean
  17112. */
  17113. this.autoResize = false;
  17114. /**
  17115. * The width of the canvas view
  17116. *
  17117. * @property width
  17118. * @type Number
  17119. * @default 800
  17120. */
  17121. this.width = game.width * this.resolution;
  17122. /**
  17123. * The height of the canvas view
  17124. *
  17125. * @property height
  17126. * @type Number
  17127. * @default 600
  17128. */
  17129. this.height = game.height * this.resolution;
  17130. /**
  17131. * The canvas element that everything is drawn to.
  17132. *
  17133. * @property view
  17134. * @type HTMLCanvasElement
  17135. */
  17136. this.view = game.canvas;
  17137. /**
  17138. * The canvas 2d context that everything is drawn with
  17139. * @property context
  17140. * @type CanvasRenderingContext2D
  17141. */
  17142. this.context = this.view.getContext("2d", { alpha: this.transparent } );
  17143. /**
  17144. * Boolean flag controlling canvas refresh.
  17145. *
  17146. * @property refresh
  17147. * @type Boolean
  17148. */
  17149. this.refresh = true;
  17150. /**
  17151. * Internal var.
  17152. *
  17153. * @property count
  17154. * @type Number
  17155. */
  17156. this.count = 0;
  17157. /**
  17158. * Instance of a PIXI.CanvasMaskManager, handles masking when using the canvas renderer
  17159. * @property CanvasMaskManager
  17160. * @type CanvasMaskManager
  17161. */
  17162. this.maskManager = new PIXI.CanvasMaskManager();
  17163. /**
  17164. * The render session is just a bunch of parameter used for rendering
  17165. * @property renderSession
  17166. * @type Object
  17167. */
  17168. this.renderSession = {
  17169. context: this.context,
  17170. maskManager: this.maskManager,
  17171. scaleMode: null,
  17172. smoothProperty: Phaser.Canvas.getSmoothingPrefix(this.context),
  17173. /**
  17174. * If true Pixi will Math.floor() x/y values when rendering, stopping pixel interpolation.
  17175. * Handy for crisp pixel art and speed on legacy devices.
  17176. */
  17177. roundPixels: false
  17178. };
  17179. this.mapBlendModes();
  17180. this.resize(this.width, this.height);
  17181. };
  17182. // constructor
  17183. PIXI.CanvasRenderer.prototype.constructor = PIXI.CanvasRenderer;
  17184. /**
  17185. * Renders the Stage to this canvas view
  17186. *
  17187. * @method render
  17188. * @param stage {Stage} the Stage element to be rendered
  17189. */
  17190. PIXI.CanvasRenderer.prototype.render = function (stage) {
  17191. stage.updateTransform();
  17192. this.context.setTransform(1, 0, 0, 1, 0, 0);
  17193. this.context.globalAlpha = 1;
  17194. this.renderSession.currentBlendMode = 0;
  17195. this.renderSession.shakeX = this.game.camera._shake.x;
  17196. this.renderSession.shakeY = this.game.camera._shake.y;
  17197. this.context.globalCompositeOperation = 'source-over';
  17198. if (navigator.isCocoonJS && this.view.screencanvas)
  17199. {
  17200. this.context.fillStyle = "black";
  17201. this.context.clear();
  17202. }
  17203. if (this.clearBeforeRender)
  17204. {
  17205. if (this.transparent)
  17206. {
  17207. this.context.clearRect(0, 0, this.width, this.height);
  17208. }
  17209. else
  17210. {
  17211. this.context.fillStyle = stage._bgColor.rgba;
  17212. this.context.fillRect(0, 0, this.width , this.height);
  17213. }
  17214. }
  17215. this.renderDisplayObject(stage);
  17216. };
  17217. /**
  17218. * Removes everything from the renderer and optionally removes the Canvas DOM element.
  17219. *
  17220. * @method destroy
  17221. * @param [removeView=true] {boolean} Removes the Canvas element from the DOM.
  17222. */
  17223. PIXI.CanvasRenderer.prototype.destroy = function (removeView) {
  17224. if (removeView === undefined) { removeView = true; }
  17225. if (removeView && this.view.parent)
  17226. {
  17227. this.view.parent.removeChild(this.view);
  17228. }
  17229. this.view = null;
  17230. this.context = null;
  17231. this.maskManager = null;
  17232. this.renderSession = null;
  17233. };
  17234. /**
  17235. * Resizes the canvas view to the specified width and height
  17236. *
  17237. * @method resize
  17238. * @param width {Number} the new width of the canvas view
  17239. * @param height {Number} the new height of the canvas view
  17240. */
  17241. PIXI.CanvasRenderer.prototype.resize = function (width, height) {
  17242. this.width = width * this.resolution;
  17243. this.height = height * this.resolution;
  17244. this.view.width = this.width;
  17245. this.view.height = this.height;
  17246. if (this.autoResize)
  17247. {
  17248. this.view.style.width = this.width / this.resolution + "px";
  17249. this.view.style.height = this.height / this.resolution + "px";
  17250. }
  17251. if (this.renderSession.smoothProperty)
  17252. {
  17253. this.context[this.renderSession.smoothProperty] = (this.renderSession.scaleMode === PIXI.scaleModes.LINEAR);
  17254. }
  17255. };
  17256. /**
  17257. * Renders a display object
  17258. *
  17259. * @method renderDisplayObject
  17260. * @param displayObject {DisplayObject} The displayObject to render
  17261. * @param context {CanvasRenderingContext2D} the context 2d method of the canvas
  17262. * @param [matrix] {Matrix} Optional matrix to apply to the display object before rendering.
  17263. * @private
  17264. */
  17265. PIXI.CanvasRenderer.prototype.renderDisplayObject = function (displayObject, context, matrix) {
  17266. this.renderSession.context = context || this.context;
  17267. this.renderSession.resolution = this.resolution;
  17268. displayObject._renderCanvas(this.renderSession, matrix);
  17269. };
  17270. /**
  17271. * Maps Pixi blend modes to canvas blend modes.
  17272. *
  17273. * @method mapBlendModes
  17274. * @private
  17275. */
  17276. PIXI.CanvasRenderer.prototype.mapBlendModes = function () {
  17277. if (!PIXI.blendModesCanvas)
  17278. {
  17279. var b = [];
  17280. var modes = PIXI.blendModes;
  17281. var useNew = PIXI.canUseNewCanvasBlendModes();
  17282. b[modes.NORMAL] = 'source-over';
  17283. b[modes.ADD] = 'lighter';
  17284. b[modes.MULTIPLY] = (useNew) ? 'multiply' : 'source-over';
  17285. b[modes.SCREEN] = (useNew) ? 'screen' : 'source-over';
  17286. b[modes.OVERLAY] = (useNew) ? 'overlay' : 'source-over';
  17287. b[modes.DARKEN] = (useNew) ? 'darken' : 'source-over';
  17288. b[modes.LIGHTEN] = (useNew) ? 'lighten' : 'source-over';
  17289. b[modes.COLOR_DODGE] = (useNew) ? 'color-dodge' : 'source-over';
  17290. b[modes.COLOR_BURN] = (useNew) ? 'color-burn' : 'source-over';
  17291. b[modes.HARD_LIGHT] = (useNew) ? 'hard-light' : 'source-over';
  17292. b[modes.SOFT_LIGHT] = (useNew) ? 'soft-light' : 'source-over';
  17293. b[modes.DIFFERENCE] = (useNew) ? 'difference' : 'source-over';
  17294. b[modes.EXCLUSION] = (useNew) ? 'exclusion' : 'source-over';
  17295. b[modes.HUE] = (useNew) ? 'hue' : 'source-over';
  17296. b[modes.SATURATION] = (useNew) ? 'saturation' : 'source-over';
  17297. b[modes.COLOR] = (useNew) ? 'color' : 'source-over';
  17298. b[modes.LUMINOSITY] = (useNew) ? 'luminosity' : 'source-over';
  17299. PIXI.blendModesCanvas = b;
  17300. }
  17301. };
  17302. /**
  17303. * @author Mat Groves http://matgroves.com/ @Doormat23
  17304. */
  17305. PIXI.BaseTextureCache = {};
  17306. PIXI.BaseTextureCacheIdGenerator = 0;
  17307. /**
  17308. * A texture stores the information that represents an image. All textures have a base texture.
  17309. *
  17310. * @class BaseTexture
  17311. * @uses EventTarget
  17312. * @constructor
  17313. * @param source {String} the source object (image or canvas)
  17314. * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values
  17315. */
  17316. PIXI.BaseTexture = function(source, scaleMode)
  17317. {
  17318. /**
  17319. * The Resolution of the texture.
  17320. *
  17321. * @property resolution
  17322. * @type Number
  17323. */
  17324. this.resolution = 1;
  17325. /**
  17326. * [read-only] The width of the base texture set when the image has loaded
  17327. *
  17328. * @property width
  17329. * @type Number
  17330. * @readOnly
  17331. */
  17332. this.width = 100;
  17333. /**
  17334. * [read-only] The height of the base texture set when the image has loaded
  17335. *
  17336. * @property height
  17337. * @type Number
  17338. * @readOnly
  17339. */
  17340. this.height = 100;
  17341. /**
  17342. * The scale mode to apply when scaling this texture
  17343. *
  17344. * @property scaleMode
  17345. * @type {Number}
  17346. * @default PIXI.scaleModes.LINEAR
  17347. */
  17348. this.scaleMode = scaleMode || PIXI.scaleModes.DEFAULT;
  17349. /**
  17350. * [read-only] Set to true once the base texture has loaded
  17351. *
  17352. * @property hasLoaded
  17353. * @type Boolean
  17354. * @readOnly
  17355. */
  17356. this.hasLoaded = false;
  17357. /**
  17358. * The image source that is used to create the texture.
  17359. *
  17360. * @property source
  17361. * @type Image
  17362. */
  17363. this.source = source;
  17364. this._UID = PIXI._UID++;
  17365. /**
  17366. * Controls if RGB channels should be pre-multiplied by Alpha (WebGL only)
  17367. *
  17368. * @property premultipliedAlpha
  17369. * @type Boolean
  17370. * @default true
  17371. */
  17372. this.premultipliedAlpha = true;
  17373. // used for webGL
  17374. /**
  17375. * @property _glTextures
  17376. * @type Array
  17377. * @private
  17378. */
  17379. this._glTextures = [];
  17380. /**
  17381. * Set this to true if a mipmap of this texture needs to be generated. This value needs to be set before the texture is used
  17382. * Also the texture must be a power of two size to work
  17383. *
  17384. * @property mipmap
  17385. * @type {Boolean}
  17386. */
  17387. this.mipmap = false;
  17388. /**
  17389. * @property _dirty
  17390. * @type Array
  17391. * @private
  17392. */
  17393. this._dirty = [true, true, true, true];
  17394. if (!source)
  17395. {
  17396. return;
  17397. }
  17398. if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height)
  17399. {
  17400. this.hasLoaded = true;
  17401. this.width = this.source.naturalWidth || this.source.width;
  17402. this.height = this.source.naturalHeight || this.source.height;
  17403. this.dirty();
  17404. }
  17405. /**
  17406. * A BaseTexture can be set to skip the rendering phase in the WebGL Sprite Batch.
  17407. *
  17408. * You may want to do this if you have a parent Sprite with no visible texture (i.e. uses the internal `__default` texture)
  17409. * that has children that you do want to render, without causing a batch flush in the process.
  17410. *
  17411. * @property skipRender
  17412. * @type Boolean
  17413. */
  17414. this.skipRender = false;
  17415. /**
  17416. * @property imageUrl
  17417. * @type String
  17418. */
  17419. this.imageUrl = null;
  17420. /**
  17421. * @property _powerOf2
  17422. * @type Boolean
  17423. * @private
  17424. */
  17425. this._powerOf2 = false;
  17426. };
  17427. PIXI.BaseTexture.prototype.constructor = PIXI.BaseTexture;
  17428. /**
  17429. * Forces this BaseTexture to be set as loaded, with the given width and height.
  17430. * Then calls BaseTexture.dirty.
  17431. * Important for when you don't want to modify the source object by forcing in `complete` or dimension properties it may not have.
  17432. *
  17433. * @method forceLoaded
  17434. * @param {number} width - The new width to force the BaseTexture to be.
  17435. * @param {number} height - The new height to force the BaseTexture to be.
  17436. */
  17437. PIXI.BaseTexture.prototype.forceLoaded = function(width, height)
  17438. {
  17439. this.hasLoaded = true;
  17440. this.width = width;
  17441. this.height = height;
  17442. this.dirty();
  17443. };
  17444. /**
  17445. * Destroys this base texture
  17446. *
  17447. * @method destroy
  17448. */
  17449. PIXI.BaseTexture.prototype.destroy = function()
  17450. {
  17451. if (this.imageUrl)
  17452. {
  17453. delete PIXI.BaseTextureCache[this.imageUrl];
  17454. delete PIXI.TextureCache[this.imageUrl];
  17455. this.imageUrl = null;
  17456. if (!navigator.isCocoonJS) this.source.src = '';
  17457. }
  17458. else if (this.source)
  17459. {
  17460. PIXI.CanvasPool.removeByCanvas(this.source);
  17461. if (this.source._pixiId)
  17462. {
  17463. delete PIXI.BaseTextureCache[this.source._pixiId];
  17464. }
  17465. }
  17466. this.source = null;
  17467. this.unloadFromGPU();
  17468. };
  17469. /**
  17470. * Changes the source image of the texture
  17471. *
  17472. * @method updateSourceImage
  17473. * @param newSrc {String} the path of the image
  17474. */
  17475. PIXI.BaseTexture.prototype.updateSourceImage = function(newSrc)
  17476. {
  17477. this.hasLoaded = false;
  17478. this.source.src = null;
  17479. this.source.src = newSrc;
  17480. };
  17481. /**
  17482. * Sets all glTextures to be dirty.
  17483. *
  17484. * @method dirty
  17485. */
  17486. PIXI.BaseTexture.prototype.dirty = function()
  17487. {
  17488. for (var i = 0; i < this._glTextures.length; i++)
  17489. {
  17490. this._dirty[i] = true;
  17491. }
  17492. };
  17493. /**
  17494. * Removes the base texture from the GPU, useful for managing resources on the GPU.
  17495. * Atexture is still 100% usable and will simply be reuploaded if there is a sprite on screen that is using it.
  17496. *
  17497. * @method unloadFromGPU
  17498. */
  17499. PIXI.BaseTexture.prototype.unloadFromGPU = function()
  17500. {
  17501. this.dirty();
  17502. // delete the webGL textures if any.
  17503. for (var i = this._glTextures.length - 1; i >= 0; i--)
  17504. {
  17505. var glTexture = this._glTextures[i];
  17506. var gl = PIXI.glContexts[i];
  17507. if(gl && glTexture)
  17508. {
  17509. gl.deleteTexture(glTexture);
  17510. }
  17511. }
  17512. this._glTextures.length = 0;
  17513. this.dirty();
  17514. };
  17515. /**
  17516. * Helper function that creates a base texture from the given image url.
  17517. * If the image is not in the base texture cache it will be created and loaded.
  17518. *
  17519. * @static
  17520. * @method fromImage
  17521. * @param imageUrl {String} The image url of the texture
  17522. * @param crossorigin {Boolean}
  17523. * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values
  17524. * @return {BaseTexture}
  17525. */
  17526. PIXI.BaseTexture.fromImage = function(imageUrl, crossorigin, scaleMode)
  17527. {
  17528. var baseTexture = PIXI.BaseTextureCache[imageUrl];
  17529. if(crossorigin === undefined && imageUrl.indexOf('data:') === -1) crossorigin = true;
  17530. if(!baseTexture)
  17531. {
  17532. // new Image() breaks tex loading in some versions of Chrome.
  17533. // See https://code.google.com/p/chromium/issues/detail?id=238071
  17534. var image = new Image();
  17535. if (crossorigin)
  17536. {
  17537. image.crossOrigin = '';
  17538. }
  17539. image.src = imageUrl;
  17540. baseTexture = new PIXI.BaseTexture(image, scaleMode);
  17541. baseTexture.imageUrl = imageUrl;
  17542. PIXI.BaseTextureCache[imageUrl] = baseTexture;
  17543. // if there is an @2x at the end of the url we are going to assume its a highres image
  17544. if( imageUrl.indexOf(PIXI.RETINA_PREFIX + '.') !== -1)
  17545. {
  17546. baseTexture.resolution = 2;
  17547. }
  17548. }
  17549. return baseTexture;
  17550. };
  17551. /**
  17552. * Helper function that creates a base texture from the given canvas element.
  17553. *
  17554. * @static
  17555. * @method fromCanvas
  17556. * @param canvas {Canvas} The canvas element source of the texture
  17557. * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values
  17558. * @return {BaseTexture}
  17559. */
  17560. PIXI.BaseTexture.fromCanvas = function(canvas, scaleMode)
  17561. {
  17562. if (!canvas._pixiId)
  17563. {
  17564. canvas._pixiId = 'canvas_' + PIXI.TextureCacheIdGenerator++;
  17565. }
  17566. if (canvas.width === 0)
  17567. {
  17568. canvas.width = 1;
  17569. }
  17570. if (canvas.height === 0)
  17571. {
  17572. canvas.height = 1;
  17573. }
  17574. var baseTexture = PIXI.BaseTextureCache[canvas._pixiId];
  17575. if (!baseTexture)
  17576. {
  17577. baseTexture = new PIXI.BaseTexture(canvas, scaleMode);
  17578. PIXI.BaseTextureCache[canvas._pixiId] = baseTexture;
  17579. }
  17580. return baseTexture;
  17581. };
  17582. /**
  17583. * @author Mat Groves http://matgroves.com/ @Doormat23
  17584. */
  17585. PIXI.TextureCache = {};
  17586. PIXI.FrameCache = {};
  17587. /**
  17588. * TextureSilentFail is a boolean that defaults to `false`.
  17589. * If `true` then `PIXI.Texture.setFrame` will no longer throw an error if the texture dimensions are incorrect.
  17590. * Instead `Texture.valid` will be set to `false` (#1556)
  17591. *
  17592. * @type {boolean}
  17593. */
  17594. PIXI.TextureSilentFail = false;
  17595. PIXI.TextureCacheIdGenerator = 0;
  17596. /**
  17597. * A texture stores the information that represents an image or part of an image. It cannot be added
  17598. * to the display list directly. Instead use it as the texture for a PIXI.Sprite. If no frame is provided then the whole image is used.
  17599. *
  17600. * @class Texture
  17601. * @uses EventTarget
  17602. * @constructor
  17603. * @param baseTexture {BaseTexture} The base texture source to create the texture from
  17604. * @param frame {Rectangle} The rectangle frame of the texture to show
  17605. * @param [crop] {Rectangle} The area of original texture
  17606. * @param [trim] {Rectangle} Trimmed texture rectangle
  17607. */
  17608. PIXI.Texture = function(baseTexture, frame, crop, trim)
  17609. {
  17610. /**
  17611. * Does this Texture have any frame data assigned to it?
  17612. *
  17613. * @property noFrame
  17614. * @type Boolean
  17615. */
  17616. this.noFrame = false;
  17617. if (!frame)
  17618. {
  17619. this.noFrame = true;
  17620. frame = new PIXI.Rectangle(0,0,1,1);
  17621. }
  17622. if (baseTexture instanceof PIXI.Texture)
  17623. {
  17624. baseTexture = baseTexture.baseTexture;
  17625. }
  17626. /**
  17627. * The base texture that this texture uses.
  17628. *
  17629. * @property baseTexture
  17630. * @type BaseTexture
  17631. */
  17632. this.baseTexture = baseTexture;
  17633. /**
  17634. * The frame specifies the region of the base texture that this texture uses
  17635. *
  17636. * @property frame
  17637. * @type Rectangle
  17638. */
  17639. this.frame = frame;
  17640. /**
  17641. * The texture trim data.
  17642. *
  17643. * @property trim
  17644. * @type Rectangle
  17645. */
  17646. this.trim = trim;
  17647. /**
  17648. * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered.
  17649. *
  17650. * @property valid
  17651. * @type Boolean
  17652. */
  17653. this.valid = false;
  17654. /**
  17655. * Is this a tiling texture? As used by the likes of a TilingSprite.
  17656. *
  17657. * @property isTiling
  17658. * @type Boolean
  17659. */
  17660. this.isTiling = false;
  17661. /**
  17662. * This will let a renderer know that a texture has been updated (used mainly for webGL uv updates)
  17663. *
  17664. * @property requiresUpdate
  17665. * @type Boolean
  17666. */
  17667. this.requiresUpdate = false;
  17668. /**
  17669. * This will let a renderer know that a tinted parent has updated its texture.
  17670. *
  17671. * @property requiresReTint
  17672. * @type Boolean
  17673. */
  17674. this.requiresReTint = false;
  17675. /**
  17676. * The WebGL UV data cache.
  17677. *
  17678. * @property _uvs
  17679. * @type Object
  17680. * @private
  17681. */
  17682. this._uvs = null;
  17683. /**
  17684. * The width of the Texture in pixels.
  17685. *
  17686. * @property width
  17687. * @type Number
  17688. */
  17689. this.width = 0;
  17690. /**
  17691. * The height of the Texture in pixels.
  17692. *
  17693. * @property height
  17694. * @type Number
  17695. */
  17696. this.height = 0;
  17697. /**
  17698. * This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering,
  17699. * irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases)
  17700. *
  17701. * @property crop
  17702. * @type Rectangle
  17703. */
  17704. this.crop = crop || new PIXI.Rectangle(0, 0, 1, 1);
  17705. if (baseTexture.hasLoaded)
  17706. {
  17707. if (this.noFrame) frame = new PIXI.Rectangle(0, 0, baseTexture.width, baseTexture.height);
  17708. this.setFrame(frame);
  17709. }
  17710. };
  17711. PIXI.Texture.prototype.constructor = PIXI.Texture;
  17712. /**
  17713. * Called when the base texture is loaded
  17714. *
  17715. * @method onBaseTextureLoaded
  17716. * @private
  17717. */
  17718. PIXI.Texture.prototype.onBaseTextureLoaded = function()
  17719. {
  17720. var baseTexture = this.baseTexture;
  17721. if (this.noFrame)
  17722. {
  17723. this.frame = new PIXI.Rectangle(0, 0, baseTexture.width, baseTexture.height);
  17724. }
  17725. this.setFrame(this.frame);
  17726. };
  17727. /**
  17728. * Destroys this texture
  17729. *
  17730. * @method destroy
  17731. * @param destroyBase {Boolean} Whether to destroy the base texture as well
  17732. */
  17733. PIXI.Texture.prototype.destroy = function(destroyBase)
  17734. {
  17735. if (destroyBase) this.baseTexture.destroy();
  17736. this.valid = false;
  17737. };
  17738. /**
  17739. * Specifies the region of the baseTexture that this texture will use.
  17740. *
  17741. * @method setFrame
  17742. * @param frame {Rectangle} The frame of the texture to set it to
  17743. */
  17744. PIXI.Texture.prototype.setFrame = function(frame)
  17745. {
  17746. this.noFrame = false;
  17747. this.frame = frame;
  17748. this.width = frame.width;
  17749. this.height = frame.height;
  17750. this.crop.x = frame.x;
  17751. this.crop.y = frame.y;
  17752. this.crop.width = frame.width;
  17753. this.crop.height = frame.height;
  17754. if (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height))
  17755. {
  17756. if (!PIXI.TextureSilentFail)
  17757. {
  17758. throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this);
  17759. }
  17760. this.valid = false;
  17761. return;
  17762. }
  17763. this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded;
  17764. if (this.trim)
  17765. {
  17766. this.width = this.trim.width;
  17767. this.height = this.trim.height;
  17768. this.frame.width = this.trim.width;
  17769. this.frame.height = this.trim.height;
  17770. }
  17771. if (this.valid) this._updateUvs();
  17772. };
  17773. /**
  17774. * Updates the internal WebGL UV cache.
  17775. *
  17776. * @method _updateUvs
  17777. * @private
  17778. */
  17779. PIXI.Texture.prototype._updateUvs = function()
  17780. {
  17781. if(!this._uvs)this._uvs = new PIXI.TextureUvs();
  17782. var frame = this.crop;
  17783. var tw = this.baseTexture.width;
  17784. var th = this.baseTexture.height;
  17785. this._uvs.x0 = frame.x / tw;
  17786. this._uvs.y0 = frame.y / th;
  17787. this._uvs.x1 = (frame.x + frame.width) / tw;
  17788. this._uvs.y1 = frame.y / th;
  17789. this._uvs.x2 = (frame.x + frame.width) / tw;
  17790. this._uvs.y2 = (frame.y + frame.height) / th;
  17791. this._uvs.x3 = frame.x / tw;
  17792. this._uvs.y3 = (frame.y + frame.height) / th;
  17793. };
  17794. /**
  17795. * Helper function that creates a Texture object from the given image url.
  17796. * If the image is not in the texture cache it will be created and loaded.
  17797. *
  17798. * @static
  17799. * @method fromImage
  17800. * @param imageUrl {String} The image url of the texture
  17801. * @param crossorigin {Boolean} Whether requests should be treated as crossorigin
  17802. * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values
  17803. * @return {Texture}
  17804. */
  17805. PIXI.Texture.fromImage = function(imageUrl, crossorigin, scaleMode)
  17806. {
  17807. var texture = PIXI.TextureCache[imageUrl];
  17808. if(!texture)
  17809. {
  17810. texture = new PIXI.Texture(PIXI.BaseTexture.fromImage(imageUrl, crossorigin, scaleMode));
  17811. PIXI.TextureCache[imageUrl] = texture;
  17812. }
  17813. return texture;
  17814. };
  17815. /**
  17816. * Helper function that returns a Texture objected based on the given frame id.
  17817. * If the frame id is not in the texture cache an error will be thrown.
  17818. *
  17819. * @static
  17820. * @method fromFrame
  17821. * @param frameId {String} The frame id of the texture
  17822. * @return {Texture}
  17823. */
  17824. PIXI.Texture.fromFrame = function(frameId)
  17825. {
  17826. var texture = PIXI.TextureCache[frameId];
  17827. if(!texture) throw new Error('The frameId "' + frameId + '" does not exist in the texture cache ');
  17828. return texture;
  17829. };
  17830. /**
  17831. * Helper function that creates a new a Texture based on the given canvas element.
  17832. *
  17833. * @static
  17834. * @method fromCanvas
  17835. * @param canvas {Canvas} The canvas element source of the texture
  17836. * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values
  17837. * @return {Texture}
  17838. */
  17839. PIXI.Texture.fromCanvas = function(canvas, scaleMode)
  17840. {
  17841. var baseTexture = PIXI.BaseTexture.fromCanvas(canvas, scaleMode);
  17842. return new PIXI.Texture(baseTexture);
  17843. };
  17844. /**
  17845. * Adds a texture to the global PIXI.TextureCache. This cache is shared across the whole PIXI object.
  17846. *
  17847. * @static
  17848. * @method addTextureToCache
  17849. * @param texture {Texture} The Texture to add to the cache.
  17850. * @param id {String} The id that the texture will be stored against.
  17851. */
  17852. PIXI.Texture.addTextureToCache = function(texture, id)
  17853. {
  17854. PIXI.TextureCache[id] = texture;
  17855. };
  17856. /**
  17857. * Remove a texture from the global PIXI.TextureCache.
  17858. *
  17859. * @static
  17860. * @method removeTextureFromCache
  17861. * @param id {String} The id of the texture to be removed
  17862. * @return {Texture} The texture that was removed
  17863. */
  17864. PIXI.Texture.removeTextureFromCache = function(id)
  17865. {
  17866. var texture = PIXI.TextureCache[id];
  17867. delete PIXI.TextureCache[id];
  17868. delete PIXI.BaseTextureCache[id];
  17869. return texture;
  17870. };
  17871. PIXI.TextureUvs = function()
  17872. {
  17873. this.x0 = 0;
  17874. this.y0 = 0;
  17875. this.x1 = 0;
  17876. this.y1 = 0;
  17877. this.x2 = 0;
  17878. this.y2 = 0;
  17879. this.x3 = 0;
  17880. this.y3 = 0;
  17881. };
  17882. /**
  17883. * @author Mat Groves http://matgroves.com/ @Doormat23
  17884. */
  17885. /**
  17886. * A RenderTexture is a special texture that allows any Pixi display object to be rendered to it.
  17887. *
  17888. * __Hint__: All DisplayObjects (i.e. Sprites) that render to a RenderTexture should be preloaded otherwise black rectangles will be drawn instead.
  17889. *
  17890. * A RenderTexture takes a snapshot of any Display Object given to its render method. The position and rotation of the given Display Objects is ignored. For example:
  17891. *
  17892. * var renderTexture = new PIXI.RenderTexture(800, 600);
  17893. * var sprite = PIXI.Sprite.fromImage("spinObj_01.png");
  17894. * sprite.position.x = 800/2;
  17895. * sprite.position.y = 600/2;
  17896. * sprite.anchor.x = 0.5;
  17897. * sprite.anchor.y = 0.5;
  17898. * renderTexture.render(sprite);
  17899. *
  17900. * The Sprite in this case will be rendered to a position of 0,0. To render this sprite at its actual position a DisplayObjectContainer should be used:
  17901. *
  17902. * var doc = new PIXI.DisplayObjectContainer();
  17903. * doc.addChild(sprite);
  17904. * renderTexture.render(doc); // Renders to center of renderTexture
  17905. *
  17906. * @class RenderTexture
  17907. * @extends Texture
  17908. * @constructor
  17909. * @param width {Number} The width of the render texture
  17910. * @param height {Number} The height of the render texture
  17911. * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used for this RenderTexture
  17912. * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values
  17913. * @param resolution {Number} The resolution of the texture being generated
  17914. */
  17915. PIXI.RenderTexture = function(width, height, renderer, scaleMode, resolution)
  17916. {
  17917. /**
  17918. * The with of the render texture
  17919. *
  17920. * @property width
  17921. * @type Number
  17922. */
  17923. this.width = width || 100;
  17924. /**
  17925. * The height of the render texture
  17926. *
  17927. * @property height
  17928. * @type Number
  17929. */
  17930. this.height = height || 100;
  17931. /**
  17932. * The Resolution of the texture.
  17933. *
  17934. * @property resolution
  17935. * @type Number
  17936. */
  17937. this.resolution = resolution || 1;
  17938. /**
  17939. * The framing rectangle of the render texture
  17940. *
  17941. * @property frame
  17942. * @type Rectangle
  17943. */
  17944. this.frame = new PIXI.Rectangle(0, 0, this.width * this.resolution, this.height * this.resolution);
  17945. /**
  17946. * This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering,
  17947. * irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases)
  17948. *
  17949. * @property crop
  17950. * @type Rectangle
  17951. */
  17952. this.crop = new PIXI.Rectangle(0, 0, this.width * this.resolution, this.height * this.resolution);
  17953. /**
  17954. * The base texture object that this texture uses
  17955. *
  17956. * @property baseTexture
  17957. * @type BaseTexture
  17958. */
  17959. this.baseTexture = new PIXI.BaseTexture();
  17960. this.baseTexture.width = this.width * this.resolution;
  17961. this.baseTexture.height = this.height * this.resolution;
  17962. this.baseTexture._glTextures = [];
  17963. this.baseTexture.resolution = this.resolution;
  17964. this.baseTexture.scaleMode = scaleMode || PIXI.scaleModes.DEFAULT;
  17965. this.baseTexture.hasLoaded = true;
  17966. PIXI.Texture.call(this,
  17967. this.baseTexture,
  17968. new PIXI.Rectangle(0, 0, this.width * this.resolution, this.height * this.resolution)
  17969. );
  17970. /**
  17971. * The renderer this RenderTexture uses. A RenderTexture can only belong to one renderer at the moment if its webGL.
  17972. *
  17973. * @property renderer
  17974. * @type CanvasRenderer|WebGLRenderer
  17975. */
  17976. this.renderer = renderer || PIXI.defaultRenderer;
  17977. if (this.renderer.type === PIXI.WEBGL_RENDERER)
  17978. {
  17979. var gl = this.renderer.gl;
  17980. this.baseTexture._dirty[gl.id] = false;
  17981. this.textureBuffer = new PIXI.FilterTexture(gl, this.width, this.height, this.baseTexture.scaleMode);
  17982. this.baseTexture._glTextures[gl.id] = this.textureBuffer.texture;
  17983. this.render = this.renderWebGL;
  17984. this.projection = new PIXI.Point(this.width * 0.5, -this.height * 0.5);
  17985. }
  17986. else
  17987. {
  17988. this.render = this.renderCanvas;
  17989. this.textureBuffer = new PIXI.CanvasBuffer(this.width * this.resolution, this.height * this.resolution);
  17990. this.baseTexture.source = this.textureBuffer.canvas;
  17991. }
  17992. /**
  17993. * @property valid
  17994. * @type Boolean
  17995. */
  17996. this.valid = true;
  17997. this.tempMatrix = new Phaser.Matrix();
  17998. this._updateUvs();
  17999. };
  18000. PIXI.RenderTexture.prototype = Object.create(PIXI.Texture.prototype);
  18001. PIXI.RenderTexture.prototype.constructor = PIXI.RenderTexture;
  18002. /**
  18003. * Resizes the RenderTexture.
  18004. *
  18005. * @method resize
  18006. * @param width {Number} The width to resize to.
  18007. * @param height {Number} The height to resize to.
  18008. * @param updateBase {Boolean} Should the baseTexture.width and height values be resized as well?
  18009. */
  18010. PIXI.RenderTexture.prototype.resize = function(width, height, updateBase)
  18011. {
  18012. if (width === this.width && height === this.height)return;
  18013. this.valid = (width > 0 && height > 0);
  18014. this.width = width;
  18015. this.height = height;
  18016. this.frame.width = this.crop.width = width * this.resolution;
  18017. this.frame.height = this.crop.height = height * this.resolution;
  18018. if (updateBase)
  18019. {
  18020. this.baseTexture.width = this.width * this.resolution;
  18021. this.baseTexture.height = this.height * this.resolution;
  18022. }
  18023. if (this.renderer.type === PIXI.WEBGL_RENDERER)
  18024. {
  18025. this.projection.x = this.width / 2;
  18026. this.projection.y = -this.height / 2;
  18027. }
  18028. if(!this.valid)return;
  18029. this.textureBuffer.resize(this.width, this.height);
  18030. };
  18031. /**
  18032. * Clears the RenderTexture.
  18033. *
  18034. * @method clear
  18035. */
  18036. PIXI.RenderTexture.prototype.clear = function()
  18037. {
  18038. if (!this.valid)
  18039. {
  18040. return;
  18041. }
  18042. if (this.renderer.type === PIXI.WEBGL_RENDERER)
  18043. {
  18044. this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer);
  18045. }
  18046. this.textureBuffer.clear();
  18047. };
  18048. /**
  18049. * This function will draw the display object to the texture.
  18050. *
  18051. * @method renderWebGL
  18052. * @param displayObject {DisplayObject} The display object to render this texture on
  18053. * @param [matrix] {Matrix} Optional matrix to apply to the display object before rendering.
  18054. * @param [clear] {Boolean} If true the texture will be cleared before the displayObject is drawn
  18055. * @private
  18056. */
  18057. PIXI.RenderTexture.prototype.renderWebGL = function(displayObject, matrix, clear)
  18058. {
  18059. if (!this.valid || displayObject.alpha === 0)
  18060. {
  18061. return;
  18062. }
  18063. // Let's create a nice matrix to apply to our display object.
  18064. // Frame buffers come in upside down so we need to flip the matrix.
  18065. var wt = displayObject.worldTransform;
  18066. wt.identity();
  18067. wt.translate(0, this.projection.y * 2);
  18068. if (matrix)
  18069. {
  18070. wt.append(matrix);
  18071. }
  18072. wt.scale(1, -1);
  18073. // Time to update all the children of the displayObject with the new matrix.
  18074. for (var i = 0; i < displayObject.children.length; i++)
  18075. {
  18076. displayObject.children[i].updateTransform();
  18077. }
  18078. // Time for the webGL fun stuff!
  18079. var gl = this.renderer.gl;
  18080. gl.viewport(0, 0, this.width * this.resolution, this.height * this.resolution);
  18081. gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer );
  18082. if (clear)
  18083. {
  18084. this.textureBuffer.clear();
  18085. }
  18086. this.renderer.spriteBatch.dirty = true;
  18087. this.renderer.renderDisplayObject(displayObject, this.projection, this.textureBuffer.frameBuffer, matrix);
  18088. this.renderer.spriteBatch.dirty = true;
  18089. };
  18090. /**
  18091. * This function will draw the display object to the texture.
  18092. *
  18093. * @method renderCanvas
  18094. * @param displayObject {DisplayObject} The display object to render this texture on
  18095. * @param [matrix] {Matrix} Optional matrix to apply to the display object before rendering.
  18096. * @param [clear] {Boolean} If true the texture will be cleared before the displayObject is drawn
  18097. * @private
  18098. */
  18099. PIXI.RenderTexture.prototype.renderCanvas = function(displayObject, matrix, clear)
  18100. {
  18101. if (!this.valid || displayObject.alpha === 0)
  18102. {
  18103. return;
  18104. }
  18105. // Let's create a nice matrix to apply to our display object.
  18106. // Frame buffers come in upside down so we need to flip the matrix.
  18107. var wt = displayObject.worldTransform;
  18108. wt.identity();
  18109. if (matrix)
  18110. {
  18111. wt.append(matrix);
  18112. }
  18113. // Time to update all the children of the displayObject with the new matrix (what new matrix? there isn't one!)
  18114. for (var i = 0; i < displayObject.children.length; i++)
  18115. {
  18116. displayObject.children[i].updateTransform();
  18117. }
  18118. if (clear)
  18119. {
  18120. this.textureBuffer.clear();
  18121. }
  18122. var realResolution = this.renderer.resolution;
  18123. this.renderer.resolution = this.resolution;
  18124. this.renderer.renderDisplayObject(displayObject, this.textureBuffer.context, matrix);
  18125. this.renderer.resolution = realResolution;
  18126. };
  18127. /**
  18128. * Will return a HTML Image of the texture
  18129. *
  18130. * @method getImage
  18131. * @return {Image}
  18132. */
  18133. PIXI.RenderTexture.prototype.getImage = function()
  18134. {
  18135. var image = new Image();
  18136. image.src = this.getBase64();
  18137. return image;
  18138. };
  18139. /**
  18140. * Will return a base64 encoded string of this texture. It works by calling RenderTexture.getCanvas and then running toDataURL on that.
  18141. *
  18142. * @method getBase64
  18143. * @return {String} A base64 encoded string of the texture.
  18144. */
  18145. PIXI.RenderTexture.prototype.getBase64 = function()
  18146. {
  18147. return this.getCanvas().toDataURL();
  18148. };
  18149. /**
  18150. * Creates a Canvas element, renders this RenderTexture to it and then returns it.
  18151. *
  18152. * @method getCanvas
  18153. * @return {HTMLCanvasElement} A Canvas element with the texture rendered on.
  18154. */
  18155. PIXI.RenderTexture.prototype.getCanvas = function()
  18156. {
  18157. if (this.renderer.type === PIXI.WEBGL_RENDERER)
  18158. {
  18159. var gl = this.renderer.gl;
  18160. var width = this.textureBuffer.width;
  18161. var height = this.textureBuffer.height;
  18162. var webGLPixels = new Uint8Array(4 * width * height);
  18163. gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer);
  18164. gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webGLPixels);
  18165. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  18166. var tempCanvas = new PIXI.CanvasBuffer(width, height);
  18167. var canvasData = tempCanvas.context.getImageData(0, 0, width, height);
  18168. canvasData.data.set(webGLPixels);
  18169. tempCanvas.context.putImageData(canvasData, 0, 0);
  18170. return tempCanvas.canvas;
  18171. }
  18172. else
  18173. {
  18174. return this.textureBuffer.canvas;
  18175. }
  18176. };
  18177. /**
  18178. * @author Mat Groves http://matgroves.com/ @Doormat23
  18179. */
  18180. /**
  18181. * This is the base class for creating a PIXI filter. Currently only webGL supports filters.
  18182. * If you want to make a custom filter this should be your base class.
  18183. * @class AbstractFilter
  18184. * @constructor
  18185. * @param fragmentSrc {Array} The fragment source in an array of strings.
  18186. * @param uniforms {Object} An object containing the uniforms for this filter.
  18187. */
  18188. PIXI.AbstractFilter = function(fragmentSrc, uniforms)
  18189. {
  18190. /**
  18191. * An array of passes - some filters contain a few steps this array simply stores the steps in a liniear fashion.
  18192. * For example the blur filter has two passes blurX and blurY.
  18193. * @property passes
  18194. * @type Array(Filter)
  18195. * @private
  18196. */
  18197. this.passes = [this];
  18198. /**
  18199. * @property shaders
  18200. * @type Array(Shader)
  18201. * @private
  18202. */
  18203. this.shaders = [];
  18204. /**
  18205. * @property dirty
  18206. * @type Boolean
  18207. */
  18208. this.dirty = true;
  18209. /**
  18210. * @property padding
  18211. * @type Number
  18212. */
  18213. this.padding = 0;
  18214. /**
  18215. * @property uniforms
  18216. * @type object
  18217. * @private
  18218. */
  18219. this.uniforms = uniforms || {};
  18220. /**
  18221. * @property fragmentSrc
  18222. * @type Array
  18223. * @private
  18224. */
  18225. this.fragmentSrc = fragmentSrc || [];
  18226. };
  18227. PIXI.AbstractFilter.prototype.constructor = PIXI.AbstractFilter;
  18228. /**
  18229. * Syncs the uniforms between the class object and the shaders.
  18230. *
  18231. * @method syncUniforms
  18232. */
  18233. PIXI.AbstractFilter.prototype.syncUniforms = function()
  18234. {
  18235. for(var i=0,j=this.shaders.length; i<j; i++)
  18236. {
  18237. this.shaders[i].dirty = true;
  18238. }
  18239. };
  18240. /*
  18241. PIXI.AbstractFilter.prototype.apply = function(frameBuffer)
  18242. {
  18243. // TODO :)
  18244. };
  18245. */
  18246. /**
  18247. * @author Mat Groves http://matgroves.com/
  18248. */
  18249. /**
  18250. *
  18251. * @class Strip
  18252. * @extends DisplayObjectContainer
  18253. * @constructor
  18254. * @param texture {Texture} The texture to use
  18255. * @param width {Number} the width
  18256. * @param height {Number} the height
  18257. *
  18258. */
  18259. PIXI.Strip = function(texture)
  18260. {
  18261. PIXI.DisplayObjectContainer.call( this );
  18262. /**
  18263. * The texture of the strip
  18264. *
  18265. * @property texture
  18266. * @type Texture
  18267. */
  18268. this.texture = texture;
  18269. // set up the main bits..
  18270. this.uvs = new PIXI.Float32Array([0, 1,
  18271. 1, 1,
  18272. 1, 0,
  18273. 0, 1]);
  18274. this.vertices = new PIXI.Float32Array([0, 0,
  18275. 100, 0,
  18276. 100, 100,
  18277. 0, 100]);
  18278. this.colors = new PIXI.Float32Array([1, 1, 1, 1]);
  18279. this.indices = new PIXI.Uint16Array([0, 1, 2, 3]);
  18280. /**
  18281. * Whether the strip is dirty or not
  18282. *
  18283. * @property dirty
  18284. * @type Boolean
  18285. */
  18286. this.dirty = true;
  18287. /**
  18288. * The blend mode to be applied to the sprite. Set to PIXI.blendModes.NORMAL to remove any blend mode.
  18289. *
  18290. * @property blendMode
  18291. * @type Number
  18292. * @default PIXI.blendModes.NORMAL;
  18293. */
  18294. this.blendMode = PIXI.blendModes.NORMAL;
  18295. /**
  18296. * Triangles in canvas mode are automatically antialiased, use this value to force triangles to overlap a bit with each other.
  18297. *
  18298. * @property canvasPadding
  18299. * @type Number
  18300. */
  18301. this.canvasPadding = 0;
  18302. this.drawMode = PIXI.Strip.DrawModes.TRIANGLE_STRIP;
  18303. };
  18304. // constructor
  18305. PIXI.Strip.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
  18306. PIXI.Strip.prototype.constructor = PIXI.Strip;
  18307. PIXI.Strip.prototype._renderWebGL = function(renderSession)
  18308. {
  18309. // if the sprite is not visible or the alpha is 0 then no need to render this element
  18310. if(!this.visible || this.alpha <= 0)return;
  18311. // render triangle strip..
  18312. renderSession.spriteBatch.stop();
  18313. // init! init!
  18314. if(!this._vertexBuffer)this._initWebGL(renderSession);
  18315. renderSession.shaderManager.setShader(renderSession.shaderManager.stripShader);
  18316. this._renderStrip(renderSession);
  18317. ///renderSession.shaderManager.activateDefaultShader();
  18318. renderSession.spriteBatch.start();
  18319. //TODO check culling
  18320. };
  18321. PIXI.Strip.prototype._initWebGL = function(renderSession)
  18322. {
  18323. // build the strip!
  18324. var gl = renderSession.gl;
  18325. this._vertexBuffer = gl.createBuffer();
  18326. this._indexBuffer = gl.createBuffer();
  18327. this._uvBuffer = gl.createBuffer();
  18328. this._colorBuffer = gl.createBuffer();
  18329. gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer);
  18330. gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.DYNAMIC_DRAW);
  18331. gl.bindBuffer(gl.ARRAY_BUFFER, this._uvBuffer);
  18332. gl.bufferData(gl.ARRAY_BUFFER, this.uvs, gl.STATIC_DRAW);
  18333. gl.bindBuffer(gl.ARRAY_BUFFER, this._colorBuffer);
  18334. gl.bufferData(gl.ARRAY_BUFFER, this.colors, gl.STATIC_DRAW);
  18335. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indexBuffer);
  18336. gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW);
  18337. };
  18338. PIXI.Strip.prototype._renderStrip = function(renderSession)
  18339. {
  18340. var gl = renderSession.gl;
  18341. var projection = renderSession.projection,
  18342. offset = renderSession.offset,
  18343. shader = renderSession.shaderManager.stripShader;
  18344. var drawMode = this.drawMode === PIXI.Strip.DrawModes.TRIANGLE_STRIP ? gl.TRIANGLE_STRIP : gl.TRIANGLES;
  18345. // gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mat4Real);
  18346. renderSession.blendModeManager.setBlendMode(this.blendMode);
  18347. // set uniforms
  18348. gl.uniformMatrix3fv(shader.translationMatrix, false, this.worldTransform.toArray(true));
  18349. gl.uniform2f(shader.projectionVector, projection.x, -projection.y);
  18350. gl.uniform2f(shader.offsetVector, -offset.x, -offset.y);
  18351. gl.uniform1f(shader.alpha, this.worldAlpha);
  18352. if(!this.dirty)
  18353. {
  18354. gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer);
  18355. gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices);
  18356. gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0);
  18357. // update the uvs
  18358. gl.bindBuffer(gl.ARRAY_BUFFER, this._uvBuffer);
  18359. gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0);
  18360. gl.activeTexture(gl.TEXTURE0);
  18361. // check if a texture is dirty..
  18362. if(this.texture.baseTexture._dirty[gl.id])
  18363. {
  18364. renderSession.renderer.updateTexture(this.texture.baseTexture);
  18365. }
  18366. else
  18367. {
  18368. // bind the current texture
  18369. gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]);
  18370. }
  18371. // dont need to upload!
  18372. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indexBuffer);
  18373. }
  18374. else
  18375. {
  18376. this.dirty = false;
  18377. gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer);
  18378. gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.STATIC_DRAW);
  18379. gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0);
  18380. // update the uvs
  18381. gl.bindBuffer(gl.ARRAY_BUFFER, this._uvBuffer);
  18382. gl.bufferData(gl.ARRAY_BUFFER, this.uvs, gl.STATIC_DRAW);
  18383. gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0);
  18384. gl.activeTexture(gl.TEXTURE0);
  18385. // check if a texture is dirty..
  18386. if(this.texture.baseTexture._dirty[gl.id])
  18387. {
  18388. renderSession.renderer.updateTexture(this.texture.baseTexture);
  18389. }
  18390. else
  18391. {
  18392. gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]);
  18393. }
  18394. // dont need to upload!
  18395. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indexBuffer);
  18396. gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW);
  18397. }
  18398. //console.log(gl.TRIANGLE_STRIP)
  18399. //
  18400. //
  18401. gl.drawElements(drawMode, this.indices.length, gl.UNSIGNED_SHORT, 0);
  18402. };
  18403. PIXI.Strip.prototype._renderCanvas = function(renderSession)
  18404. {
  18405. var context = renderSession.context;
  18406. var transform = this.worldTransform;
  18407. var tx = (transform.tx * renderSession.resolution) + renderSession.shakeX;
  18408. var ty = (transform.ty * renderSession.resolution) + renderSession.shakeY;
  18409. if (renderSession.roundPixels)
  18410. {
  18411. context.setTransform(transform.a, transform.b, transform.c, transform.d, tx | 0, ty | 0);
  18412. }
  18413. else
  18414. {
  18415. context.setTransform(transform.a, transform.b, transform.c, transform.d, tx, ty);
  18416. }
  18417. if (this.drawMode === PIXI.Strip.DrawModes.TRIANGLE_STRIP)
  18418. {
  18419. this._renderCanvasTriangleStrip(context);
  18420. }
  18421. else
  18422. {
  18423. this._renderCanvasTriangles(context);
  18424. }
  18425. };
  18426. PIXI.Strip.prototype._renderCanvasTriangleStrip = function(context)
  18427. {
  18428. // draw triangles!!
  18429. var vertices = this.vertices;
  18430. var uvs = this.uvs;
  18431. var length = vertices.length / 2;
  18432. this.count++;
  18433. for (var i = 0; i < length - 2; i++) {
  18434. // draw some triangles!
  18435. var index = i * 2;
  18436. this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4));
  18437. }
  18438. };
  18439. PIXI.Strip.prototype._renderCanvasTriangles = function(context)
  18440. {
  18441. // draw triangles!!
  18442. var vertices = this.vertices;
  18443. var uvs = this.uvs;
  18444. var indices = this.indices;
  18445. var length = indices.length;
  18446. this.count++;
  18447. for (var i = 0; i < length; i += 3) {
  18448. // draw some triangles!
  18449. var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2;
  18450. this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2);
  18451. }
  18452. };
  18453. PIXI.Strip.prototype._renderCanvasDrawTriangle = function(context, vertices, uvs, index0, index1, index2)
  18454. {
  18455. var textureSource = this.texture.baseTexture.source;
  18456. var textureWidth = this.texture.width;
  18457. var textureHeight = this.texture.height;
  18458. var x0 = vertices[index0], x1 = vertices[index1], x2 = vertices[index2];
  18459. var y0 = vertices[index0 + 1], y1 = vertices[index1 + 1], y2 = vertices[index2 + 1];
  18460. var u0 = uvs[index0] * textureWidth, u1 = uvs[index1] * textureWidth, u2 = uvs[index2] * textureWidth;
  18461. var v0 = uvs[index0 + 1] * textureHeight, v1 = uvs[index1 + 1] * textureHeight, v2 = uvs[index2 + 1] * textureHeight;
  18462. if (this.canvasPadding > 0) {
  18463. var paddingX = this.canvasPadding / this.worldTransform.a;
  18464. var paddingY = this.canvasPadding / this.worldTransform.d;
  18465. var centerX = (x0 + x1 + x2) / 3;
  18466. var centerY = (y0 + y1 + y2) / 3;
  18467. var normX = x0 - centerX;
  18468. var normY = y0 - centerY;
  18469. var dist = Math.sqrt(normX * normX + normY * normY);
  18470. x0 = centerX + (normX / dist) * (dist + paddingX);
  18471. y0 = centerY + (normY / dist) * (dist + paddingY);
  18472. //
  18473. normX = x1 - centerX;
  18474. normY = y1 - centerY;
  18475. dist = Math.sqrt(normX * normX + normY * normY);
  18476. x1 = centerX + (normX / dist) * (dist + paddingX);
  18477. y1 = centerY + (normY / dist) * (dist + paddingY);
  18478. normX = x2 - centerX;
  18479. normY = y2 - centerY;
  18480. dist = Math.sqrt(normX * normX + normY * normY);
  18481. x2 = centerX + (normX / dist) * (dist + paddingX);
  18482. y2 = centerY + (normY / dist) * (dist + paddingY);
  18483. }
  18484. context.save();
  18485. context.beginPath();
  18486. context.moveTo(x0, y0);
  18487. context.lineTo(x1, y1);
  18488. context.lineTo(x2, y2);
  18489. context.closePath();
  18490. context.clip();
  18491. // Compute matrix transform
  18492. var delta = (u0 * v1) + (v0 * u2) + (u1 * v2) - (v1 * u2) - (v0 * u1) - (u0 * v2);
  18493. var deltaA = (x0 * v1) + (v0 * x2) + (x1 * v2) - (v1 * x2) - (v0 * x1) - (x0 * v2);
  18494. var deltaB = (u0 * x1) + (x0 * u2) + (u1 * x2) - (x1 * u2) - (x0 * u1) - (u0 * x2);
  18495. var deltaC = (u0 * v1 * x2) + (v0 * x1 * u2) + (x0 * u1 * v2) - (x0 * v1 * u2) - (v0 * u1 * x2) - (u0 * x1 * v2);
  18496. var deltaD = (y0 * v1) + (v0 * y2) + (y1 * v2) - (v1 * y2) - (v0 * y1) - (y0 * v2);
  18497. var deltaE = (u0 * y1) + (y0 * u2) + (u1 * y2) - (y1 * u2) - (y0 * u1) - (u0 * y2);
  18498. var deltaF = (u0 * v1 * y2) + (v0 * y1 * u2) + (y0 * u1 * v2) - (y0 * v1 * u2) - (v0 * u1 * y2) - (u0 * y1 * v2);
  18499. context.transform(deltaA / delta, deltaD / delta,
  18500. deltaB / delta, deltaE / delta,
  18501. deltaC / delta, deltaF / delta);
  18502. context.drawImage(textureSource, 0, 0);
  18503. context.restore();
  18504. };
  18505. /**
  18506. * Renders a flat strip
  18507. *
  18508. * @method renderStripFlat
  18509. * @param strip {Strip} The Strip to render
  18510. * @private
  18511. */
  18512. PIXI.Strip.prototype.renderStripFlat = function(strip)
  18513. {
  18514. var context = this.context;
  18515. var vertices = strip.vertices;
  18516. var length = vertices.length/2;
  18517. this.count++;
  18518. context.beginPath();
  18519. for (var i=1; i < length-2; i++)
  18520. {
  18521. // draw some triangles!
  18522. var index = i*2;
  18523. var x0 = vertices[index], x1 = vertices[index+2], x2 = vertices[index+4];
  18524. var y0 = vertices[index+1], y1 = vertices[index+3], y2 = vertices[index+5];
  18525. context.moveTo(x0, y0);
  18526. context.lineTo(x1, y1);
  18527. context.lineTo(x2, y2);
  18528. }
  18529. context.fillStyle = '#FF0000';
  18530. context.fill();
  18531. context.closePath();
  18532. };
  18533. /*
  18534. PIXI.Strip.prototype.setTexture = function(texture)
  18535. {
  18536. //TODO SET THE TEXTURES
  18537. //TODO VISIBILITY
  18538. // stop current texture
  18539. this.texture = texture;
  18540. this.width = texture.frame.width;
  18541. this.height = texture.frame.height;
  18542. this.updateFrame = true;
  18543. };
  18544. */
  18545. /**
  18546. * When the texture is updated, this event will fire to update the scale and frame
  18547. *
  18548. * @method onTextureUpdate
  18549. * @param event
  18550. * @private
  18551. */
  18552. PIXI.Strip.prototype.onTextureUpdate = function()
  18553. {
  18554. this.updateFrame = true;
  18555. };
  18556. /**
  18557. * Returns the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account.
  18558. *
  18559. * @method getBounds
  18560. * @param matrix {Matrix} the transformation matrix of the sprite
  18561. * @return {Rectangle} the framing rectangle
  18562. */
  18563. PIXI.Strip.prototype.getBounds = function(matrix)
  18564. {
  18565. var worldTransform = matrix || this.worldTransform;
  18566. var a = worldTransform.a;
  18567. var b = worldTransform.b;
  18568. var c = worldTransform.c;
  18569. var d = worldTransform.d;
  18570. var tx = worldTransform.tx;
  18571. var ty = worldTransform.ty;
  18572. var maxX = -Infinity;
  18573. var maxY = -Infinity;
  18574. var minX = Infinity;
  18575. var minY = Infinity;
  18576. var vertices = this.vertices;
  18577. for (var i = 0, n = vertices.length; i < n; i += 2)
  18578. {
  18579. var rawX = vertices[i], rawY = vertices[i + 1];
  18580. var x = (a * rawX) + (c * rawY) + tx;
  18581. var y = (d * rawY) + (b * rawX) + ty;
  18582. minX = x < minX ? x : minX;
  18583. minY = y < minY ? y : minY;
  18584. maxX = x > maxX ? x : maxX;
  18585. maxY = y > maxY ? y : maxY;
  18586. }
  18587. if (minX === -Infinity || maxY === Infinity)
  18588. {
  18589. return PIXI.EmptyRectangle;
  18590. }
  18591. var bounds = this._bounds;
  18592. bounds.x = minX;
  18593. bounds.width = maxX - minX;
  18594. bounds.y = minY;
  18595. bounds.height = maxY - minY;
  18596. // store a reference so that if this function gets called again in the render cycle we do not have to recalculate
  18597. this._currentBounds = bounds;
  18598. return bounds;
  18599. };
  18600. /**
  18601. * Different drawing buffer modes supported
  18602. *
  18603. * @property
  18604. * @type {{TRIANGLE_STRIP: number, TRIANGLES: number}}
  18605. * @static
  18606. */
  18607. PIXI.Strip.DrawModes = {
  18608. TRIANGLE_STRIP: 0,
  18609. TRIANGLES: 1
  18610. };
  18611. /**
  18612. * @author Mat Groves http://matgroves.com/ @Doormat23
  18613. * @copyright Mat Groves, Rovanion Luckey
  18614. */
  18615. /**
  18616. *
  18617. * @class Rope
  18618. * @constructor
  18619. * @extends Strip
  18620. * @param {Texture} texture - The texture to use on the rope.
  18621. * @param {Array} points - An array of {PIXI.Point}.
  18622. *
  18623. */
  18624. PIXI.Rope = function(texture, points)
  18625. {
  18626. PIXI.Strip.call( this, texture );
  18627. this.points = points;
  18628. this.vertices = new PIXI.Float32Array(points.length * 4);
  18629. this.uvs = new PIXI.Float32Array(points.length * 4);
  18630. this.colors = new PIXI.Float32Array(points.length * 2);
  18631. this.indices = new PIXI.Uint16Array(points.length * 2);
  18632. this.refresh();
  18633. };
  18634. // constructor
  18635. PIXI.Rope.prototype = Object.create( PIXI.Strip.prototype );
  18636. PIXI.Rope.prototype.constructor = PIXI.Rope;
  18637. /*
  18638. * Refreshes
  18639. *
  18640. * @method refresh
  18641. */
  18642. PIXI.Rope.prototype.refresh = function()
  18643. {
  18644. var points = this.points;
  18645. if(points.length < 1) return;
  18646. var uvs = this.uvs;
  18647. var lastPoint = points[0];
  18648. var indices = this.indices;
  18649. var colors = this.colors;
  18650. this.count-=0.2;
  18651. uvs[0] = 0;
  18652. uvs[1] = 0;
  18653. uvs[2] = 0;
  18654. uvs[3] = 1;
  18655. colors[0] = 1;
  18656. colors[1] = 1;
  18657. indices[0] = 0;
  18658. indices[1] = 1;
  18659. var total = points.length,
  18660. point, index, amount;
  18661. for (var i = 1; i < total; i++)
  18662. {
  18663. point = points[i];
  18664. index = i * 4;
  18665. // time to do some smart drawing!
  18666. amount = i / (total-1);
  18667. if(i%2)
  18668. {
  18669. uvs[index] = amount;
  18670. uvs[index+1] = 0;
  18671. uvs[index+2] = amount;
  18672. uvs[index+3] = 1;
  18673. }
  18674. else
  18675. {
  18676. uvs[index] = amount;
  18677. uvs[index+1] = 0;
  18678. uvs[index+2] = amount;
  18679. uvs[index+3] = 1;
  18680. }
  18681. index = i * 2;
  18682. colors[index] = 1;
  18683. colors[index+1] = 1;
  18684. index = i * 2;
  18685. indices[index] = index;
  18686. indices[index + 1] = index + 1;
  18687. lastPoint = point;
  18688. }
  18689. };
  18690. /*
  18691. * Updates the object transform for rendering
  18692. *
  18693. * @method updateTransform
  18694. * @private
  18695. */
  18696. PIXI.Rope.prototype.updateTransform = function()
  18697. {
  18698. var points = this.points;
  18699. if(points.length < 1)return;
  18700. var lastPoint = points[0];
  18701. var nextPoint;
  18702. var perp = {x:0, y:0};
  18703. this.count-=0.2;
  18704. var vertices = this.vertices;
  18705. var total = points.length,
  18706. point, index, ratio, perpLength, num;
  18707. for (var i = 0; i < total; i++)
  18708. {
  18709. point = points[i];
  18710. index = i * 4;
  18711. if(i < points.length-1)
  18712. {
  18713. nextPoint = points[i+1];
  18714. }
  18715. else
  18716. {
  18717. nextPoint = point;
  18718. }
  18719. perp.y = -(nextPoint.x - lastPoint.x);
  18720. perp.x = nextPoint.y - lastPoint.y;
  18721. ratio = (1 - (i / (total-1))) * 10;
  18722. if(ratio > 1) ratio = 1;
  18723. perpLength = Math.sqrt(perp.x * perp.x + perp.y * perp.y);
  18724. num = this.texture.height / 2; //(20 + Math.abs(Math.sin((i + this.count) * 0.3) * 50) )* ratio;
  18725. perp.x /= perpLength;
  18726. perp.y /= perpLength;
  18727. perp.x *= num;
  18728. perp.y *= num;
  18729. vertices[index] = point.x + perp.x;
  18730. vertices[index+1] = point.y + perp.y;
  18731. vertices[index+2] = point.x - perp.x;
  18732. vertices[index+3] = point.y - perp.y;
  18733. lastPoint = point;
  18734. }
  18735. PIXI.DisplayObjectContainer.prototype.updateTransform.call( this );
  18736. };
  18737. /*
  18738. * Sets the texture that the Rope will use
  18739. *
  18740. * @method setTexture
  18741. * @param texture {Texture} the texture that will be used
  18742. */
  18743. PIXI.Rope.prototype.setTexture = function(texture)
  18744. {
  18745. // stop current texture
  18746. this.texture = texture;
  18747. //this.updateFrame = true;
  18748. };
  18749. /**
  18750. * @author Mat Groves http://matgroves.com/
  18751. */
  18752. /**
  18753. * A tiling sprite is a fast way of rendering a tiling image
  18754. *
  18755. * @class TilingSprite
  18756. * @extends Sprite
  18757. * @constructor
  18758. * @param texture {Texture} the texture of the tiling sprite
  18759. * @param width {Number} the width of the tiling sprite
  18760. * @param height {Number} the height of the tiling sprite
  18761. */
  18762. PIXI.TilingSprite = function(texture, width, height)
  18763. {
  18764. PIXI.Sprite.call(this, texture);
  18765. /**
  18766. * The width of the tiling sprite
  18767. *
  18768. * @property width
  18769. * @type Number
  18770. */
  18771. this._width = width || 128;
  18772. /**
  18773. * The height of the tiling sprite
  18774. *
  18775. * @property height
  18776. * @type Number
  18777. */
  18778. this._height = height || 128;
  18779. /**
  18780. * The scaling of the image that is being tiled
  18781. *
  18782. * @property tileScale
  18783. * @type Point
  18784. */
  18785. this.tileScale = new PIXI.Point(1, 1);
  18786. /**
  18787. * A point that represents the scale of the texture object
  18788. *
  18789. * @property tileScaleOffset
  18790. * @type Point
  18791. */
  18792. this.tileScaleOffset = new PIXI.Point(1, 1);
  18793. /**
  18794. * The offset position of the image that is being tiled
  18795. *
  18796. * @property tilePosition
  18797. * @type Point
  18798. */
  18799. this.tilePosition = new PIXI.Point();
  18800. /**
  18801. * Whether this sprite is renderable or not
  18802. *
  18803. * @property renderable
  18804. * @type Boolean
  18805. * @default true
  18806. */
  18807. this.renderable = true;
  18808. /**
  18809. * The tint applied to the sprite. This is a hex value
  18810. *
  18811. * @property tint
  18812. * @type Number
  18813. * @default 0xFFFFFF
  18814. */
  18815. this.tint = 0xFFFFFF;
  18816. /**
  18817. * If enabled a green rectangle will be drawn behind the generated tiling texture, allowing you to visually
  18818. * debug the texture being used.
  18819. *
  18820. * @property textureDebug
  18821. * @type Boolean
  18822. */
  18823. this.textureDebug = false;
  18824. /**
  18825. * The blend mode to be applied to the sprite
  18826. *
  18827. * @property blendMode
  18828. * @type Number
  18829. * @default PIXI.blendModes.NORMAL;
  18830. */
  18831. this.blendMode = PIXI.blendModes.NORMAL;
  18832. /**
  18833. * The CanvasBuffer object that the tiled texture is drawn to.
  18834. *
  18835. * @property canvasBuffer
  18836. * @type PIXI.CanvasBuffer
  18837. */
  18838. this.canvasBuffer = null;
  18839. /**
  18840. * An internal Texture object that holds the tiling texture that was generated from TilingSprite.texture.
  18841. *
  18842. * @property tilingTexture
  18843. * @type PIXI.Texture
  18844. */
  18845. this.tilingTexture = null;
  18846. /**
  18847. * The Context fill pattern that is used to draw the TilingSprite in Canvas mode only (will be null in WebGL).
  18848. *
  18849. * @property tilePattern
  18850. * @type PIXI.Texture
  18851. */
  18852. this.tilePattern = null;
  18853. /**
  18854. * If true the TilingSprite will run generateTexture on its **next** render pass.
  18855. * This is set by the likes of Phaser.LoadTexture.setFrame.
  18856. *
  18857. * @property refreshTexture
  18858. * @type Boolean
  18859. * @default true
  18860. */
  18861. this.refreshTexture = true;
  18862. this.frameWidth = 0;
  18863. this.frameHeight = 0;
  18864. };
  18865. PIXI.TilingSprite.prototype = Object.create(PIXI.Sprite.prototype);
  18866. PIXI.TilingSprite.prototype.constructor = PIXI.TilingSprite;
  18867. PIXI.TilingSprite.prototype.setTexture = function(texture)
  18868. {
  18869. if (this.texture !== texture)
  18870. {
  18871. this.texture = texture;
  18872. this.refreshTexture = true;
  18873. this.cachedTint = 0xFFFFFF;
  18874. }
  18875. };
  18876. /**
  18877. * Renders the object using the WebGL renderer
  18878. *
  18879. * @method _renderWebGL
  18880. * @param renderSession {RenderSession}
  18881. * @private
  18882. */
  18883. PIXI.TilingSprite.prototype._renderWebGL = function(renderSession)
  18884. {
  18885. if (!this.visible || !this.renderable || this.alpha === 0)
  18886. {
  18887. return;
  18888. }
  18889. if (this._mask)
  18890. {
  18891. renderSession.spriteBatch.stop();
  18892. renderSession.maskManager.pushMask(this.mask, renderSession);
  18893. renderSession.spriteBatch.start();
  18894. }
  18895. if (this._filters)
  18896. {
  18897. renderSession.spriteBatch.flush();
  18898. renderSession.filterManager.pushFilter(this._filterBlock);
  18899. }
  18900. if (this.refreshTexture)
  18901. {
  18902. this.generateTilingTexture(true, renderSession);
  18903. if (this.tilingTexture)
  18904. {
  18905. if (this.tilingTexture.needsUpdate)
  18906. {
  18907. renderSession.renderer.updateTexture(this.tilingTexture.baseTexture);
  18908. this.tilingTexture.needsUpdate = false;
  18909. }
  18910. }
  18911. else
  18912. {
  18913. return;
  18914. }
  18915. }
  18916. renderSession.spriteBatch.renderTilingSprite(this);
  18917. for (var i = 0; i < this.children.length; i++)
  18918. {
  18919. this.children[i]._renderWebGL(renderSession);
  18920. }
  18921. renderSession.spriteBatch.stop();
  18922. if (this._filters)
  18923. {
  18924. renderSession.filterManager.popFilter();
  18925. }
  18926. if (this._mask)
  18927. {
  18928. renderSession.maskManager.popMask(this._mask, renderSession);
  18929. }
  18930. renderSession.spriteBatch.start();
  18931. };
  18932. /**
  18933. * Renders the object using the Canvas renderer
  18934. *
  18935. * @method _renderCanvas
  18936. * @param renderSession {RenderSession}
  18937. * @private
  18938. */
  18939. PIXI.TilingSprite.prototype._renderCanvas = function(renderSession)
  18940. {
  18941. if (!this.visible || !this.renderable || this.alpha === 0)
  18942. {
  18943. return;
  18944. }
  18945. var context = renderSession.context;
  18946. if (this._mask)
  18947. {
  18948. renderSession.maskManager.pushMask(this._mask, renderSession);
  18949. }
  18950. context.globalAlpha = this.worldAlpha;
  18951. var wt = this.worldTransform;
  18952. var resolution = renderSession.resolution;
  18953. var tx = (wt.tx * resolution) + renderSession.shakeX;
  18954. var ty = (wt.ty * resolution) + renderSession.shakeY;
  18955. context.setTransform(wt.a * resolution, wt.b * resolution, wt.c * resolution, wt.d * resolution, tx, ty);
  18956. if (this.refreshTexture)
  18957. {
  18958. this.generateTilingTexture(false, renderSession);
  18959. if (this.tilingTexture)
  18960. {
  18961. this.tilePattern = context.createPattern(this.tilingTexture.baseTexture.source, 'repeat');
  18962. }
  18963. else
  18964. {
  18965. return;
  18966. }
  18967. }
  18968. var sessionBlendMode = renderSession.currentBlendMode;
  18969. // Check blend mode
  18970. if (this.blendMode !== renderSession.currentBlendMode)
  18971. {
  18972. renderSession.currentBlendMode = this.blendMode;
  18973. context.globalCompositeOperation = PIXI.blendModesCanvas[renderSession.currentBlendMode];
  18974. }
  18975. var tilePosition = this.tilePosition;
  18976. var tileScale = this.tileScale;
  18977. tilePosition.x %= this.tilingTexture.baseTexture.width;
  18978. tilePosition.y %= this.tilingTexture.baseTexture.height;
  18979. // Translate
  18980. context.scale(tileScale.x, tileScale.y);
  18981. context.translate(tilePosition.x + (this.anchor.x * -this._width), tilePosition.y + (this.anchor.y * -this._height));
  18982. context.fillStyle = this.tilePattern;
  18983. var tx = -tilePosition.x;
  18984. var ty = -tilePosition.y;
  18985. var tw = this._width / tileScale.x;
  18986. var th = this._height / tileScale.y;
  18987. // Allow for pixel rounding
  18988. if (renderSession.roundPixels)
  18989. {
  18990. tx |= 0;
  18991. ty |= 0;
  18992. tw |= 0;
  18993. th |= 0;
  18994. }
  18995. context.fillRect(tx, ty, tw, th);
  18996. // Translate back again
  18997. context.scale(1 / tileScale.x, 1 / tileScale.y);
  18998. context.translate(-tilePosition.x + (this.anchor.x * this._width), -tilePosition.y + (this.anchor.y * this._height));
  18999. if (this._mask)
  19000. {
  19001. renderSession.maskManager.popMask(renderSession);
  19002. }
  19003. for (var i = 0; i < this.children.length; i++)
  19004. {
  19005. this.children[i]._renderCanvas(renderSession);
  19006. }
  19007. // Reset blend mode
  19008. if (sessionBlendMode !== this.blendMode)
  19009. {
  19010. renderSession.currentBlendMode = sessionBlendMode;
  19011. context.globalCompositeOperation = PIXI.blendModesCanvas[sessionBlendMode];
  19012. }
  19013. };
  19014. /**
  19015. * When the texture is updated, this event will fire to update the scale and frame
  19016. *
  19017. * @method onTextureUpdate
  19018. * @param event
  19019. * @private
  19020. */
  19021. PIXI.TilingSprite.prototype.onTextureUpdate = function()
  19022. {
  19023. // overriding the sprite version of this!
  19024. };
  19025. /**
  19026. *
  19027. * @method generateTilingTexture
  19028. *
  19029. * @param forcePowerOfTwo {Boolean} Whether we want to force the texture to be a power of two
  19030. * @param renderSession {RenderSession}
  19031. */
  19032. PIXI.TilingSprite.prototype.generateTilingTexture = function(forcePowerOfTwo, renderSession)
  19033. {
  19034. if (!this.texture.baseTexture.hasLoaded)
  19035. {
  19036. return;
  19037. }
  19038. var texture = this.texture;
  19039. var frame = texture.frame;
  19040. var targetWidth = this._frame.sourceSizeW || this._frame.width;
  19041. var targetHeight = this._frame.sourceSizeH || this._frame.height;
  19042. var dx = 0;
  19043. var dy = 0;
  19044. if (this._frame.trimmed)
  19045. {
  19046. dx = this._frame.spriteSourceSizeX;
  19047. dy = this._frame.spriteSourceSizeY;
  19048. }
  19049. if (forcePowerOfTwo)
  19050. {
  19051. targetWidth = PIXI.getNextPowerOfTwo(targetWidth);
  19052. targetHeight = PIXI.getNextPowerOfTwo(targetHeight);
  19053. }
  19054. if (this.canvasBuffer)
  19055. {
  19056. this.canvasBuffer.resize(targetWidth, targetHeight);
  19057. this.tilingTexture.baseTexture.width = targetWidth;
  19058. this.tilingTexture.baseTexture.height = targetHeight;
  19059. this.tilingTexture.needsUpdate = true;
  19060. }
  19061. else
  19062. {
  19063. this.canvasBuffer = new PIXI.CanvasBuffer(targetWidth, targetHeight);
  19064. this.tilingTexture = PIXI.Texture.fromCanvas(this.canvasBuffer.canvas);
  19065. this.tilingTexture.isTiling = true;
  19066. this.tilingTexture.needsUpdate = true;
  19067. }
  19068. if (this.textureDebug)
  19069. {
  19070. this.canvasBuffer.context.strokeStyle = '#00ff00';
  19071. this.canvasBuffer.context.strokeRect(0, 0, targetWidth, targetHeight);
  19072. }
  19073. // If a sprite sheet we need this:
  19074. var w = texture.crop.width;
  19075. var h = texture.crop.height;
  19076. if (w !== targetWidth || h !== targetHeight)
  19077. {
  19078. w = targetWidth;
  19079. h = targetHeight;
  19080. }
  19081. this.canvasBuffer.context.drawImage(texture.baseTexture.source,
  19082. texture.crop.x,
  19083. texture.crop.y,
  19084. texture.crop.width,
  19085. texture.crop.height,
  19086. dx,
  19087. dy,
  19088. w,
  19089. h);
  19090. this.tileScaleOffset.x = frame.width / targetWidth;
  19091. this.tileScaleOffset.y = frame.height / targetHeight;
  19092. this.refreshTexture = false;
  19093. this.tilingTexture.baseTexture._powerOf2 = true;
  19094. };
  19095. /**
  19096. * Returns the framing rectangle of the sprite as a PIXI.Rectangle object
  19097. *
  19098. * @method getBounds
  19099. * @return {Rectangle} the framing rectangle
  19100. */
  19101. PIXI.TilingSprite.prototype.getBounds = function()
  19102. {
  19103. var width = this._width;
  19104. var height = this._height;
  19105. var w0 = width * (1-this.anchor.x);
  19106. var w1 = width * -this.anchor.x;
  19107. var h0 = height * (1-this.anchor.y);
  19108. var h1 = height * -this.anchor.y;
  19109. var worldTransform = this.worldTransform;
  19110. var a = worldTransform.a;
  19111. var b = worldTransform.b;
  19112. var c = worldTransform.c;
  19113. var d = worldTransform.d;
  19114. var tx = worldTransform.tx;
  19115. var ty = worldTransform.ty;
  19116. var x1 = a * w1 + c * h1 + tx;
  19117. var y1 = d * h1 + b * w1 + ty;
  19118. var x2 = a * w0 + c * h1 + tx;
  19119. var y2 = d * h1 + b * w0 + ty;
  19120. var x3 = a * w0 + c * h0 + tx;
  19121. var y3 = d * h0 + b * w0 + ty;
  19122. var x4 = a * w1 + c * h0 + tx;
  19123. var y4 = d * h0 + b * w1 + ty;
  19124. var maxX = -Infinity;
  19125. var maxY = -Infinity;
  19126. var minX = Infinity;
  19127. var minY = Infinity;
  19128. minX = x1 < minX ? x1 : minX;
  19129. minX = x2 < minX ? x2 : minX;
  19130. minX = x3 < minX ? x3 : minX;
  19131. minX = x4 < minX ? x4 : minX;
  19132. minY = y1 < minY ? y1 : minY;
  19133. minY = y2 < minY ? y2 : minY;
  19134. minY = y3 < minY ? y3 : minY;
  19135. minY = y4 < minY ? y4 : minY;
  19136. maxX = x1 > maxX ? x1 : maxX;
  19137. maxX = x2 > maxX ? x2 : maxX;
  19138. maxX = x3 > maxX ? x3 : maxX;
  19139. maxX = x4 > maxX ? x4 : maxX;
  19140. maxY = y1 > maxY ? y1 : maxY;
  19141. maxY = y2 > maxY ? y2 : maxY;
  19142. maxY = y3 > maxY ? y3 : maxY;
  19143. maxY = y4 > maxY ? y4 : maxY;
  19144. var bounds = this._bounds;
  19145. bounds.x = minX;
  19146. bounds.width = maxX - minX;
  19147. bounds.y = minY;
  19148. bounds.height = maxY - minY;
  19149. // store a reference so that if this function gets called again in the render cycle we do not have to recalculate
  19150. this._currentBounds = bounds;
  19151. return bounds;
  19152. };
  19153. PIXI.TilingSprite.prototype.destroy = function () {
  19154. PIXI.Sprite.prototype.destroy.call(this);
  19155. if (this.canvasBuffer)
  19156. {
  19157. this.canvasBuffer.destroy();
  19158. this.canvasBuffer = null;
  19159. }
  19160. this.tileScale = null;
  19161. this.tileScaleOffset = null;
  19162. this.tilePosition = null;
  19163. if (this.tilingTexture)
  19164. {
  19165. this.tilingTexture.destroy(true);
  19166. this.tilingTexture = null;
  19167. }
  19168. };
  19169. /**
  19170. * The width of the sprite, setting this will actually modify the scale to achieve the value set
  19171. *
  19172. * @property width
  19173. * @type Number
  19174. */
  19175. Object.defineProperty(PIXI.TilingSprite.prototype, 'width', {
  19176. get: function() {
  19177. return this._width;
  19178. },
  19179. set: function(value) {
  19180. this._width = value;
  19181. }
  19182. });
  19183. /**
  19184. * The height of the TilingSprite, setting this will actually modify the scale to achieve the value set
  19185. *
  19186. * @property height
  19187. * @type Number
  19188. */
  19189. Object.defineProperty(PIXI.TilingSprite.prototype, 'height', {
  19190. get: function() {
  19191. return this._height;
  19192. },
  19193. set: function(value) {
  19194. this._height = value;
  19195. }
  19196. });
  19197. /**
  19198. * @author Mat Groves http://matgroves.com/ @Doormat23
  19199. */
  19200. if (typeof exports !== 'undefined') {
  19201. if (typeof module !== 'undefined' && module.exports) {
  19202. exports = module.exports = PIXI;
  19203. }
  19204. exports.PIXI = PIXI;
  19205. } else if (typeof define !== 'undefined' && define.amd) {
  19206. define('PIXI', (function() { return root.PIXI = PIXI; })() );
  19207. } else {
  19208. root.PIXI = PIXI;
  19209. }
  19210. return PIXI;
  19211. }).call(this);
  19212. /**
  19213. * @author Richard Davey <rich@photonstorm.com>
  19214. * @copyright 2016 Photon Storm Ltd.
  19215. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  19216. */
  19217. (function(){
  19218. var root = this;
  19219. /* global Phaser:true */
  19220. /**
  19221. * @author Richard Davey <rich@photonstorm.com>
  19222. * @copyright 2016 Photon Storm Ltd.
  19223. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  19224. */
  19225. /**
  19226. * @namespace Phaser
  19227. */
  19228. var Phaser = Phaser || {
  19229. /**
  19230. * The Phaser version number.
  19231. * @constant
  19232. * @type {string}
  19233. */
  19234. VERSION: '2.4.7',
  19235. /**
  19236. * An array of Phaser game instances.
  19237. * @constant
  19238. * @type {array}
  19239. */
  19240. GAMES: [],
  19241. /**
  19242. * AUTO renderer - picks between WebGL or Canvas based on device.
  19243. * @constant
  19244. * @type {integer}
  19245. */
  19246. AUTO: 0,
  19247. /**
  19248. * Canvas Renderer.
  19249. * @constant
  19250. * @type {integer}
  19251. */
  19252. CANVAS: 1,
  19253. /**
  19254. * WebGL Renderer.
  19255. * @constant
  19256. * @type {integer}
  19257. */
  19258. WEBGL: 2,
  19259. /**
  19260. * Headless renderer (not visual output)
  19261. * @constant
  19262. * @type {integer}
  19263. */
  19264. HEADLESS: 3,
  19265. /**
  19266. * Direction constant.
  19267. * @constant
  19268. * @type {integer}
  19269. */
  19270. NONE: 0,
  19271. /**
  19272. * Direction constant.
  19273. * @constant
  19274. * @type {integer}
  19275. */
  19276. LEFT: 1,
  19277. /**
  19278. * Direction constant.
  19279. * @constant
  19280. * @type {integer}
  19281. */
  19282. RIGHT: 2,
  19283. /**
  19284. * Direction constant.
  19285. * @constant
  19286. * @type {integer}
  19287. */
  19288. UP: 3,
  19289. /**
  19290. * Direction constant.
  19291. * @constant
  19292. * @type {integer}
  19293. */
  19294. DOWN: 4,
  19295. /**
  19296. * Game Object type.
  19297. * @constant
  19298. * @type {integer}
  19299. */
  19300. SPRITE: 0,
  19301. /**
  19302. * Game Object type.
  19303. * @constant
  19304. * @type {integer}
  19305. */
  19306. BUTTON: 1,
  19307. /**
  19308. * Game Object type.
  19309. * @constant
  19310. * @type {integer}
  19311. */
  19312. IMAGE: 2,
  19313. /**
  19314. * Game Object type.
  19315. * @constant
  19316. * @type {integer}
  19317. */
  19318. GRAPHICS: 3,
  19319. /**
  19320. * Game Object type.
  19321. * @constant
  19322. * @type {integer}
  19323. */
  19324. TEXT: 4,
  19325. /**
  19326. * Game Object type.
  19327. * @constant
  19328. * @type {integer}
  19329. */
  19330. TILESPRITE: 5,
  19331. /**
  19332. * Game Object type.
  19333. * @constant
  19334. * @type {integer}
  19335. */
  19336. BITMAPTEXT: 6,
  19337. /**
  19338. * Game Object type.
  19339. * @constant
  19340. * @type {integer}
  19341. */
  19342. GROUP: 7,
  19343. /**
  19344. * Game Object type.
  19345. * @constant
  19346. * @type {integer}
  19347. */
  19348. RENDERTEXTURE: 8,
  19349. /**
  19350. * Game Object type.
  19351. * @constant
  19352. * @type {integer}
  19353. */
  19354. TILEMAP: 9,
  19355. /**
  19356. * Game Object type.
  19357. * @constant
  19358. * @type {integer}
  19359. */
  19360. TILEMAPLAYER: 10,
  19361. /**
  19362. * Game Object type.
  19363. * @constant
  19364. * @type {integer}
  19365. */
  19366. EMITTER: 11,
  19367. /**
  19368. * Game Object type.
  19369. * @constant
  19370. * @type {integer}
  19371. */
  19372. POLYGON: 12,
  19373. /**
  19374. * Game Object type.
  19375. * @constant
  19376. * @type {integer}
  19377. */
  19378. BITMAPDATA: 13,
  19379. /**
  19380. * Game Object type.
  19381. * @constant
  19382. * @type {integer}
  19383. */
  19384. CANVAS_FILTER: 14,
  19385. /**
  19386. * Game Object type.
  19387. * @constant
  19388. * @type {integer}
  19389. */
  19390. WEBGL_FILTER: 15,
  19391. /**
  19392. * Game Object type.
  19393. * @constant
  19394. * @type {integer}
  19395. */
  19396. ELLIPSE: 16,
  19397. /**
  19398. * Game Object type.
  19399. * @constant
  19400. * @type {integer}
  19401. */
  19402. SPRITEBATCH: 17,
  19403. /**
  19404. * Game Object type.
  19405. * @constant
  19406. * @type {integer}
  19407. */
  19408. RETROFONT: 18,
  19409. /**
  19410. * Game Object type.
  19411. * @constant
  19412. * @type {integer}
  19413. */
  19414. POINTER: 19,
  19415. /**
  19416. * Game Object type.
  19417. * @constant
  19418. * @type {integer}
  19419. */
  19420. ROPE: 20,
  19421. /**
  19422. * Game Object type.
  19423. * @constant
  19424. * @type {integer}
  19425. */
  19426. CIRCLE: 21,
  19427. /**
  19428. * Game Object type.
  19429. * @constant
  19430. * @type {integer}
  19431. */
  19432. RECTANGLE: 22,
  19433. /**
  19434. * Game Object type.
  19435. * @constant
  19436. * @type {integer}
  19437. */
  19438. LINE: 23,
  19439. /**
  19440. * Game Object type.
  19441. * @constant
  19442. * @type {integer}
  19443. */
  19444. MATRIX: 24,
  19445. /**
  19446. * Game Object type.
  19447. * @constant
  19448. * @type {integer}
  19449. */
  19450. POINT: 25,
  19451. /**
  19452. * Game Object type.
  19453. * @constant
  19454. * @type {integer}
  19455. */
  19456. ROUNDEDRECTANGLE: 26,
  19457. /**
  19458. * Game Object type.
  19459. * @constant
  19460. * @type {integer}
  19461. */
  19462. CREATURE: 27,
  19463. /**
  19464. * Game Object type.
  19465. * @constant
  19466. * @type {integer}
  19467. */
  19468. VIDEO: 28,
  19469. /**
  19470. * Game Object type.
  19471. * @constant
  19472. * @type {integer}
  19473. */
  19474. PENDING_ATLAS: -1,
  19475. /**
  19476. * Various blend modes supported by Pixi.
  19477. *
  19478. * IMPORTANT: The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes.
  19479. *
  19480. * @constant
  19481. * @property {Number} blendModes.NORMAL
  19482. * @property {Number} blendModes.ADD
  19483. * @property {Number} blendModes.MULTIPLY
  19484. * @property {Number} blendModes.SCREEN
  19485. * @property {Number} blendModes.OVERLAY
  19486. * @property {Number} blendModes.DARKEN
  19487. * @property {Number} blendModes.LIGHTEN
  19488. * @property {Number} blendModes.COLOR_DODGE
  19489. * @property {Number} blendModes.COLOR_BURN
  19490. * @property {Number} blendModes.HARD_LIGHT
  19491. * @property {Number} blendModes.SOFT_LIGHT
  19492. * @property {Number} blendModes.DIFFERENCE
  19493. * @property {Number} blendModes.EXCLUSION
  19494. * @property {Number} blendModes.HUE
  19495. * @property {Number} blendModes.SATURATION
  19496. * @property {Number} blendModes.COLOR
  19497. * @property {Number} blendModes.LUMINOSITY
  19498. * @static
  19499. */
  19500. blendModes: {
  19501. NORMAL:0,
  19502. ADD:1,
  19503. MULTIPLY:2,
  19504. SCREEN:3,
  19505. OVERLAY:4,
  19506. DARKEN:5,
  19507. LIGHTEN:6,
  19508. COLOR_DODGE:7,
  19509. COLOR_BURN:8,
  19510. HARD_LIGHT:9,
  19511. SOFT_LIGHT:10,
  19512. DIFFERENCE:11,
  19513. EXCLUSION:12,
  19514. HUE:13,
  19515. SATURATION:14,
  19516. COLOR:15,
  19517. LUMINOSITY:16
  19518. },
  19519. /**
  19520. * The scale modes that are supported by Pixi.
  19521. *
  19522. * The DEFAULT scale mode affects the default scaling mode of future operations.
  19523. * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability.
  19524. *
  19525. * @constant
  19526. * @property {Object} Phaser.scaleModes
  19527. * @property {Number} scaleModes.DEFAULT=LINEAR
  19528. * @property {Number} scaleModes.LINEAR Smooth scaling
  19529. * @property {Number} scaleModes.NEAREST Pixelating scaling
  19530. * @static
  19531. */
  19532. scaleModes: {
  19533. DEFAULT:0,
  19534. LINEAR:0,
  19535. NEAREST:1
  19536. },
  19537. PIXI: PIXI || {}
  19538. };
  19539. /**
  19540. * @copyright 2016 Photon Storm Ltd.
  19541. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  19542. */
  19543. // ES6 Math.trunc - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc
  19544. if (!Math.trunc) {
  19545. Math.trunc = function trunc(x) {
  19546. return x < 0 ? Math.ceil(x) : Math.floor(x);
  19547. };
  19548. }
  19549. /**
  19550. * A polyfill for Function.prototype.bind
  19551. */
  19552. if (!Function.prototype.bind) {
  19553. /* jshint freeze: false */
  19554. Function.prototype.bind = (function () {
  19555. var slice = Array.prototype.slice;
  19556. return function (thisArg) {
  19557. var target = this, boundArgs = slice.call(arguments, 1);
  19558. if (typeof target !== 'function')
  19559. {
  19560. throw new TypeError();
  19561. }
  19562. function bound() {
  19563. var args = boundArgs.concat(slice.call(arguments));
  19564. target.apply(this instanceof bound ? this : thisArg, args);
  19565. }
  19566. bound.prototype = (function F(proto) {
  19567. if (proto)
  19568. {
  19569. F.prototype = proto;
  19570. }
  19571. if (!(this instanceof F))
  19572. {
  19573. /* jshint supernew: true */
  19574. return new F;
  19575. }
  19576. })(target.prototype);
  19577. return bound;
  19578. };
  19579. })();
  19580. }
  19581. /**
  19582. * A polyfill for Array.isArray
  19583. */
  19584. if (!Array.isArray)
  19585. {
  19586. Array.isArray = function (arg)
  19587. {
  19588. return Object.prototype.toString.call(arg) == '[object Array]';
  19589. };
  19590. }
  19591. /**
  19592. * A polyfill for Array.forEach
  19593. * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
  19594. */
  19595. if (!Array.prototype.forEach)
  19596. {
  19597. Array.prototype.forEach = function(fun /*, thisArg */)
  19598. {
  19599. "use strict";
  19600. if (this === void 0 || this === null)
  19601. {
  19602. throw new TypeError();
  19603. }
  19604. var t = Object(this);
  19605. var len = t.length >>> 0;
  19606. if (typeof fun !== "function")
  19607. {
  19608. throw new TypeError();
  19609. }
  19610. var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
  19611. for (var i = 0; i < len; i++)
  19612. {
  19613. if (i in t)
  19614. {
  19615. fun.call(thisArg, t[i], i, t);
  19616. }
  19617. }
  19618. };
  19619. }
  19620. /**
  19621. * Low-budget Float32Array knock-off, suitable for use with P2.js in IE9
  19622. * Source: http://www.html5gamedevs.com/topic/5988-phaser-12-ie9/
  19623. * Cameron Foale (http://www.kibibu.com)
  19624. */
  19625. if (typeof window.Uint32Array !== "function" && typeof window.Uint32Array !== "object")
  19626. {
  19627. var CheapArray = function(type)
  19628. {
  19629. var proto = new Array(); // jshint ignore:line
  19630. window[type] = function(arg) {
  19631. if (typeof(arg) === "number")
  19632. {
  19633. Array.call(this, arg);
  19634. this.length = arg;
  19635. for (var i = 0; i < this.length; i++)
  19636. {
  19637. this[i] = 0;
  19638. }
  19639. }
  19640. else
  19641. {
  19642. Array.call(this, arg.length);
  19643. this.length = arg.length;
  19644. for (var i = 0; i < this.length; i++)
  19645. {
  19646. this[i] = arg[i];
  19647. }
  19648. }
  19649. };
  19650. window[type].prototype = proto;
  19651. window[type].constructor = window[type];
  19652. };
  19653. CheapArray('Uint32Array'); // jshint ignore:line
  19654. CheapArray('Int16Array'); // jshint ignore:line
  19655. }
  19656. /**
  19657. * Also fix for the absent console in IE9
  19658. */
  19659. if (!window.console)
  19660. {
  19661. window.console = {};
  19662. window.console.log = window.console.assert = function(){};
  19663. window.console.warn = window.console.assert = function(){};
  19664. }
  19665. /**
  19666. * @author Richard Davey <rich@photonstorm.com>
  19667. * @copyright 2016 Photon Storm Ltd.
  19668. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  19669. */
  19670. /**
  19671. * @class Phaser.Utils
  19672. * @static
  19673. */
  19674. Phaser.Utils = {
  19675. /**
  19676. * Gets an objects property by string.
  19677. *
  19678. * @method Phaser.Utils.getProperty
  19679. * @param {object} obj - The object to traverse.
  19680. * @param {string} prop - The property whose value will be returned.
  19681. * @return {*} the value of the property or null if property isn't found .
  19682. */
  19683. getProperty: function(obj, prop) {
  19684. var parts = prop.split('.'),
  19685. last = parts.pop(),
  19686. l = parts.length,
  19687. i = 1,
  19688. current = parts[0];
  19689. while (i < l && (obj = obj[current]))
  19690. {
  19691. current = parts[i];
  19692. i++;
  19693. }
  19694. if (obj)
  19695. {
  19696. return obj[last];
  19697. }
  19698. else
  19699. {
  19700. return null;
  19701. }
  19702. },
  19703. /**
  19704. * Sets an objects property by string.
  19705. *
  19706. * @method Phaser.Utils.setProperty
  19707. * @param {object} obj - The object to traverse
  19708. * @param {string} prop - The property whose value will be changed
  19709. * @return {object} The object on which the property was set.
  19710. */
  19711. setProperty: function(obj, prop, value) {
  19712. var parts = prop.split('.'),
  19713. last = parts.pop(),
  19714. l = parts.length,
  19715. i = 1,
  19716. current = parts[0];
  19717. while (i < l && (obj = obj[current]))
  19718. {
  19719. current = parts[i];
  19720. i++;
  19721. }
  19722. if (obj)
  19723. {
  19724. obj[last] = value;
  19725. }
  19726. return obj;
  19727. },
  19728. /**
  19729. * Generate a random bool result based on the chance value.
  19730. *
  19731. * Returns true or false based on the chance value (default 50%). For example if you wanted a player to have a 30% chance
  19732. * of getting a bonus, call chanceRoll(30) - true means the chance passed, false means it failed.
  19733. *
  19734. * @method Phaser.Utils#chanceRoll
  19735. * @param {number} chance - The chance of receiving the value. A number between 0 and 100 (effectively 0% to 100%).
  19736. * @return {boolean} True if the roll passed, or false otherwise.
  19737. */
  19738. chanceRoll: function (chance) {
  19739. if (chance === undefined) { chance = 50; }
  19740. return chance > 0 && (Math.random() * 100 <= chance);
  19741. },
  19742. /**
  19743. * Choose between one of two values randomly.
  19744. *
  19745. * @method Phaser.Utils#randomChoice
  19746. * @param {any} choice1
  19747. * @param {any} choice2
  19748. * @return {any} The randomly selected choice
  19749. */
  19750. randomChoice: function (choice1, choice2) {
  19751. return (Math.random() < 0.5) ? choice1 : choice2;
  19752. },
  19753. /**
  19754. * Get a unit dimension from a string.
  19755. *
  19756. * @method Phaser.Utils.parseDimension
  19757. * @param {string|number} size - The size to parse.
  19758. * @param {number} dimension - The window dimension to check.
  19759. * @return {number} The parsed dimension.
  19760. */
  19761. parseDimension: function (size, dimension) {
  19762. var f = 0;
  19763. var px = 0;
  19764. if (typeof size === 'string')
  19765. {
  19766. // %?
  19767. if (size.substr(-1) === '%')
  19768. {
  19769. f = parseInt(size, 10) / 100;
  19770. if (dimension === 0)
  19771. {
  19772. px = window.innerWidth * f;
  19773. }
  19774. else
  19775. {
  19776. px = window.innerHeight * f;
  19777. }
  19778. }
  19779. else
  19780. {
  19781. px = parseInt(size, 10);
  19782. }
  19783. }
  19784. else
  19785. {
  19786. px = size;
  19787. }
  19788. return px;
  19789. },
  19790. /**
  19791. * JavaScript string pad http://www.webtoolkit.info/.
  19792. *
  19793. * @method Phaser.Utils.pad
  19794. * @param {string} str - The target string.
  19795. * @param {integer} [len=0] - The number of characters to be added.
  19796. * @param {string} [pad=" "] - The string to pad it out with (defaults to a space).
  19797. * @param {integer} [dir=3] The direction dir = 1 (left), 2 (right), 3 (both).
  19798. * @return {string} The padded string
  19799. */
  19800. pad: function (str, len, pad, dir) {
  19801. if (len === undefined) { var len = 0; }
  19802. if (pad === undefined) { var pad = ' '; }
  19803. if (dir === undefined) { var dir = 3; }
  19804. var padlen = 0;
  19805. if (len + 1 >= str.length)
  19806. {
  19807. switch (dir)
  19808. {
  19809. case 1:
  19810. str = new Array(len + 1 - str.length).join(pad) + str;
  19811. break;
  19812. case 3:
  19813. var right = Math.ceil((padlen = len - str.length) / 2);
  19814. var left = padlen - right;
  19815. str = new Array(left+1).join(pad) + str + new Array(right+1).join(pad);
  19816. break;
  19817. default:
  19818. str = str + new Array(len + 1 - str.length).join(pad);
  19819. break;
  19820. }
  19821. }
  19822. return str;
  19823. },
  19824. /**
  19825. * This is a slightly modified version of jQuery.isPlainObject.
  19826. * A plain object is an object whose internal class property is [object Object].
  19827. * @method Phaser.Utils.isPlainObject
  19828. * @param {object} obj - The object to inspect.
  19829. * @return {boolean} - true if the object is plain, otherwise false.
  19830. */
  19831. isPlainObject: function (obj) {
  19832. // Not plain objects:
  19833. // - Any object or value whose internal [[Class]] property is not "[object Object]"
  19834. // - DOM nodes
  19835. // - window
  19836. if (typeof(obj) !== "object" || obj.nodeType || obj === obj.window)
  19837. {
  19838. return false;
  19839. }
  19840. // Support: Firefox <20
  19841. // The try/catch suppresses exceptions thrown when attempting to access
  19842. // the "constructor" property of certain host objects, ie. |window.location|
  19843. // https://bugzilla.mozilla.org/show_bug.cgi?id=814622
  19844. try {
  19845. if (obj.constructor && !({}).hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf"))
  19846. {
  19847. return false;
  19848. }
  19849. } catch (e) {
  19850. return false;
  19851. }
  19852. // If the function hasn't returned already, we're confident that
  19853. // |obj| is a plain object, created by {} or constructed with new Object
  19854. return true;
  19855. },
  19856. /**
  19857. * This is a slightly modified version of http://api.jquery.com/jQuery.extend/
  19858. *
  19859. * @method Phaser.Utils.extend
  19860. * @param {boolean} deep - Perform a deep copy?
  19861. * @param {object} target - The target object to copy to.
  19862. * @return {object} The extended object.
  19863. */
  19864. extend: function () {
  19865. var options, name, src, copy, copyIsArray, clone,
  19866. target = arguments[0] || {},
  19867. i = 1,
  19868. length = arguments.length,
  19869. deep = false;
  19870. // Handle a deep copy situation
  19871. if (typeof target === "boolean")
  19872. {
  19873. deep = target;
  19874. target = arguments[1] || {};
  19875. // skip the boolean and the target
  19876. i = 2;
  19877. }
  19878. // extend Phaser if only one argument is passed
  19879. if (length === i)
  19880. {
  19881. target = this;
  19882. --i;
  19883. }
  19884. for (; i < length; i++)
  19885. {
  19886. // Only deal with non-null/undefined values
  19887. if ((options = arguments[i]) != null)
  19888. {
  19889. // Extend the base object
  19890. for (name in options)
  19891. {
  19892. src = target[name];
  19893. copy = options[name];
  19894. // Prevent never-ending loop
  19895. if (target === copy)
  19896. {
  19897. continue;
  19898. }
  19899. // Recurse if we're merging plain objects or arrays
  19900. if (deep && copy && (Phaser.Utils.isPlainObject(copy) || (copyIsArray = Array.isArray(copy))))
  19901. {
  19902. if (copyIsArray)
  19903. {
  19904. copyIsArray = false;
  19905. clone = src && Array.isArray(src) ? src : [];
  19906. }
  19907. else
  19908. {
  19909. clone = src && Phaser.Utils.isPlainObject(src) ? src : {};
  19910. }
  19911. // Never move original objects, clone them
  19912. target[name] = Phaser.Utils.extend(deep, clone, copy);
  19913. // Don't bring in undefined values
  19914. }
  19915. else if (copy !== undefined)
  19916. {
  19917. target[name] = copy;
  19918. }
  19919. }
  19920. }
  19921. }
  19922. // Return the modified object
  19923. return target;
  19924. },
  19925. /**
  19926. * Mixes in an existing mixin object with the target.
  19927. *
  19928. * Values in the mixin that have either `get` or `set` functions are created as properties via `defineProperty`
  19929. * _except_ if they also define a `clone` method - if a clone method is defined that is called instead and
  19930. * the result is assigned directly.
  19931. *
  19932. * @method Phaser.Utils.mixinPrototype
  19933. * @param {object} target - The target object to receive the new functions.
  19934. * @param {object} mixin - The object to copy the functions from.
  19935. * @param {boolean} [replace=false] - If the target object already has a matching function should it be overwritten or not?
  19936. */
  19937. mixinPrototype: function (target, mixin, replace) {
  19938. if (replace === undefined) { replace = false; }
  19939. var mixinKeys = Object.keys(mixin);
  19940. for (var i = 0; i < mixinKeys.length; i++)
  19941. {
  19942. var key = mixinKeys[i];
  19943. var value = mixin[key];
  19944. if (!replace && (key in target))
  19945. {
  19946. // Not overwriting existing property
  19947. continue;
  19948. }
  19949. else
  19950. {
  19951. if (value &&
  19952. (typeof value.get === 'function' || typeof value.set === 'function'))
  19953. {
  19954. // Special case for classes like Phaser.Point which has a 'set' function!
  19955. if (typeof value.clone === 'function')
  19956. {
  19957. target[key] = value.clone();
  19958. }
  19959. else
  19960. {
  19961. Object.defineProperty(target, key, value);
  19962. }
  19963. }
  19964. else
  19965. {
  19966. target[key] = value;
  19967. }
  19968. }
  19969. }
  19970. },
  19971. /**
  19972. * Mixes the source object into the destination object, returning the newly modified destination object.
  19973. * Based on original code by @mudcube
  19974. *
  19975. * @method Phaser.Utils.mixin
  19976. * @param {object} from - The object to copy (the source object).
  19977. * @param {object} to - The object to copy to (the destination object).
  19978. * @return {object} The modified destination object.
  19979. */
  19980. mixin: function (from, to) {
  19981. if (!from || typeof (from) !== "object")
  19982. {
  19983. return to;
  19984. }
  19985. for (var key in from)
  19986. {
  19987. var o = from[key];
  19988. if (o.childNodes || o.cloneNode)
  19989. {
  19990. continue;
  19991. }
  19992. var type = typeof (from[key]);
  19993. if (!from[key] || type !== "object")
  19994. {
  19995. to[key] = from[key];
  19996. }
  19997. else
  19998. {
  19999. // Clone sub-object
  20000. if (typeof (to[key]) === type)
  20001. {
  20002. to[key] = Phaser.Utils.mixin(from[key], to[key]);
  20003. }
  20004. else
  20005. {
  20006. to[key] = Phaser.Utils.mixin(from[key], new o.constructor());
  20007. }
  20008. }
  20009. }
  20010. return to;
  20011. }
  20012. };
  20013. /**
  20014. * @author Richard Davey <rich@photonstorm.com>
  20015. * @copyright 2016 Photon Storm Ltd.
  20016. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  20017. */
  20018. /**
  20019. * Creates a new Circle object with the center coordinate specified by the x and y parameters and the diameter specified by the diameter parameter.
  20020. * If you call this function without parameters, a circle with x, y, diameter and radius properties set to 0 is created.
  20021. *
  20022. * @class Phaser.Circle
  20023. * @constructor
  20024. * @param {number} [x=0] - The x coordinate of the center of the circle.
  20025. * @param {number} [y=0] - The y coordinate of the center of the circle.
  20026. * @param {number} [diameter=0] - The diameter of the circle.
  20027. */
  20028. Phaser.Circle = function (x, y, diameter) {
  20029. x = x || 0;
  20030. y = y || 0;
  20031. diameter = diameter || 0;
  20032. /**
  20033. * @property {number} x - The x coordinate of the center of the circle.
  20034. */
  20035. this.x = x;
  20036. /**
  20037. * @property {number} y - The y coordinate of the center of the circle.
  20038. */
  20039. this.y = y;
  20040. /**
  20041. * @property {number} _diameter - The diameter of the circle.
  20042. * @private
  20043. */
  20044. this._diameter = diameter;
  20045. /**
  20046. * @property {number} _radius - The radius of the circle.
  20047. * @private
  20048. */
  20049. this._radius = 0;
  20050. if (diameter > 0)
  20051. {
  20052. this._radius = diameter * 0.5;
  20053. }
  20054. /**
  20055. * @property {number} type - The const type of this object.
  20056. * @readonly
  20057. */
  20058. this.type = Phaser.CIRCLE;
  20059. };
  20060. Phaser.Circle.prototype = {
  20061. /**
  20062. * The circumference of the circle.
  20063. *
  20064. * @method Phaser.Circle#circumference
  20065. * @return {number} The circumference of the circle.
  20066. */
  20067. circumference: function () {
  20068. return 2 * (Math.PI * this._radius);
  20069. },
  20070. /**
  20071. * Returns a uniformly distributed random point from anywhere within this Circle.
  20072. *
  20073. * @method Phaser.Circle#random
  20074. * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in.
  20075. * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object.
  20076. * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties.
  20077. */
  20078. random: function (out) {
  20079. if (out === undefined) { out = new Phaser.Point(); }
  20080. var t = 2 * Math.PI * Math.random();
  20081. var u = Math.random() + Math.random();
  20082. var r = (u > 1) ? 2 - u : u;
  20083. var x = r * Math.cos(t);
  20084. var y = r * Math.sin(t);
  20085. out.x = this.x + (x * this.radius);
  20086. out.y = this.y + (y * this.radius);
  20087. return out;
  20088. },
  20089. /**
  20090. * Returns the framing rectangle of the circle as a Phaser.Rectangle object.
  20091. *
  20092. * @method Phaser.Circle#getBounds
  20093. * @return {Phaser.Rectangle} The bounds of the Circle.
  20094. */
  20095. getBounds: function () {
  20096. return new Phaser.Rectangle(this.x - this.radius, this.y - this.radius, this.diameter, this.diameter);
  20097. },
  20098. /**
  20099. * Sets the members of Circle to the specified values.
  20100. * @method Phaser.Circle#setTo
  20101. * @param {number} x - The x coordinate of the center of the circle.
  20102. * @param {number} y - The y coordinate of the center of the circle.
  20103. * @param {number} diameter - The diameter of the circle.
  20104. * @return {Circle} This circle object.
  20105. */
  20106. setTo: function (x, y, diameter) {
  20107. this.x = x;
  20108. this.y = y;
  20109. this._diameter = diameter;
  20110. this._radius = diameter * 0.5;
  20111. return this;
  20112. },
  20113. /**
  20114. * Copies the x, y and diameter properties from any given object to this Circle.
  20115. * @method Phaser.Circle#copyFrom
  20116. * @param {any} source - The object to copy from.
  20117. * @return {Circle} This Circle object.
  20118. */
  20119. copyFrom: function (source) {
  20120. return this.setTo(source.x, source.y, source.diameter);
  20121. },
  20122. /**
  20123. * Copies the x, y and diameter properties from this Circle to any given object.
  20124. * @method Phaser.Circle#copyTo
  20125. * @param {any} dest - The object to copy to.
  20126. * @return {object} This dest object.
  20127. */
  20128. copyTo: function (dest) {
  20129. dest.x = this.x;
  20130. dest.y = this.y;
  20131. dest.diameter = this._diameter;
  20132. return dest;
  20133. },
  20134. /**
  20135. * Returns the distance from the center of the Circle object to the given object
  20136. * (can be Circle, Point or anything with x/y properties)
  20137. * @method Phaser.Circle#distance
  20138. * @param {object} dest - The target object. Must have visible x and y properties that represent the center of the object.
  20139. * @param {boolean} [round=false] - Round the distance to the nearest integer.
  20140. * @return {number} The distance between this Point object and the destination Point object.
  20141. */
  20142. distance: function (dest, round) {
  20143. var distance = Phaser.Math.distance(this.x, this.y, dest.x, dest.y);
  20144. return round ? Math.round(distance) : distance;
  20145. },
  20146. /**
  20147. * Returns a new Circle object with the same values for the x, y, width, and height properties as this Circle object.
  20148. * @method Phaser.Circle#clone
  20149. * @param {Phaser.Circle} output - Optional Circle object. If given the values will be set into the object, otherwise a brand new Circle object will be created and returned.
  20150. * @return {Phaser.Circle} The cloned Circle object.
  20151. */
  20152. clone: function (output) {
  20153. if (output === undefined || output === null)
  20154. {
  20155. output = new Phaser.Circle(this.x, this.y, this.diameter);
  20156. }
  20157. else
  20158. {
  20159. output.setTo(this.x, this.y, this.diameter);
  20160. }
  20161. return output;
  20162. },
  20163. /**
  20164. * Return true if the given x/y coordinates are within this Circle object.
  20165. * @method Phaser.Circle#contains
  20166. * @param {number} x - The X value of the coordinate to test.
  20167. * @param {number} y - The Y value of the coordinate to test.
  20168. * @return {boolean} True if the coordinates are within this circle, otherwise false.
  20169. */
  20170. contains: function (x, y) {
  20171. return Phaser.Circle.contains(this, x, y);
  20172. },
  20173. /**
  20174. * Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle.
  20175. * @method Phaser.Circle#circumferencePoint
  20176. * @param {number} angle - The angle in radians (unless asDegrees is true) to return the point from.
  20177. * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)?
  20178. * @param {Phaser.Point} [out] - An optional Point object to put the result in to. If none specified a new Point object will be created.
  20179. * @return {Phaser.Point} The Point object holding the result.
  20180. */
  20181. circumferencePoint: function (angle, asDegrees, out) {
  20182. return Phaser.Circle.circumferencePoint(this, angle, asDegrees, out);
  20183. },
  20184. /**
  20185. * Adjusts the location of the Circle object, as determined by its center coordinate, by the specified amounts.
  20186. * @method Phaser.Circle#offset
  20187. * @param {number} dx - Moves the x value of the Circle object by this amount.
  20188. * @param {number} dy - Moves the y value of the Circle object by this amount.
  20189. * @return {Circle} This Circle object.
  20190. */
  20191. offset: function (dx, dy) {
  20192. this.x += dx;
  20193. this.y += dy;
  20194. return this;
  20195. },
  20196. /**
  20197. * 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.
  20198. * @method Phaser.Circle#offsetPoint
  20199. * @param {Point} point A Point object to use to offset this Circle object (or any valid object with exposed x and y properties).
  20200. * @return {Circle} This Circle object.
  20201. */
  20202. offsetPoint: function (point) {
  20203. return this.offset(point.x, point.y);
  20204. },
  20205. /**
  20206. * Returns a string representation of this object.
  20207. * @method Phaser.Circle#toString
  20208. * @return {string} a string representation of the instance.
  20209. */
  20210. toString: function () {
  20211. return "[{Phaser.Circle (x=" + this.x + " y=" + this.y + " diameter=" + this.diameter + " radius=" + this.radius + ")}]";
  20212. }
  20213. };
  20214. Phaser.Circle.prototype.constructor = Phaser.Circle;
  20215. /**
  20216. * The largest distance between any two points on the circle. The same as the radius * 2.
  20217. *
  20218. * @name Phaser.Circle#diameter
  20219. * @property {number} diameter - Gets or sets the diameter of the circle.
  20220. */
  20221. Object.defineProperty(Phaser.Circle.prototype, "diameter", {
  20222. get: function () {
  20223. return this._diameter;
  20224. },
  20225. set: function (value) {
  20226. if (value > 0)
  20227. {
  20228. this._diameter = value;
  20229. this._radius = value * 0.5;
  20230. }
  20231. }
  20232. });
  20233. /**
  20234. * 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.
  20235. * @name Phaser.Circle#radius
  20236. * @property {number} radius - Gets or sets the radius of the circle.
  20237. */
  20238. Object.defineProperty(Phaser.Circle.prototype, "radius", {
  20239. get: function () {
  20240. return this._radius;
  20241. },
  20242. set: function (value) {
  20243. if (value > 0)
  20244. {
  20245. this._radius = value;
  20246. this._diameter = value * 2;
  20247. }
  20248. }
  20249. });
  20250. /**
  20251. * 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.
  20252. * @name Phaser.Circle#left
  20253. * @propety {number} left - Gets or sets the value of the leftmost point of the circle.
  20254. */
  20255. Object.defineProperty(Phaser.Circle.prototype, "left", {
  20256. get: function () {
  20257. return this.x - this._radius;
  20258. },
  20259. set: function (value) {
  20260. if (value > this.x)
  20261. {
  20262. this._radius = 0;
  20263. this._diameter = 0;
  20264. }
  20265. else
  20266. {
  20267. this.radius = this.x - value;
  20268. }
  20269. }
  20270. });
  20271. /**
  20272. * 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.
  20273. * @name Phaser.Circle#right
  20274. * @property {number} right - Gets or sets the value of the rightmost point of the circle.
  20275. */
  20276. Object.defineProperty(Phaser.Circle.prototype, "right", {
  20277. get: function () {
  20278. return this.x + this._radius;
  20279. },
  20280. set: function (value) {
  20281. if (value < this.x)
  20282. {
  20283. this._radius = 0;
  20284. this._diameter = 0;
  20285. }
  20286. else
  20287. {
  20288. this.radius = value - this.x;
  20289. }
  20290. }
  20291. });
  20292. /**
  20293. * 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.
  20294. * @name Phaser.Circle#top
  20295. * @property {number} top - Gets or sets the top of the circle.
  20296. */
  20297. Object.defineProperty(Phaser.Circle.prototype, "top", {
  20298. get: function () {
  20299. return this.y - this._radius;
  20300. },
  20301. set: function (value) {
  20302. if (value > this.y)
  20303. {
  20304. this._radius = 0;
  20305. this._diameter = 0;
  20306. }
  20307. else
  20308. {
  20309. this.radius = this.y - value;
  20310. }
  20311. }
  20312. });
  20313. /**
  20314. * 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.
  20315. * @name Phaser.Circle#bottom
  20316. * @property {number} bottom - Gets or sets the bottom of the circle.
  20317. */
  20318. Object.defineProperty(Phaser.Circle.prototype, "bottom", {
  20319. get: function () {
  20320. return this.y + this._radius;
  20321. },
  20322. set: function (value) {
  20323. if (value < this.y)
  20324. {
  20325. this._radius = 0;
  20326. this._diameter = 0;
  20327. }
  20328. else
  20329. {
  20330. this.radius = value - this.y;
  20331. }
  20332. }
  20333. });
  20334. /**
  20335. * The area of this Circle.
  20336. * @name Phaser.Circle#area
  20337. * @property {number} area - The area of this circle.
  20338. * @readonly
  20339. */
  20340. Object.defineProperty(Phaser.Circle.prototype, "area", {
  20341. get: function () {
  20342. if (this._radius > 0)
  20343. {
  20344. return Math.PI * this._radius * this._radius;
  20345. }
  20346. else
  20347. {
  20348. return 0;
  20349. }
  20350. }
  20351. });
  20352. /**
  20353. * 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.
  20354. * 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.
  20355. * @name Phaser.Circle#empty
  20356. * @property {boolean} empty - Gets or sets the empty state of the circle.
  20357. */
  20358. Object.defineProperty(Phaser.Circle.prototype, "empty", {
  20359. get: function () {
  20360. return (this._diameter === 0);
  20361. },
  20362. set: function (value) {
  20363. if (value === true)
  20364. {
  20365. this.setTo(0, 0, 0);
  20366. }
  20367. }
  20368. });
  20369. /**
  20370. * Return true if the given x/y coordinates are within the Circle object.
  20371. * @method Phaser.Circle.contains
  20372. * @param {Phaser.Circle} a - The Circle to be checked.
  20373. * @param {number} x - The X value of the coordinate to test.
  20374. * @param {number} y - The Y value of the coordinate to test.
  20375. * @return {boolean} True if the coordinates are within this circle, otherwise false.
  20376. */
  20377. Phaser.Circle.contains = function (a, x, y) {
  20378. // Check if x/y are within the bounds first
  20379. if (a.radius > 0 && x >= a.left && x <= a.right && y >= a.top && y <= a.bottom)
  20380. {
  20381. var dx = (a.x - x) * (a.x - x);
  20382. var dy = (a.y - y) * (a.y - y);
  20383. return (dx + dy) <= (a.radius * a.radius);
  20384. }
  20385. else
  20386. {
  20387. return false;
  20388. }
  20389. };
  20390. /**
  20391. * Determines whether the two Circle objects match. This method compares the x, y and diameter properties.
  20392. * @method Phaser.Circle.equals
  20393. * @param {Phaser.Circle} a - The first Circle object.
  20394. * @param {Phaser.Circle} b - The second Circle object.
  20395. * @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.
  20396. */
  20397. Phaser.Circle.equals = function (a, b) {
  20398. return (a.x == b.x && a.y == b.y && a.diameter == b.diameter);
  20399. };
  20400. /**
  20401. * Determines whether the two Circle objects intersect.
  20402. * This method checks the radius distances between the two Circle objects to see if they intersect.
  20403. * @method Phaser.Circle.intersects
  20404. * @param {Phaser.Circle} a - The first Circle object.
  20405. * @param {Phaser.Circle} b - The second Circle object.
  20406. * @return {boolean} A value of true if the specified object intersects with this Circle object; otherwise false.
  20407. */
  20408. Phaser.Circle.intersects = function (a, b) {
  20409. return (Phaser.Math.distance(a.x, a.y, b.x, b.y) <= (a.radius + b.radius));
  20410. };
  20411. /**
  20412. * Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle.
  20413. * @method Phaser.Circle.circumferencePoint
  20414. * @param {Phaser.Circle} a - The first Circle object.
  20415. * @param {number} angle - The angle in radians (unless asDegrees is true) to return the point from.
  20416. * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)?
  20417. * @param {Phaser.Point} [out] - An optional Point object to put the result in to. If none specified a new Point object will be created.
  20418. * @return {Phaser.Point} The Point object holding the result.
  20419. */
  20420. Phaser.Circle.circumferencePoint = function (a, angle, asDegrees, out) {
  20421. if (asDegrees === undefined) { asDegrees = false; }
  20422. if (out === undefined) { out = new Phaser.Point(); }
  20423. if (asDegrees === true)
  20424. {
  20425. angle = Phaser.Math.degToRad(angle);
  20426. }
  20427. out.x = a.x + a.radius * Math.cos(angle);
  20428. out.y = a.y + a.radius * Math.sin(angle);
  20429. return out;
  20430. };
  20431. /**
  20432. * Checks if the given Circle and Rectangle objects intersect.
  20433. * @method Phaser.Circle.intersectsRectangle
  20434. * @param {Phaser.Circle} c - The Circle object to test.
  20435. * @param {Phaser.Rectangle} r - The Rectangle object to test.
  20436. * @return {boolean} True if the two objects intersect, otherwise false.
  20437. */
  20438. Phaser.Circle.intersectsRectangle = function (c, r) {
  20439. var cx = Math.abs(c.x - r.x - r.halfWidth);
  20440. var xDist = r.halfWidth + c.radius;
  20441. if (cx > xDist)
  20442. {
  20443. return false;
  20444. }
  20445. var cy = Math.abs(c.y - r.y - r.halfHeight);
  20446. var yDist = r.halfHeight + c.radius;
  20447. if (cy > yDist)
  20448. {
  20449. return false;
  20450. }
  20451. if (cx <= r.halfWidth || cy <= r.halfHeight)
  20452. {
  20453. return true;
  20454. }
  20455. var xCornerDist = cx - r.halfWidth;
  20456. var yCornerDist = cy - r.halfHeight;
  20457. var xCornerDistSq = xCornerDist * xCornerDist;
  20458. var yCornerDistSq = yCornerDist * yCornerDist;
  20459. var maxCornerDistSq = c.radius * c.radius;
  20460. return xCornerDistSq + yCornerDistSq <= maxCornerDistSq;
  20461. };
  20462. // Because PIXI uses its own Circle, we'll replace it with ours to avoid duplicating code or confusion.
  20463. PIXI.Circle = Phaser.Circle;
  20464. /**
  20465. * @author Richard Davey <rich@photonstorm.com>
  20466. * @author Chad Engler <chad@pantherdev.com>
  20467. * @copyright 2016 Photon Storm Ltd.
  20468. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  20469. */
  20470. /**
  20471. * Creates a Ellipse object. A curve on a plane surrounding two focal points.
  20472. *
  20473. * @class Phaser.Ellipse
  20474. * @constructor
  20475. * @param {number} [x=0] - The X coordinate of the upper-left corner of the framing rectangle of this ellipse.
  20476. * @param {number} [y=0] - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse.
  20477. * @param {number} [width=0] - The overall width of this ellipse.
  20478. * @param {number} [height=0] - The overall height of this ellipse.
  20479. */
  20480. Phaser.Ellipse = function (x, y, width, height) {
  20481. x = x || 0;
  20482. y = y || 0;
  20483. width = width || 0;
  20484. height = height || 0;
  20485. /**
  20486. * @property {number} x - The X coordinate of the upper-left corner of the framing rectangle of this ellipse.
  20487. */
  20488. this.x = x;
  20489. /**
  20490. * @property {number} y - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse.
  20491. */
  20492. this.y = y;
  20493. /**
  20494. * @property {number} width - The overall width of this ellipse.
  20495. */
  20496. this.width = width;
  20497. /**
  20498. * @property {number} height - The overall height of this ellipse.
  20499. */
  20500. this.height = height;
  20501. /**
  20502. * @property {number} type - The const type of this object.
  20503. * @readonly
  20504. */
  20505. this.type = Phaser.ELLIPSE;
  20506. };
  20507. Phaser.Ellipse.prototype = {
  20508. /**
  20509. * Sets the members of the Ellipse to the specified values.
  20510. * @method Phaser.Ellipse#setTo
  20511. * @param {number} x - The X coordinate of the upper-left corner of the framing rectangle of this ellipse.
  20512. * @param {number} y - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse.
  20513. * @param {number} width - The overall width of this ellipse.
  20514. * @param {number} height - The overall height of this ellipse.
  20515. * @return {Phaser.Ellipse} This Ellipse object.
  20516. */
  20517. setTo: function (x, y, width, height) {
  20518. this.x = x;
  20519. this.y = y;
  20520. this.width = width;
  20521. this.height = height;
  20522. return this;
  20523. },
  20524. /**
  20525. * Returns the framing rectangle of the ellipse as a Phaser.Rectangle object.
  20526. *
  20527. * @method Phaser.Ellipse#getBounds
  20528. * @return {Phaser.Rectangle} The bounds of the Ellipse.
  20529. */
  20530. getBounds: function () {
  20531. return new Phaser.Rectangle(this.x - this.width, this.y - this.height, this.width, this.height);
  20532. },
  20533. /**
  20534. * Copies the x, y, width and height properties from any given object to this Ellipse.
  20535. *
  20536. * @method Phaser.Ellipse#copyFrom
  20537. * @param {any} source - The object to copy from.
  20538. * @return {Phaser.Ellipse} This Ellipse object.
  20539. */
  20540. copyFrom: function (source) {
  20541. return this.setTo(source.x, source.y, source.width, source.height);
  20542. },
  20543. /**
  20544. * Copies the x, y, width and height properties from this Ellipse to any given object.
  20545. * @method Phaser.Ellipse#copyTo
  20546. * @param {any} dest - The object to copy to.
  20547. * @return {object} This dest object.
  20548. */
  20549. copyTo: function(dest) {
  20550. dest.x = this.x;
  20551. dest.y = this.y;
  20552. dest.width = this.width;
  20553. dest.height = this.height;
  20554. return dest;
  20555. },
  20556. /**
  20557. * Returns a new Ellipse object with the same values for the x, y, width, and height properties as this Ellipse object.
  20558. * @method Phaser.Ellipse#clone
  20559. * @param {Phaser.Ellipse} output - Optional Ellipse object. If given the values will be set into the object, otherwise a brand new Ellipse object will be created and returned.
  20560. * @return {Phaser.Ellipse} The cloned Ellipse object.
  20561. */
  20562. clone: function(output) {
  20563. if (output === undefined || output === null)
  20564. {
  20565. output = new Phaser.Ellipse(this.x, this.y, this.width, this.height);
  20566. }
  20567. else
  20568. {
  20569. output.setTo(this.x, this.y, this.width, this.height);
  20570. }
  20571. return output;
  20572. },
  20573. /**
  20574. * Return true if the given x/y coordinates are within this Ellipse object.
  20575. *
  20576. * @method Phaser.Ellipse#contains
  20577. * @param {number} x - The X value of the coordinate to test.
  20578. * @param {number} y - The Y value of the coordinate to test.
  20579. * @return {boolean} True if the coordinates are within this ellipse, otherwise false.
  20580. */
  20581. contains: function (x, y) {
  20582. return Phaser.Ellipse.contains(this, x, y);
  20583. },
  20584. /**
  20585. * Returns a uniformly distributed random point from anywhere within this Ellipse.
  20586. *
  20587. * @method Phaser.Ellipse#random
  20588. * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in.
  20589. * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object.
  20590. * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties.
  20591. */
  20592. random: function (out) {
  20593. if (out === undefined) { out = new Phaser.Point(); }
  20594. var p = Math.random() * Math.PI * 2;
  20595. var r = Math.random();
  20596. out.x = Math.sqrt(r) * Math.cos(p);
  20597. out.y = Math.sqrt(r) * Math.sin(p);
  20598. out.x = this.x + (out.x * this.width / 2.0);
  20599. out.y = this.y + (out.y * this.height / 2.0);
  20600. return out;
  20601. },
  20602. /**
  20603. * Returns a string representation of this object.
  20604. * @method Phaser.Ellipse#toString
  20605. * @return {string} A string representation of the instance.
  20606. */
  20607. toString: function () {
  20608. return "[{Phaser.Ellipse (x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + ")}]";
  20609. }
  20610. };
  20611. Phaser.Ellipse.prototype.constructor = Phaser.Ellipse;
  20612. /**
  20613. * The left coordinate of the Ellipse. The same as the X coordinate.
  20614. * @name Phaser.Ellipse#left
  20615. * @propety {number} left - Gets or sets the value of the leftmost point of the ellipse.
  20616. */
  20617. Object.defineProperty(Phaser.Ellipse.prototype, "left", {
  20618. get: function () {
  20619. return this.x;
  20620. },
  20621. set: function (value) {
  20622. this.x = value;
  20623. }
  20624. });
  20625. /**
  20626. * The x coordinate of the rightmost point of the Ellipse. Changing the right property of an Ellipse object has no effect on the x property, but does adjust the width.
  20627. * @name Phaser.Ellipse#right
  20628. * @property {number} right - Gets or sets the value of the rightmost point of the ellipse.
  20629. */
  20630. Object.defineProperty(Phaser.Ellipse.prototype, "right", {
  20631. get: function () {
  20632. return this.x + this.width;
  20633. },
  20634. set: function (value) {
  20635. if (value < this.x)
  20636. {
  20637. this.width = 0;
  20638. }
  20639. else
  20640. {
  20641. this.width = value - this.x;
  20642. }
  20643. }
  20644. });
  20645. /**
  20646. * The top of the Ellipse. The same as its y property.
  20647. * @name Phaser.Ellipse#top
  20648. * @property {number} top - Gets or sets the top of the ellipse.
  20649. */
  20650. Object.defineProperty(Phaser.Ellipse.prototype, "top", {
  20651. get: function () {
  20652. return this.y;
  20653. },
  20654. set: function (value) {
  20655. this.y = value;
  20656. }
  20657. });
  20658. /**
  20659. * The sum of the y and height properties. Changing the bottom property of an Ellipse doesn't adjust the y property, but does change the height.
  20660. * @name Phaser.Ellipse#bottom
  20661. * @property {number} bottom - Gets or sets the bottom of the ellipse.
  20662. */
  20663. Object.defineProperty(Phaser.Ellipse.prototype, "bottom", {
  20664. get: function () {
  20665. return this.y + this.height;
  20666. },
  20667. set: function (value) {
  20668. if (value < this.y)
  20669. {
  20670. this.height = 0;
  20671. }
  20672. else
  20673. {
  20674. this.height = value - this.y;
  20675. }
  20676. }
  20677. });
  20678. /**
  20679. * Determines whether or not this Ellipse object is empty. Will return a value of true if the Ellipse objects dimensions are less than or equal to 0; otherwise false.
  20680. * If set to true it will reset all of the Ellipse objects properties to 0. An Ellipse object is empty if its width or height is less than or equal to 0.
  20681. * @name Phaser.Ellipse#empty
  20682. * @property {boolean} empty - Gets or sets the empty state of the ellipse.
  20683. */
  20684. Object.defineProperty(Phaser.Ellipse.prototype, "empty", {
  20685. get: function () {
  20686. return (this.width === 0 || this.height === 0);
  20687. },
  20688. set: function (value) {
  20689. if (value === true)
  20690. {
  20691. this.setTo(0, 0, 0, 0);
  20692. }
  20693. }
  20694. });
  20695. /**
  20696. * Return true if the given x/y coordinates are within the Ellipse object.
  20697. *
  20698. * @method Phaser.Ellipse.contains
  20699. * @param {Phaser.Ellipse} a - The Ellipse to be checked.
  20700. * @param {number} x - The X value of the coordinate to test.
  20701. * @param {number} y - The Y value of the coordinate to test.
  20702. * @return {boolean} True if the coordinates are within this ellipse, otherwise false.
  20703. */
  20704. Phaser.Ellipse.contains = function (a, x, y) {
  20705. if (a.width <= 0 || a.height <= 0) {
  20706. return false;
  20707. }
  20708. // Normalize the coords to an ellipse with center 0,0 and a radius of 0.5
  20709. var normx = ((x - a.x) / a.width) - 0.5;
  20710. var normy = ((y - a.y) / a.height) - 0.5;
  20711. normx *= normx;
  20712. normy *= normy;
  20713. return (normx + normy < 0.25);
  20714. };
  20715. // Because PIXI uses its own Ellipse, we'll replace it with ours to avoid duplicating code or confusion.
  20716. PIXI.Ellipse = Phaser.Ellipse;
  20717. /**
  20718. * @author Richard Davey <rich@photonstorm.com>
  20719. * @copyright 2016 Photon Storm Ltd.
  20720. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  20721. */
  20722. /**
  20723. * Creates a new Line object with a start and an end point.
  20724. *
  20725. * @class Phaser.Line
  20726. * @constructor
  20727. * @param {number} [x1=0] - The x coordinate of the start of the line.
  20728. * @param {number} [y1=0] - The y coordinate of the start of the line.
  20729. * @param {number} [x2=0] - The x coordinate of the end of the line.
  20730. * @param {number} [y2=0] - The y coordinate of the end of the line.
  20731. */
  20732. Phaser.Line = function (x1, y1, x2, y2) {
  20733. x1 = x1 || 0;
  20734. y1 = y1 || 0;
  20735. x2 = x2 || 0;
  20736. y2 = y2 || 0;
  20737. /**
  20738. * @property {Phaser.Point} start - The start point of the line.
  20739. */
  20740. this.start = new Phaser.Point(x1, y1);
  20741. /**
  20742. * @property {Phaser.Point} end - The end point of the line.
  20743. */
  20744. this.end = new Phaser.Point(x2, y2);
  20745. /**
  20746. * @property {number} type - The const type of this object.
  20747. * @readonly
  20748. */
  20749. this.type = Phaser.LINE;
  20750. };
  20751. Phaser.Line.prototype = {
  20752. /**
  20753. * Sets the components of the Line to the specified values.
  20754. *
  20755. * @method Phaser.Line#setTo
  20756. * @param {number} [x1=0] - The x coordinate of the start of the line.
  20757. * @param {number} [y1=0] - The y coordinate of the start of the line.
  20758. * @param {number} [x2=0] - The x coordinate of the end of the line.
  20759. * @param {number} [y2=0] - The y coordinate of the end of the line.
  20760. * @return {Phaser.Line} This line object
  20761. */
  20762. setTo: function (x1, y1, x2, y2) {
  20763. this.start.setTo(x1, y1);
  20764. this.end.setTo(x2, y2);
  20765. return this;
  20766. },
  20767. /**
  20768. * Sets the line to match the x/y coordinates of the two given sprites.
  20769. * Can optionally be calculated from their center coordinates.
  20770. *
  20771. * @method Phaser.Line#fromSprite
  20772. * @param {Phaser.Sprite} startSprite - The coordinates of this Sprite will be set to the Line.start point.
  20773. * @param {Phaser.Sprite} endSprite - The coordinates of this Sprite will be set to the Line.start point.
  20774. * @param {boolean} [useCenter=false] - If true it will use startSprite.center.x, if false startSprite.x. Note that Sprites don't have a center property by default, so only enable if you've over-ridden your Sprite with a custom class.
  20775. * @return {Phaser.Line} This line object
  20776. */
  20777. fromSprite: function (startSprite, endSprite, useCenter) {
  20778. if (useCenter === undefined) { useCenter = false; }
  20779. if (useCenter)
  20780. {
  20781. return this.setTo(startSprite.center.x, startSprite.center.y, endSprite.center.x, endSprite.center.y);
  20782. }
  20783. return this.setTo(startSprite.x, startSprite.y, endSprite.x, endSprite.y);
  20784. },
  20785. /**
  20786. * Sets this line to start at the given `x` and `y` coordinates and for the segment to extend at `angle` for the given `length`.
  20787. *
  20788. * @method Phaser.Line#fromAngle
  20789. * @param {number} x - The x coordinate of the start of the line.
  20790. * @param {number} y - The y coordinate of the start of the line.
  20791. * @param {number} angle - The angle of the line in radians.
  20792. * @param {number} length - The length of the line in pixels.
  20793. * @return {Phaser.Line} This line object
  20794. */
  20795. fromAngle: function (x, y, angle, length) {
  20796. this.start.setTo(x, y);
  20797. this.end.setTo(x + (Math.cos(angle) * length), y + (Math.sin(angle) * length));
  20798. return this;
  20799. },
  20800. /**
  20801. * Rotates the line by the amount specified in `angle`.
  20802. *
  20803. * Rotation takes place from the center of the line.
  20804. * If you wish to rotate around a different point see Line.rotateAround.
  20805. *
  20806. * If you wish to rotate the ends of the Line then see Line.start.rotate or Line.end.rotate.
  20807. *
  20808. * @method Phaser.Line#rotate
  20809. * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the line by.
  20810. * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)?
  20811. * @return {Phaser.Line} This line object
  20812. */
  20813. rotate: function (angle, asDegrees) {
  20814. var cx = (this.start.x + this.end.x) / 2;
  20815. var cy = (this.start.y + this.end.y) / 2;
  20816. this.start.rotate(cx, cy, angle, asDegrees);
  20817. this.end.rotate(cx, cy, angle, asDegrees);
  20818. return this;
  20819. },
  20820. /**
  20821. * Rotates the line by the amount specified in `angle`.
  20822. *
  20823. * Rotation takes place around the coordinates given.
  20824. *
  20825. * @method Phaser.Line#rotateAround
  20826. * @param {number} x - The x coordinate to offset the rotation from.
  20827. * @param {number} y - The y coordinate to offset the rotation from.
  20828. * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the line by.
  20829. * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)?
  20830. * @return {Phaser.Line} This line object
  20831. */
  20832. rotateAround: function (x, y, angle, asDegrees) {
  20833. this.start.rotate(x, y, angle, asDegrees);
  20834. this.end.rotate(x, y, angle, asDegrees);
  20835. return this;
  20836. },
  20837. /**
  20838. * Checks for intersection between this line and another Line.
  20839. * If asSegment is true it will check for segment intersection. If asSegment is false it will check for line intersection.
  20840. * Returns the intersection segment of AB and EF as a Point, or null if there is no intersection.
  20841. *
  20842. * @method Phaser.Line#intersects
  20843. * @param {Phaser.Line} line - The line to check against this one.
  20844. * @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection.
  20845. * @param {Phaser.Point} [result] - A Point object to store the result in, if not given a new one will be created.
  20846. * @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection.
  20847. */
  20848. intersects: function (line, asSegment, result) {
  20849. return Phaser.Line.intersectsPoints(this.start, this.end, line.start, line.end, asSegment, result);
  20850. },
  20851. /**
  20852. * Returns the reflected angle between two lines.
  20853. * This is the outgoing angle based on the angle of this line and the normalAngle of the given line.
  20854. *
  20855. * @method Phaser.Line#reflect
  20856. * @param {Phaser.Line} line - The line to reflect off this line.
  20857. * @return {number} The reflected angle in radians.
  20858. */
  20859. reflect: function (line) {
  20860. return Phaser.Line.reflect(this, line);
  20861. },
  20862. /**
  20863. * Returns a Point object where the x and y values correspond to the center (or midpoint) of the Line segment.
  20864. *
  20865. * @method Phaser.Line#midPoint
  20866. * @param {Phaser.Point} [out] - A Phaser.Point object into which the result will be populated. If not given a new Point object is created.
  20867. * @return {Phaser.Point} A Phaser.Point object with the x and y values set to the center of the line segment.
  20868. */
  20869. midPoint: function (out) {
  20870. if (out === undefined) { out = new Phaser.Point(); }
  20871. out.x = (this.start.x + this.end.x) / 2;
  20872. out.y = (this.start.y + this.end.y) / 2;
  20873. return out;
  20874. },
  20875. /**
  20876. * Centers this Line on the given coordinates.
  20877. *
  20878. * The line is centered by positioning the start and end points so that the lines midpoint matches
  20879. * the coordinates given.
  20880. *
  20881. * @method Phaser.Line#centerOn
  20882. * @param {number} x - The x position to center the line on.
  20883. * @param {number} y - The y position to center the line on.
  20884. * @return {Phaser.Line} This line object
  20885. */
  20886. centerOn: function (x, y) {
  20887. var cx = (this.start.x + this.end.x) / 2;
  20888. var cy = (this.start.y + this.end.y) / 2;
  20889. var tx = x - cx;
  20890. var ty = y - cy;
  20891. this.start.add(tx, ty);
  20892. this.end.add(tx, ty);
  20893. },
  20894. /**
  20895. * Tests if the given coordinates fall on this line. See pointOnSegment to test against just the line segment.
  20896. *
  20897. * @method Phaser.Line#pointOnLine
  20898. * @param {number} x - The line to check against this one.
  20899. * @param {number} y - The line to check against this one.
  20900. * @return {boolean} True if the point is on the line, false if not.
  20901. */
  20902. pointOnLine: function (x, y) {
  20903. return ((x - this.start.x) * (this.end.y - this.start.y) === (this.end.x - this.start.x) * (y - this.start.y));
  20904. },
  20905. /**
  20906. * Tests if the given coordinates fall on this line and within the segment. See pointOnLine to test against just the line.
  20907. *
  20908. * @method Phaser.Line#pointOnSegment
  20909. * @param {number} x - The line to check against this one.
  20910. * @param {number} y - The line to check against this one.
  20911. * @return {boolean} True if the point is on the line and segment, false if not.
  20912. */
  20913. pointOnSegment: function (x, y) {
  20914. var xMin = Math.min(this.start.x, this.end.x);
  20915. var xMax = Math.max(this.start.x, this.end.x);
  20916. var yMin = Math.min(this.start.y, this.end.y);
  20917. var yMax = Math.max(this.start.y, this.end.y);
  20918. return (this.pointOnLine(x, y) && (x >= xMin && x <= xMax) && (y >= yMin && y <= yMax));
  20919. },
  20920. /**
  20921. * Picks a random point from anywhere on the Line segment and returns it.
  20922. *
  20923. * @method Phaser.Line#random
  20924. * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in.
  20925. * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an object.
  20926. * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties.
  20927. */
  20928. random: function (out) {
  20929. if (out === undefined) { out = new Phaser.Point(); }
  20930. var t = Math.random();
  20931. out.x = this.start.x + t * (this.end.x - this.start.x);
  20932. out.y = this.start.y + t * (this.end.y - this.start.y);
  20933. return out;
  20934. },
  20935. /**
  20936. * Using Bresenham's line algorithm this will return an array of all coordinates on this line.
  20937. * The start and end points are rounded before this runs as the algorithm works on integers.
  20938. *
  20939. * @method Phaser.Line#coordinatesOnLine
  20940. * @param {number} [stepRate=1] - How many steps will we return? 1 = every coordinate on the line, 2 = every other coordinate, etc.
  20941. * @param {array} [results] - The array to store the results in. If not provided a new one will be generated.
  20942. * @return {array} An array of coordinates.
  20943. */
  20944. coordinatesOnLine: function (stepRate, results) {
  20945. if (stepRate === undefined) { stepRate = 1; }
  20946. if (results === undefined) { results = []; }
  20947. var x1 = Math.round(this.start.x);
  20948. var y1 = Math.round(this.start.y);
  20949. var x2 = Math.round(this.end.x);
  20950. var y2 = Math.round(this.end.y);
  20951. var dx = Math.abs(x2 - x1);
  20952. var dy = Math.abs(y2 - y1);
  20953. var sx = (x1 < x2) ? 1 : -1;
  20954. var sy = (y1 < y2) ? 1 : -1;
  20955. var err = dx - dy;
  20956. results.push([x1, y1]);
  20957. var i = 1;
  20958. while (!((x1 == x2) && (y1 == y2)))
  20959. {
  20960. var e2 = err << 1;
  20961. if (e2 > -dy)
  20962. {
  20963. err -= dy;
  20964. x1 += sx;
  20965. }
  20966. if (e2 < dx)
  20967. {
  20968. err += dx;
  20969. y1 += sy;
  20970. }
  20971. if (i % stepRate === 0)
  20972. {
  20973. results.push([x1, y1]);
  20974. }
  20975. i++;
  20976. }
  20977. return results;
  20978. },
  20979. /**
  20980. * Returns a new Line object with the same values for the start and end properties as this Line object.
  20981. * @method Phaser.Line#clone
  20982. * @param {Phaser.Line} output - Optional Line object. If given the values will be set into the object, otherwise a brand new Line object will be created and returned.
  20983. * @return {Phaser.Line} The cloned Line object.
  20984. */
  20985. clone: function (output) {
  20986. if (output === undefined || output === null)
  20987. {
  20988. output = new Phaser.Line(this.start.x, this.start.y, this.end.x, this.end.y);
  20989. }
  20990. else
  20991. {
  20992. output.setTo(this.start.x, this.start.y, this.end.x, this.end.y);
  20993. }
  20994. return output;
  20995. }
  20996. };
  20997. /**
  20998. * @name Phaser.Line#length
  20999. * @property {number} length - Gets the length of the line segment.
  21000. * @readonly
  21001. */
  21002. Object.defineProperty(Phaser.Line.prototype, "length", {
  21003. get: function () {
  21004. return Math.sqrt((this.end.x - this.start.x) * (this.end.x - this.start.x) + (this.end.y - this.start.y) * (this.end.y - this.start.y));
  21005. }
  21006. });
  21007. /**
  21008. * @name Phaser.Line#angle
  21009. * @property {number} angle - Gets the angle of the line in radians.
  21010. * @readonly
  21011. */
  21012. Object.defineProperty(Phaser.Line.prototype, "angle", {
  21013. get: function () {
  21014. return Math.atan2(this.end.y - this.start.y, this.end.x - this.start.x);
  21015. }
  21016. });
  21017. /**
  21018. * @name Phaser.Line#slope
  21019. * @property {number} slope - Gets the slope of the line (y/x).
  21020. * @readonly
  21021. */
  21022. Object.defineProperty(Phaser.Line.prototype, "slope", {
  21023. get: function () {
  21024. return (this.end.y - this.start.y) / (this.end.x - this.start.x);
  21025. }
  21026. });
  21027. /**
  21028. * @name Phaser.Line#perpSlope
  21029. * @property {number} perpSlope - Gets the perpendicular slope of the line (x/y).
  21030. * @readonly
  21031. */
  21032. Object.defineProperty(Phaser.Line.prototype, "perpSlope", {
  21033. get: function () {
  21034. return -((this.end.x - this.start.x) / (this.end.y - this.start.y));
  21035. }
  21036. });
  21037. /**
  21038. * @name Phaser.Line#x
  21039. * @property {number} x - Gets the x coordinate of the top left of the bounds around this line.
  21040. * @readonly
  21041. */
  21042. Object.defineProperty(Phaser.Line.prototype, "x", {
  21043. get: function () {
  21044. return Math.min(this.start.x, this.end.x);
  21045. }
  21046. });
  21047. /**
  21048. * @name Phaser.Line#y
  21049. * @property {number} y - Gets the y coordinate of the top left of the bounds around this line.
  21050. * @readonly
  21051. */
  21052. Object.defineProperty(Phaser.Line.prototype, "y", {
  21053. get: function () {
  21054. return Math.min(this.start.y, this.end.y);
  21055. }
  21056. });
  21057. /**
  21058. * @name Phaser.Line#left
  21059. * @property {number} left - Gets the left-most point of this line.
  21060. * @readonly
  21061. */
  21062. Object.defineProperty(Phaser.Line.prototype, "left", {
  21063. get: function () {
  21064. return Math.min(this.start.x, this.end.x);
  21065. }
  21066. });
  21067. /**
  21068. * @name Phaser.Line#right
  21069. * @property {number} right - Gets the right-most point of this line.
  21070. * @readonly
  21071. */
  21072. Object.defineProperty(Phaser.Line.prototype, "right", {
  21073. get: function () {
  21074. return Math.max(this.start.x, this.end.x);
  21075. }
  21076. });
  21077. /**
  21078. * @name Phaser.Line#top
  21079. * @property {number} top - Gets the top-most point of this line.
  21080. * @readonly
  21081. */
  21082. Object.defineProperty(Phaser.Line.prototype, "top", {
  21083. get: function () {
  21084. return Math.min(this.start.y, this.end.y);
  21085. }
  21086. });
  21087. /**
  21088. * @name Phaser.Line#bottom
  21089. * @property {number} bottom - Gets the bottom-most point of this line.
  21090. * @readonly
  21091. */
  21092. Object.defineProperty(Phaser.Line.prototype, "bottom", {
  21093. get: function () {
  21094. return Math.max(this.start.y, this.end.y);
  21095. }
  21096. });
  21097. /**
  21098. * @name Phaser.Line#width
  21099. * @property {number} width - Gets the width of this bounds of this line.
  21100. * @readonly
  21101. */
  21102. Object.defineProperty(Phaser.Line.prototype, "width", {
  21103. get: function () {
  21104. return Math.abs(this.start.x - this.end.x);
  21105. }
  21106. });
  21107. /**
  21108. * @name Phaser.Line#height
  21109. * @property {number} height - Gets the height of this bounds of this line.
  21110. * @readonly
  21111. */
  21112. Object.defineProperty(Phaser.Line.prototype, "height", {
  21113. get: function () {
  21114. return Math.abs(this.start.y - this.end.y);
  21115. }
  21116. });
  21117. /**
  21118. * @name Phaser.Line#normalX
  21119. * @property {number} normalX - Gets the x component of the left-hand normal of this line.
  21120. * @readonly
  21121. */
  21122. Object.defineProperty(Phaser.Line.prototype, "normalX", {
  21123. get: function () {
  21124. return Math.cos(this.angle - 1.5707963267948966);
  21125. }
  21126. });
  21127. /**
  21128. * @name Phaser.Line#normalY
  21129. * @property {number} normalY - Gets the y component of the left-hand normal of this line.
  21130. * @readonly
  21131. */
  21132. Object.defineProperty(Phaser.Line.prototype, "normalY", {
  21133. get: function () {
  21134. return Math.sin(this.angle - 1.5707963267948966);
  21135. }
  21136. });
  21137. /**
  21138. * @name Phaser.Line#normalAngle
  21139. * @property {number} normalAngle - Gets the angle in radians of the normal of this line (line.angle - 90 degrees.)
  21140. * @readonly
  21141. */
  21142. Object.defineProperty(Phaser.Line.prototype, "normalAngle", {
  21143. get: function () {
  21144. return Phaser.Math.wrap(this.angle - 1.5707963267948966, -Math.PI, Math.PI);
  21145. }
  21146. });
  21147. /**
  21148. * Checks for intersection between two lines as defined by the given start and end points.
  21149. * If asSegment is true it will check for line segment intersection. If asSegment is false it will check for line intersection.
  21150. * Returns the intersection segment of AB and EF as a Point, or null if there is no intersection.
  21151. * Adapted from code by Keith Hair
  21152. *
  21153. * @method Phaser.Line.intersectsPoints
  21154. * @param {Phaser.Point} a - The start of the first Line to be checked.
  21155. * @param {Phaser.Point} b - The end of the first line to be checked.
  21156. * @param {Phaser.Point} e - The start of the second Line to be checked.
  21157. * @param {Phaser.Point} f - The end of the second line to be checked.
  21158. * @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection.
  21159. * @param {Phaser.Point|object} [result] - A Point object to store the result in, if not given a new one will be created.
  21160. * @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection.
  21161. */
  21162. Phaser.Line.intersectsPoints = function (a, b, e, f, asSegment, result) {
  21163. if (asSegment === undefined) { asSegment = true; }
  21164. if (result === undefined) { result = new Phaser.Point(); }
  21165. var a1 = b.y - a.y;
  21166. var a2 = f.y - e.y;
  21167. var b1 = a.x - b.x;
  21168. var b2 = e.x - f.x;
  21169. var c1 = (b.x * a.y) - (a.x * b.y);
  21170. var c2 = (f.x * e.y) - (e.x * f.y);
  21171. var denom = (a1 * b2) - (a2 * b1);
  21172. if (denom === 0)
  21173. {
  21174. return null;
  21175. }
  21176. result.x = ((b1 * c2) - (b2 * c1)) / denom;
  21177. result.y = ((a2 * c1) - (a1 * c2)) / denom;
  21178. if (asSegment)
  21179. {
  21180. var uc = ((f.y - e.y) * (b.x - a.x) - (f.x - e.x) * (b.y - a.y));
  21181. var ua = (((f.x - e.x) * (a.y - e.y)) - (f.y - e.y) * (a.x - e.x)) / uc;
  21182. var ub = (((b.x - a.x) * (a.y - e.y)) - ((b.y - a.y) * (a.x - e.x))) / uc;
  21183. if (ua >= 0 && ua <= 1 && ub >= 0 && ub <= 1)
  21184. {
  21185. return result;
  21186. }
  21187. else
  21188. {
  21189. return null;
  21190. }
  21191. }
  21192. return result;
  21193. };
  21194. /**
  21195. * Checks for intersection between two lines.
  21196. * If asSegment is true it will check for segment intersection.
  21197. * If asSegment is false it will check for line intersection.
  21198. * Returns the intersection segment of AB and EF as a Point, or null if there is no intersection.
  21199. * Adapted from code by Keith Hair
  21200. *
  21201. * @method Phaser.Line.intersects
  21202. * @param {Phaser.Line} a - The first Line to be checked.
  21203. * @param {Phaser.Line} b - The second Line to be checked.
  21204. * @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection.
  21205. * @param {Phaser.Point} [result] - A Point object to store the result in, if not given a new one will be created.
  21206. * @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection.
  21207. */
  21208. Phaser.Line.intersects = function (a, b, asSegment, result) {
  21209. return Phaser.Line.intersectsPoints(a.start, a.end, b.start, b.end, asSegment, result);
  21210. };
  21211. /**
  21212. * Returns the reflected angle between two lines.
  21213. * This is the outgoing angle based on the angle of Line 1 and the normalAngle of Line 2.
  21214. *
  21215. * @method Phaser.Line.reflect
  21216. * @param {Phaser.Line} a - The base line.
  21217. * @param {Phaser.Line} b - The line to be reflected from the base line.
  21218. * @return {number} The reflected angle in radians.
  21219. */
  21220. Phaser.Line.reflect = function (a, b) {
  21221. return 2 * b.normalAngle - 3.141592653589793 - a.angle;
  21222. };
  21223. /**
  21224. * @author Mat Groves http://matgroves.com/ @Doormat23
  21225. * @author Richard Davey <rich@photonstorm.com>
  21226. * @copyright 2016 Photon Storm Ltd.
  21227. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  21228. */
  21229. /**
  21230. * The Matrix is a 3x3 matrix mostly used for display transforms within the renderer.
  21231. *
  21232. * It is represented like so:
  21233. *
  21234. * | a | b | tx |
  21235. * | c | d | ty |
  21236. * | 0 | 0 | 1 |
  21237. *
  21238. * @class Phaser.Matrix
  21239. * @constructor
  21240. * @param {number} [a=1]
  21241. * @param {number} [b=0]
  21242. * @param {number} [c=0]
  21243. * @param {number} [d=1]
  21244. * @param {number} [tx=0]
  21245. * @param {number} [ty=0]
  21246. */
  21247. Phaser.Matrix = function (a, b, c, d, tx, ty) {
  21248. a = a || 1;
  21249. b = b || 0;
  21250. c = c || 0;
  21251. d = d || 1;
  21252. tx = tx || 0;
  21253. ty = ty || 0;
  21254. /**
  21255. * @property {number} a
  21256. * @default 1
  21257. */
  21258. this.a = a;
  21259. /**
  21260. * @property {number} b
  21261. * @default 0
  21262. */
  21263. this.b = b;
  21264. /**
  21265. * @property {number} c
  21266. * @default 0
  21267. */
  21268. this.c = c;
  21269. /**
  21270. * @property {number} d
  21271. * @default 1
  21272. */
  21273. this.d = d;
  21274. /**
  21275. * @property {number} tx
  21276. * @default 0
  21277. */
  21278. this.tx = tx;
  21279. /**
  21280. * @property {number} ty
  21281. * @default 0
  21282. */
  21283. this.ty = ty;
  21284. /**
  21285. * @property {number} type - The const type of this object.
  21286. * @readonly
  21287. */
  21288. this.type = Phaser.MATRIX;
  21289. };
  21290. Phaser.Matrix.prototype = {
  21291. /**
  21292. * Sets the values of this Matrix to the values in the given array.
  21293. *
  21294. * The Array elements should be set as follows:
  21295. *
  21296. * a = array[0]
  21297. * b = array[1]
  21298. * c = array[3]
  21299. * d = array[4]
  21300. * tx = array[2]
  21301. * ty = array[5]
  21302. *
  21303. * @method Phaser.Matrix#fromArray
  21304. * @param {Array} array - The array to copy from.
  21305. * @return {Phaser.Matrix} This Matrix object.
  21306. */
  21307. fromArray: function (array) {
  21308. return this.setTo(array[0], array[1], array[3], array[4], array[2], array[5]);
  21309. },
  21310. /**
  21311. * Sets the values of this Matrix to the given values.
  21312. *
  21313. * @method Phaser.Matrix#setTo
  21314. * @param {number} a
  21315. * @param {number} b
  21316. * @param {number} c
  21317. * @param {number} d
  21318. * @param {number} tx
  21319. * @param {number} ty
  21320. * @return {Phaser.Matrix} This Matrix object.
  21321. */
  21322. setTo: function (a, b, c, d, tx, ty) {
  21323. this.a = a;
  21324. this.b = b;
  21325. this.c = c;
  21326. this.d = d;
  21327. this.tx = tx;
  21328. this.ty = ty;
  21329. return this;
  21330. },
  21331. /**
  21332. * Creates a new Matrix object based on the values of this Matrix.
  21333. * If you provide the output parameter the values of this Matrix will be copied over to it.
  21334. * If the output parameter is blank a new Matrix object will be created.
  21335. *
  21336. * @method Phaser.Matrix#clone
  21337. * @param {Phaser.Matrix} [output] - If provided the values of this Matrix will be copied to it, otherwise a new Matrix object is created.
  21338. * @return {Phaser.Matrix} A clone of this Matrix.
  21339. */
  21340. clone: function (output) {
  21341. if (output === undefined || output === null)
  21342. {
  21343. output = new Phaser.Matrix(this.a, this.b, this.c, this.d, this.tx, this.ty);
  21344. }
  21345. else
  21346. {
  21347. output.a = this.a;
  21348. output.b = this.b;
  21349. output.c = this.c;
  21350. output.d = this.d;
  21351. output.tx = this.tx;
  21352. output.ty = this.ty;
  21353. }
  21354. return output;
  21355. },
  21356. /**
  21357. * Copies the properties from this Matrix to the given Matrix.
  21358. *
  21359. * @method Phaser.Matrix#copyTo
  21360. * @param {Phaser.Matrix} matrix - The Matrix to copy from.
  21361. * @return {Phaser.Matrix} The destination Matrix object.
  21362. */
  21363. copyTo: function (matrix) {
  21364. matrix.copyFrom(this);
  21365. return matrix;
  21366. },
  21367. /**
  21368. * Copies the properties from the given Matrix into this Matrix.
  21369. *
  21370. * @method Phaser.Matrix#copyFrom
  21371. * @param {Phaser.Matrix} matrix - The Matrix to copy from.
  21372. * @return {Phaser.Matrix} This Matrix object.
  21373. */
  21374. copyFrom: function (matrix) {
  21375. this.a = matrix.a;
  21376. this.b = matrix.b;
  21377. this.c = matrix.c;
  21378. this.d = matrix.d;
  21379. this.tx = matrix.tx;
  21380. this.ty = matrix.ty;
  21381. return this;
  21382. },
  21383. /**
  21384. * Creates a Float32 Array with values populated from this Matrix object.
  21385. *
  21386. * @method Phaser.Matrix#toArray
  21387. * @param {boolean} [transpose=false] - Whether the values in the array are transposed or not.
  21388. * @param {PIXI.Float32Array} [array] - If provided the values will be set into this array, otherwise a new Float32Array is created.
  21389. * @return {PIXI.Float32Array} The newly created array which contains the matrix.
  21390. */
  21391. toArray: function (transpose, array) {
  21392. if (array === undefined) { array = new PIXI.Float32Array(9); }
  21393. if (transpose)
  21394. {
  21395. array[0] = this.a;
  21396. array[1] = this.b;
  21397. array[2] = 0;
  21398. array[3] = this.c;
  21399. array[4] = this.d;
  21400. array[5] = 0;
  21401. array[6] = this.tx;
  21402. array[7] = this.ty;
  21403. array[8] = 1;
  21404. }
  21405. else
  21406. {
  21407. array[0] = this.a;
  21408. array[1] = this.c;
  21409. array[2] = this.tx;
  21410. array[3] = this.b;
  21411. array[4] = this.d;
  21412. array[5] = this.ty;
  21413. array[6] = 0;
  21414. array[7] = 0;
  21415. array[8] = 1;
  21416. }
  21417. return array;
  21418. },
  21419. /**
  21420. * Get a new position with the current transformation applied.
  21421. *
  21422. * Can be used to go from a childs coordinate space to the world coordinate space (e.g. rendering)
  21423. *
  21424. * @method Phaser.Matrix#apply
  21425. * @param {Phaser.Point} pos - The origin Point.
  21426. * @param {Phaser.Point} [newPos] - The point that the new position is assigned to. This can be same as input point.
  21427. * @return {Phaser.Point} The new point, transformed through this matrix.
  21428. */
  21429. apply: function (pos, newPos) {
  21430. if (newPos === undefined) { newPos = new Phaser.Point(); }
  21431. newPos.x = this.a * pos.x + this.c * pos.y + this.tx;
  21432. newPos.y = this.b * pos.x + this.d * pos.y + this.ty;
  21433. return newPos;
  21434. },
  21435. /**
  21436. * Get a new position with the inverse of the current transformation applied.
  21437. *
  21438. * Can be used to go from the world coordinate space to a childs coordinate space. (e.g. input)
  21439. *
  21440. * @method Phaser.Matrix#applyInverse
  21441. * @param {Phaser.Point} pos - The origin Point.
  21442. * @param {Phaser.Point} [newPos] - The point that the new position is assigned to. This can be same as input point.
  21443. * @return {Phaser.Point} The new point, inverse transformed through this matrix.
  21444. */
  21445. applyInverse: function (pos, newPos) {
  21446. if (newPos === undefined) { newPos = new Phaser.Point(); }
  21447. var id = 1 / (this.a * this.d + this.c * -this.b);
  21448. var x = pos.x;
  21449. var y = pos.y;
  21450. newPos.x = this.d * id * x + -this.c * id * y + (this.ty * this.c - this.tx * this.d) * id;
  21451. newPos.y = this.a * id * y + -this.b * id * x + (-this.ty * this.a + this.tx * this.b) * id;
  21452. return newPos;
  21453. },
  21454. /**
  21455. * Translates the matrix on the x and y.
  21456. * This is the same as Matrix.tx += x.
  21457. *
  21458. * @method Phaser.Matrix#translate
  21459. * @param {number} x - The x value to translate on.
  21460. * @param {number} y - The y value to translate on.
  21461. * @return {Phaser.Matrix} This Matrix object.
  21462. */
  21463. translate: function (x, y) {
  21464. this.tx += x;
  21465. this.ty += y;
  21466. return this;
  21467. },
  21468. /**
  21469. * Applies a scale transformation to this matrix.
  21470. *
  21471. * @method Phaser.Matrix#scale
  21472. * @param {number} x - The amount to scale horizontally.
  21473. * @param {number} y - The amount to scale vertically.
  21474. * @return {Phaser.Matrix} This Matrix object.
  21475. */
  21476. scale: function (x, y) {
  21477. this.a *= x;
  21478. this.d *= y;
  21479. this.c *= x;
  21480. this.b *= y;
  21481. this.tx *= x;
  21482. this.ty *= y;
  21483. return this;
  21484. },
  21485. /**
  21486. * Applies a rotation transformation to this matrix.
  21487. *
  21488. * @method Phaser.Matrix#rotate
  21489. * @param {number} angle - The angle to rotate by, given in radians.
  21490. * @return {Phaser.Matrix} This Matrix object.
  21491. */
  21492. rotate: function (angle) {
  21493. var cos = Math.cos(angle);
  21494. var sin = Math.sin(angle);
  21495. var a1 = this.a;
  21496. var c1 = this.c;
  21497. var tx1 = this.tx;
  21498. this.a = a1 * cos-this.b * sin;
  21499. this.b = a1 * sin+this.b * cos;
  21500. this.c = c1 * cos-this.d * sin;
  21501. this.d = c1 * sin+this.d * cos;
  21502. this.tx = tx1 * cos - this.ty * sin;
  21503. this.ty = tx1 * sin + this.ty * cos;
  21504. return this;
  21505. },
  21506. /**
  21507. * Appends the given Matrix to this Matrix.
  21508. *
  21509. * @method Phaser.Matrix#append
  21510. * @param {Phaser.Matrix} matrix - The matrix to append to this one.
  21511. * @return {Phaser.Matrix} This Matrix object.
  21512. */
  21513. append: function (matrix) {
  21514. var a1 = this.a;
  21515. var b1 = this.b;
  21516. var c1 = this.c;
  21517. var d1 = this.d;
  21518. this.a = matrix.a * a1 + matrix.b * c1;
  21519. this.b = matrix.a * b1 + matrix.b * d1;
  21520. this.c = matrix.c * a1 + matrix.d * c1;
  21521. this.d = matrix.c * b1 + matrix.d * d1;
  21522. this.tx = matrix.tx * a1 + matrix.ty * c1 + this.tx;
  21523. this.ty = matrix.tx * b1 + matrix.ty * d1 + this.ty;
  21524. return this;
  21525. },
  21526. /**
  21527. * Resets this Matrix to an identity (default) matrix.
  21528. *
  21529. * @method Phaser.Matrix#identity
  21530. * @return {Phaser.Matrix} This Matrix object.
  21531. */
  21532. identity: function () {
  21533. return this.setTo(1, 0, 0, 1, 0, 0);
  21534. }
  21535. };
  21536. Phaser.identityMatrix = new Phaser.Matrix();
  21537. // Because PIXI uses its own type, we'll replace it with ours to avoid duplicating code or confusion.
  21538. PIXI.Matrix = Phaser.Matrix;
  21539. PIXI.identityMatrix = Phaser.identityMatrix;
  21540. /**
  21541. * @author Richard Davey <rich@photonstorm.com>
  21542. * @copyright 2016 Photon Storm Ltd.
  21543. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  21544. */
  21545. /**
  21546. * A Point object represents a location in a two-dimensional coordinate system, where x represents the horizontal axis and y represents the vertical axis.
  21547. * The following code creates a point at (0,0):
  21548. * `var myPoint = new Phaser.Point();`
  21549. * You can also use them as 2D Vectors and you'll find different vector related methods in this class.
  21550. *
  21551. * @class Phaser.Point
  21552. * @constructor
  21553. * @param {number} [x=0] - The horizontal position of this Point.
  21554. * @param {number} [y=0] - The vertical position of this Point.
  21555. */
  21556. Phaser.Point = function (x, y) {
  21557. x = x || 0;
  21558. y = y || 0;
  21559. /**
  21560. * @property {number} x - The x value of the point.
  21561. */
  21562. this.x = x;
  21563. /**
  21564. * @property {number} y - The y value of the point.
  21565. */
  21566. this.y = y;
  21567. /**
  21568. * @property {number} type - The const type of this object.
  21569. * @readonly
  21570. */
  21571. this.type = Phaser.POINT;
  21572. };
  21573. Phaser.Point.prototype = {
  21574. /**
  21575. * Copies the x and y properties from any given object to this Point.
  21576. *
  21577. * @method Phaser.Point#copyFrom
  21578. * @param {any} source - The object to copy from.
  21579. * @return {Phaser.Point} This Point object.
  21580. */
  21581. copyFrom: function (source) {
  21582. return this.setTo(source.x, source.y);
  21583. },
  21584. /**
  21585. * Inverts the x and y values of this Point
  21586. *
  21587. * @method Phaser.Point#invert
  21588. * @return {Phaser.Point} This Point object.
  21589. */
  21590. invert: function () {
  21591. return this.setTo(this.y, this.x);
  21592. },
  21593. /**
  21594. * Sets the `x` and `y` values of this Point object to the given values.
  21595. * If you omit the `y` value then the `x` value will be applied to both, for example:
  21596. * `Point.setTo(2)` is the same as `Point.setTo(2, 2)`
  21597. *
  21598. * @method Phaser.Point#setTo
  21599. * @param {number} x - The horizontal value of this point.
  21600. * @param {number} [y] - The vertical value of this point. If not given the x value will be used in its place.
  21601. * @return {Phaser.Point} This Point object. Useful for chaining method calls.
  21602. */
  21603. setTo: function (x, y) {
  21604. this.x = x || 0;
  21605. this.y = y || ( (y !== 0) ? this.x : 0 );
  21606. return this;
  21607. },
  21608. /**
  21609. * Sets the `x` and `y` values of this Point object to the given values.
  21610. * If you omit the `y` value then the `x` value will be applied to both, for example:
  21611. * `Point.set(2)` is the same as `Point.set(2, 2)`
  21612. *
  21613. * @method Phaser.Point#set
  21614. * @param {number} x - The horizontal value of this point.
  21615. * @param {number} [y] - The vertical value of this point. If not given the x value will be used in its place.
  21616. * @return {Phaser.Point} This Point object. Useful for chaining method calls.
  21617. */
  21618. set: function (x, y) {
  21619. this.x = x || 0;
  21620. this.y = y || ( (y !== 0) ? this.x : 0 );
  21621. return this;
  21622. },
  21623. /**
  21624. * Adds the given x and y values to this Point.
  21625. *
  21626. * @method Phaser.Point#add
  21627. * @param {number} x - The value to add to Point.x.
  21628. * @param {number} y - The value to add to Point.y.
  21629. * @return {Phaser.Point} This Point object. Useful for chaining method calls.
  21630. */
  21631. add: function (x, y) {
  21632. this.x += x;
  21633. this.y += y;
  21634. return this;
  21635. },
  21636. /**
  21637. * Subtracts the given x and y values from this Point.
  21638. *
  21639. * @method Phaser.Point#subtract
  21640. * @param {number} x - The value to subtract from Point.x.
  21641. * @param {number} y - The value to subtract from Point.y.
  21642. * @return {Phaser.Point} This Point object. Useful for chaining method calls.
  21643. */
  21644. subtract: function (x, y) {
  21645. this.x -= x;
  21646. this.y -= y;
  21647. return this;
  21648. },
  21649. /**
  21650. * Multiplies Point.x and Point.y by the given x and y values. Sometimes known as `Scale`.
  21651. *
  21652. * @method Phaser.Point#multiply
  21653. * @param {number} x - The value to multiply Point.x by.
  21654. * @param {number} y - The value to multiply Point.x by.
  21655. * @return {Phaser.Point} This Point object. Useful for chaining method calls.
  21656. */
  21657. multiply: function (x, y) {
  21658. this.x *= x;
  21659. this.y *= y;
  21660. return this;
  21661. },
  21662. /**
  21663. * Divides Point.x and Point.y by the given x and y values.
  21664. *
  21665. * @method Phaser.Point#divide
  21666. * @param {number} x - The value to divide Point.x by.
  21667. * @param {number} y - The value to divide Point.x by.
  21668. * @return {Phaser.Point} This Point object. Useful for chaining method calls.
  21669. */
  21670. divide: function (x, y) {
  21671. this.x /= x;
  21672. this.y /= y;
  21673. return this;
  21674. },
  21675. /**
  21676. * Clamps the x value of this Point to be between the given min and max.
  21677. *
  21678. * @method Phaser.Point#clampX
  21679. * @param {number} min - The minimum value to clamp this Point to.
  21680. * @param {number} max - The maximum value to clamp this Point to.
  21681. * @return {Phaser.Point} This Point object.
  21682. */
  21683. clampX: function (min, max) {
  21684. this.x = Phaser.Math.clamp(this.x, min, max);
  21685. return this;
  21686. },
  21687. /**
  21688. * Clamps the y value of this Point to be between the given min and max
  21689. *
  21690. * @method Phaser.Point#clampY
  21691. * @param {number} min - The minimum value to clamp this Point to.
  21692. * @param {number} max - The maximum value to clamp this Point to.
  21693. * @return {Phaser.Point} This Point object.
  21694. */
  21695. clampY: function (min, max) {
  21696. this.y = Phaser.Math.clamp(this.y, min, max);
  21697. return this;
  21698. },
  21699. /**
  21700. * Clamps this Point object values to be between the given min and max.
  21701. *
  21702. * @method Phaser.Point#clamp
  21703. * @param {number} min - The minimum value to clamp this Point to.
  21704. * @param {number} max - The maximum value to clamp this Point to.
  21705. * @return {Phaser.Point} This Point object.
  21706. */
  21707. clamp: function (min, max) {
  21708. this.x = Phaser.Math.clamp(this.x, min, max);
  21709. this.y = Phaser.Math.clamp(this.y, min, max);
  21710. return this;
  21711. },
  21712. /**
  21713. * Creates a copy of the given Point.
  21714. *
  21715. * @method Phaser.Point#clone
  21716. * @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.
  21717. * @return {Phaser.Point} The new Point object.
  21718. */
  21719. clone: function (output) {
  21720. if (output === undefined || output === null)
  21721. {
  21722. output = new Phaser.Point(this.x, this.y);
  21723. }
  21724. else
  21725. {
  21726. output.setTo(this.x, this.y);
  21727. }
  21728. return output;
  21729. },
  21730. /**
  21731. * Copies the x and y properties from this Point to any given object.
  21732. *
  21733. * @method Phaser.Point#copyTo
  21734. * @param {any} dest - The object to copy to.
  21735. * @return {object} The dest object.
  21736. */
  21737. copyTo: function (dest) {
  21738. dest.x = this.x;
  21739. dest.y = this.y;
  21740. return dest;
  21741. },
  21742. /**
  21743. * Returns the distance of this Point object to the given object (can be a Circle, Point or anything with x/y properties)
  21744. *
  21745. * @method Phaser.Point#distance
  21746. * @param {object} dest - The target object. Must have visible x and y properties that represent the center of the object.
  21747. * @param {boolean} [round] - Round the distance to the nearest integer (default false).
  21748. * @return {number} The distance between this Point object and the destination Point object.
  21749. */
  21750. distance: function (dest, round) {
  21751. return Phaser.Point.distance(this, dest, round);
  21752. },
  21753. /**
  21754. * Determines whether the given objects x/y values are equal to this Point object.
  21755. *
  21756. * @method Phaser.Point#equals
  21757. * @param {Phaser.Point|any} a - The object to compare with this Point.
  21758. * @return {boolean} A value of true if the x and y points are equal, otherwise false.
  21759. */
  21760. equals: function (a) {
  21761. return (a.x === this.x && a.y === this.y);
  21762. },
  21763. /**
  21764. * Returns the angle between this Point object and another object with public x and y properties.
  21765. *
  21766. * @method Phaser.Point#angle
  21767. * @param {Phaser.Point|any} a - The object to get the angle from this Point to.
  21768. * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)?
  21769. * @return {number} The angle between the two objects.
  21770. */
  21771. angle: function (a, asDegrees) {
  21772. if (asDegrees === undefined) { asDegrees = false; }
  21773. if (asDegrees)
  21774. {
  21775. return Phaser.Math.radToDeg(Math.atan2(a.y - this.y, a.x - this.x));
  21776. }
  21777. else
  21778. {
  21779. return Math.atan2(a.y - this.y, a.x - this.x);
  21780. }
  21781. },
  21782. /**
  21783. * Rotates this Point around the x/y coordinates given to the desired angle.
  21784. *
  21785. * @method Phaser.Point#rotate
  21786. * @param {number} x - The x coordinate of the anchor point.
  21787. * @param {number} y - The y coordinate of the anchor point.
  21788. * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the Point to.
  21789. * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)?
  21790. * @param {number} [distance] - An optional distance constraint between the Point and the anchor.
  21791. * @return {Phaser.Point} The modified point object.
  21792. */
  21793. rotate: function (x, y, angle, asDegrees, distance) {
  21794. return Phaser.Point.rotate(this, x, y, angle, asDegrees, distance);
  21795. },
  21796. /**
  21797. * Calculates the length of the Point object.
  21798. *
  21799. * @method Phaser.Point#getMagnitude
  21800. * @return {number} The length of the Point.
  21801. */
  21802. getMagnitude: function () {
  21803. return Math.sqrt((this.x * this.x) + (this.y * this.y));
  21804. },
  21805. /**
  21806. * Calculates the length squared of the Point object.
  21807. *
  21808. * @method Phaser.Point#getMagnitudeSq
  21809. * @return {number} The length ^ 2 of the Point.
  21810. */
  21811. getMagnitudeSq: function () {
  21812. return (this.x * this.x) + (this.y * this.y);
  21813. },
  21814. /**
  21815. * Alters the length of the Point without changing the direction.
  21816. *
  21817. * @method Phaser.Point#setMagnitude
  21818. * @param {number} magnitude - The desired magnitude of the resulting Point.
  21819. * @return {Phaser.Point} This Point object.
  21820. */
  21821. setMagnitude: function (magnitude) {
  21822. return this.normalize().multiply(magnitude, magnitude);
  21823. },
  21824. /**
  21825. * Alters the Point object so that its length is 1, but it retains the same direction.
  21826. *
  21827. * @method Phaser.Point#normalize
  21828. * @return {Phaser.Point} This Point object.
  21829. */
  21830. normalize: function () {
  21831. if (!this.isZero())
  21832. {
  21833. var m = this.getMagnitude();
  21834. this.x /= m;
  21835. this.y /= m;
  21836. }
  21837. return this;
  21838. },
  21839. /**
  21840. * Determine if this point is at 0,0.
  21841. *
  21842. * @method Phaser.Point#isZero
  21843. * @return {boolean} True if this Point is 0,0, otherwise false.
  21844. */
  21845. isZero: function () {
  21846. return (this.x === 0 && this.y === 0);
  21847. },
  21848. /**
  21849. * The dot product of this and another Point object.
  21850. *
  21851. * @method Phaser.Point#dot
  21852. * @param {Phaser.Point} a - The Point object to get the dot product combined with this Point.
  21853. * @return {number} The result.
  21854. */
  21855. dot: function (a) {
  21856. return ((this.x * a.x) + (this.y * a.y));
  21857. },
  21858. /**
  21859. * The cross product of this and another Point object.
  21860. *
  21861. * @method Phaser.Point#cross
  21862. * @param {Phaser.Point} a - The Point object to get the cross product combined with this Point.
  21863. * @return {number} The result.
  21864. */
  21865. cross: function (a) {
  21866. return ((this.x * a.y) - (this.y * a.x));
  21867. },
  21868. /**
  21869. * Make this Point perpendicular (90 degrees rotation)
  21870. *
  21871. * @method Phaser.Point#perp
  21872. * @return {Phaser.Point} This Point object.
  21873. */
  21874. perp: function () {
  21875. return this.setTo(-this.y, this.x);
  21876. },
  21877. /**
  21878. * Make this Point perpendicular (-90 degrees rotation)
  21879. *
  21880. * @method Phaser.Point#rperp
  21881. * @return {Phaser.Point} This Point object.
  21882. */
  21883. rperp: function () {
  21884. return this.setTo(this.y, -this.x);
  21885. },
  21886. /**
  21887. * Right-hand normalize (make unit length) this Point.
  21888. *
  21889. * @method Phaser.Point#normalRightHand
  21890. * @return {Phaser.Point} This Point object.
  21891. */
  21892. normalRightHand: function () {
  21893. return this.setTo(this.y * -1, this.x);
  21894. },
  21895. /**
  21896. * Math.floor() both the x and y properties of this Point.
  21897. *
  21898. * @method Phaser.Point#floor
  21899. * @return {Phaser.Point} This Point object.
  21900. */
  21901. floor: function () {
  21902. return this.setTo(Math.floor(this.x), Math.floor(this.y));
  21903. },
  21904. /**
  21905. * Math.ceil() both the x and y properties of this Point.
  21906. *
  21907. * @method Phaser.Point#ceil
  21908. * @return {Phaser.Point} This Point object.
  21909. */
  21910. ceil: function () {
  21911. return this.setTo(Math.ceil(this.x), Math.ceil(this.y));
  21912. },
  21913. /**
  21914. * Returns a string representation of this object.
  21915. *
  21916. * @method Phaser.Point#toString
  21917. * @return {string} A string representation of the instance.
  21918. */
  21919. toString: function () {
  21920. return '[{Point (x=' + this.x + ' y=' + this.y + ')}]';
  21921. }
  21922. };
  21923. Phaser.Point.prototype.constructor = Phaser.Point;
  21924. /**
  21925. * Adds the coordinates of two points together to create a new point.
  21926. *
  21927. * @method Phaser.Point.add
  21928. * @param {Phaser.Point} a - The first Point object.
  21929. * @param {Phaser.Point} b - The second Point object.
  21930. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  21931. * @return {Phaser.Point} The new Point object.
  21932. */
  21933. Phaser.Point.add = function (a, b, out) {
  21934. if (out === undefined) { out = new Phaser.Point(); }
  21935. out.x = a.x + b.x;
  21936. out.y = a.y + b.y;
  21937. return out;
  21938. };
  21939. /**
  21940. * Subtracts the coordinates of two points to create a new point.
  21941. *
  21942. * @method Phaser.Point.subtract
  21943. * @param {Phaser.Point} a - The first Point object.
  21944. * @param {Phaser.Point} b - The second Point object.
  21945. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  21946. * @return {Phaser.Point} The new Point object.
  21947. */
  21948. Phaser.Point.subtract = function (a, b, out) {
  21949. if (out === undefined) { out = new Phaser.Point(); }
  21950. out.x = a.x - b.x;
  21951. out.y = a.y - b.y;
  21952. return out;
  21953. };
  21954. /**
  21955. * Multiplies the coordinates of two points to create a new point.
  21956. *
  21957. * @method Phaser.Point.multiply
  21958. * @param {Phaser.Point} a - The first Point object.
  21959. * @param {Phaser.Point} b - The second Point object.
  21960. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  21961. * @return {Phaser.Point} The new Point object.
  21962. */
  21963. Phaser.Point.multiply = function (a, b, out) {
  21964. if (out === undefined) { out = new Phaser.Point(); }
  21965. out.x = a.x * b.x;
  21966. out.y = a.y * b.y;
  21967. return out;
  21968. };
  21969. /**
  21970. * Divides the coordinates of two points to create a new point.
  21971. *
  21972. * @method Phaser.Point.divide
  21973. * @param {Phaser.Point} a - The first Point object.
  21974. * @param {Phaser.Point} b - The second Point object.
  21975. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  21976. * @return {Phaser.Point} The new Point object.
  21977. */
  21978. Phaser.Point.divide = function (a, b, out) {
  21979. if (out === undefined) { out = new Phaser.Point(); }
  21980. out.x = a.x / b.x;
  21981. out.y = a.y / b.y;
  21982. return out;
  21983. };
  21984. /**
  21985. * Determines whether the two given Point objects are equal. They are considered equal if they have the same x and y values.
  21986. *
  21987. * @method Phaser.Point.equals
  21988. * @param {Phaser.Point} a - The first Point object.
  21989. * @param {Phaser.Point} b - The second Point object.
  21990. * @return {boolean} A value of true if the Points are equal, otherwise false.
  21991. */
  21992. Phaser.Point.equals = function (a, b) {
  21993. return (a.x === b.x && a.y === b.y);
  21994. };
  21995. /**
  21996. * Returns the angle between two Point objects.
  21997. *
  21998. * @method Phaser.Point.angle
  21999. * @param {Phaser.Point} a - The first Point object.
  22000. * @param {Phaser.Point} b - The second Point object.
  22001. * @return {number} The angle between the two Points.
  22002. */
  22003. Phaser.Point.angle = function (a, b) {
  22004. // return Math.atan2(a.x * b.y - a.y * b.x, a.x * b.x + a.y * b.y);
  22005. return Math.atan2(a.y - b.y, a.x - b.x);
  22006. };
  22007. /**
  22008. * Creates a negative Point.
  22009. *
  22010. * @method Phaser.Point.negative
  22011. * @param {Phaser.Point} a - The first Point object.
  22012. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  22013. * @return {Phaser.Point} The new Point object.
  22014. */
  22015. Phaser.Point.negative = function (a, out) {
  22016. if (out === undefined) { out = new Phaser.Point(); }
  22017. return out.setTo(-a.x, -a.y);
  22018. };
  22019. /**
  22020. * Adds two 2D Points together and multiplies the result by the given scalar.
  22021. *
  22022. * @method Phaser.Point.multiplyAdd
  22023. * @param {Phaser.Point} a - The first Point object.
  22024. * @param {Phaser.Point} b - The second Point object.
  22025. * @param {number} s - The scaling value.
  22026. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  22027. * @return {Phaser.Point} The new Point object.
  22028. */
  22029. Phaser.Point.multiplyAdd = function (a, b, s, out) {
  22030. if (out === undefined) { out = new Phaser.Point(); }
  22031. return out.setTo(a.x + b.x * s, a.y + b.y * s);
  22032. };
  22033. /**
  22034. * Interpolates the two given Points, based on the `f` value (between 0 and 1) and returns a new Point.
  22035. *
  22036. * @method Phaser.Point.interpolate
  22037. * @param {Phaser.Point} a - The first Point object.
  22038. * @param {Phaser.Point} b - The second Point object.
  22039. * @param {number} f - The level of interpolation between the two points. Indicates where the new point will be, along the line between pt1 and pt2. If f=1, pt1 is returned; if f=0, pt2 is returned.
  22040. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  22041. * @return {Phaser.Point} The new Point object.
  22042. */
  22043. Phaser.Point.interpolate = function (a, b, f, out) {
  22044. if (out === undefined) { out = new Phaser.Point(); }
  22045. return out.setTo(a.x + (b.x - a.x) * f, a.y + (b.y - a.y) * f);
  22046. };
  22047. /**
  22048. * Return a perpendicular vector (90 degrees rotation)
  22049. *
  22050. * @method Phaser.Point.perp
  22051. * @param {Phaser.Point} a - The Point object.
  22052. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  22053. * @return {Phaser.Point} The new Point object.
  22054. */
  22055. Phaser.Point.perp = function (a, out) {
  22056. if (out === undefined) { out = new Phaser.Point(); }
  22057. return out.setTo(-a.y, a.x);
  22058. };
  22059. /**
  22060. * Return a perpendicular vector (-90 degrees rotation)
  22061. *
  22062. * @method Phaser.Point.rperp
  22063. * @param {Phaser.Point} a - The Point object.
  22064. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  22065. * @return {Phaser.Point} The new Point object.
  22066. */
  22067. Phaser.Point.rperp = function (a, out) {
  22068. if (out === undefined) { out = new Phaser.Point(); }
  22069. return out.setTo(a.y, -a.x);
  22070. };
  22071. /**
  22072. * Returns the euclidian distance of this Point object to the given object (can be a Circle, Point or anything with x/y properties).
  22073. *
  22074. * @method Phaser.Point.distance
  22075. * @param {object} a - The target object. Must have visible x and y properties that represent the center of the object.
  22076. * @param {object} b - The target object. Must have visible x and y properties that represent the center of the object.
  22077. * @param {boolean} [round=false] - Round the distance to the nearest integer.
  22078. * @return {number} The distance between this Point object and the destination Point object.
  22079. */
  22080. Phaser.Point.distance = function (a, b, round) {
  22081. var distance = Phaser.Math.distance(a.x, a.y, b.x, b.y);
  22082. return round ? Math.round(distance) : distance;
  22083. };
  22084. /**
  22085. * Project two Points onto another Point.
  22086. *
  22087. * @method Phaser.Point.project
  22088. * @param {Phaser.Point} a - The first Point object.
  22089. * @param {Phaser.Point} b - The second Point object.
  22090. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  22091. * @return {Phaser.Point} The new Point object.
  22092. */
  22093. Phaser.Point.project = function (a, b, out) {
  22094. if (out === undefined) { out = new Phaser.Point(); }
  22095. var amt = a.dot(b) / b.getMagnitudeSq();
  22096. if (amt !== 0)
  22097. {
  22098. out.setTo(amt * b.x, amt * b.y);
  22099. }
  22100. return out;
  22101. };
  22102. /**
  22103. * Project two Points onto a Point of unit length.
  22104. *
  22105. * @method Phaser.Point.projectUnit
  22106. * @param {Phaser.Point} a - The first Point object.
  22107. * @param {Phaser.Point} b - The second Point object.
  22108. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  22109. * @return {Phaser.Point} The new Point object.
  22110. */
  22111. Phaser.Point.projectUnit = function (a, b, out) {
  22112. if (out === undefined) { out = new Phaser.Point(); }
  22113. var amt = a.dot(b);
  22114. if (amt !== 0)
  22115. {
  22116. out.setTo(amt * b.x, amt * b.y);
  22117. }
  22118. return out;
  22119. };
  22120. /**
  22121. * Right-hand normalize (make unit length) a Point.
  22122. *
  22123. * @method Phaser.Point.normalRightHand
  22124. * @param {Phaser.Point} a - The Point object.
  22125. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  22126. * @return {Phaser.Point} The new Point object.
  22127. */
  22128. Phaser.Point.normalRightHand = function (a, out) {
  22129. if (out === undefined) { out = new Phaser.Point(); }
  22130. return out.setTo(a.y * -1, a.x);
  22131. };
  22132. /**
  22133. * Normalize (make unit length) a Point.
  22134. *
  22135. * @method Phaser.Point.normalize
  22136. * @param {Phaser.Point} a - The Point object.
  22137. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  22138. * @return {Phaser.Point} The new Point object.
  22139. */
  22140. Phaser.Point.normalize = function (a, out) {
  22141. if (out === undefined) { out = new Phaser.Point(); }
  22142. var m = a.getMagnitude();
  22143. if (m !== 0)
  22144. {
  22145. out.setTo(a.x / m, a.y / m);
  22146. }
  22147. return out;
  22148. };
  22149. /**
  22150. * Rotates a Point object, or any object with exposed x/y properties, around the given coordinates by
  22151. * the angle specified. If the angle between the point and coordinates was 45 deg and the angle argument
  22152. * is 45 deg then the resulting angle will be 90 deg, as the angle argument is added to the current angle.
  22153. *
  22154. * The distance allows you to specify a distance constraint for the rotation between the point and the
  22155. * coordinates. If none is given the distance between the two is calculated and used.
  22156. *
  22157. * @method Phaser.Point.rotate
  22158. * @param {Phaser.Point} a - The Point object to rotate.
  22159. * @param {number} x - The x coordinate of the anchor point
  22160. * @param {number} y - The y coordinate of the anchor point
  22161. * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the Point by.
  22162. * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)?
  22163. * @param {number} [distance] - An optional distance constraint between the Point and the anchor.
  22164. * @return {Phaser.Point} The modified point object.
  22165. */
  22166. Phaser.Point.rotate = function (a, x, y, angle, asDegrees, distance) {
  22167. if (asDegrees) { angle = Phaser.Math.degToRad(angle); }
  22168. if (distance === undefined)
  22169. {
  22170. a.subtract(x, y);
  22171. var s = Math.sin(angle);
  22172. var c = Math.cos(angle);
  22173. var tx = c * a.x - s * a.y;
  22174. var ty = s * a.x + c * a.y;
  22175. a.x = tx + x;
  22176. a.y = ty + y;
  22177. }
  22178. else
  22179. {
  22180. var t = angle + Math.atan2(a.y - y, a.x - x);
  22181. a.x = x + distance * Math.cos(t);
  22182. a.y = y + distance * Math.sin(t);
  22183. }
  22184. return a;
  22185. };
  22186. /**
  22187. * Calculates centroid (or midpoint) from an array of points. If only one point is provided, that point is returned.
  22188. *
  22189. * @method Phaser.Point.centroid
  22190. * @param {Phaser.Point[]} points - The array of one or more points.
  22191. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  22192. * @return {Phaser.Point} The new Point object.
  22193. */
  22194. Phaser.Point.centroid = function (points, out) {
  22195. if (out === undefined) { out = new Phaser.Point(); }
  22196. if (Object.prototype.toString.call(points) !== '[object Array]')
  22197. {
  22198. throw new Error("Phaser.Point. Parameter 'points' must be an array");
  22199. }
  22200. var pointslength = points.length;
  22201. if (pointslength < 1)
  22202. {
  22203. throw new Error("Phaser.Point. Parameter 'points' array must not be empty");
  22204. }
  22205. if (pointslength === 1)
  22206. {
  22207. out.copyFrom(points[0]);
  22208. return out;
  22209. }
  22210. for (var i = 0; i < pointslength; i++)
  22211. {
  22212. Phaser.Point.add(out, points[i], out);
  22213. }
  22214. out.divide(pointslength, pointslength);
  22215. return out;
  22216. };
  22217. /**
  22218. * Parses an object for x and/or y properties and returns a new Phaser.Point with matching values.
  22219. * If the object doesn't contain those properties a Point with x/y of zero will be returned.
  22220. *
  22221. * @method Phaser.Point.parse
  22222. * @static
  22223. * @param {object} obj - The object to parse.
  22224. * @param {string} [xProp='x'] - The property used to set the Point.x value.
  22225. * @param {string} [yProp='y'] - The property used to set the Point.y value.
  22226. * @return {Phaser.Point} The new Point object.
  22227. */
  22228. Phaser.Point.parse = function(obj, xProp, yProp) {
  22229. xProp = xProp || 'x';
  22230. yProp = yProp || 'y';
  22231. var point = new Phaser.Point();
  22232. if (obj[xProp])
  22233. {
  22234. point.x = parseInt(obj[xProp], 10);
  22235. }
  22236. if (obj[yProp])
  22237. {
  22238. point.y = parseInt(obj[yProp], 10);
  22239. }
  22240. return point;
  22241. };
  22242. // Because PIXI uses its own Point, we'll replace it with ours to avoid duplicating code or confusion.
  22243. PIXI.Point = Phaser.Point;
  22244. /**
  22245. * @author Richard Davey <rich@photonstorm.com>
  22246. * @author Adrien Brault <adrien.brault@gmail.com>
  22247. * @copyright 2016 Photon Storm Ltd.
  22248. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  22249. */
  22250. /**
  22251. * Creates a new Polygon.
  22252. *
  22253. * The points can be set from a variety of formats:
  22254. *
  22255. * - An array of Point objects: `[new Phaser.Point(x1, y1), ...]`
  22256. * - An array of objects with public x/y properties: `[obj1, obj2, ...]`
  22257. * - An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]`
  22258. * - As separate Point arguments: `setTo(new Phaser.Point(x1, y1), ...)`
  22259. * - As separate objects with public x/y properties arguments: `setTo(obj1, obj2, ...)`
  22260. * - As separate arguments representing point coordinates: `setTo(x1,y1, x2,y2, ...)`
  22261. *
  22262. * @class Phaser.Polygon
  22263. * @constructor
  22264. * @param {Phaser.Point[]|number[]|...Phaser.Point|...number} points - The points to set.
  22265. */
  22266. Phaser.Polygon = function () {
  22267. /**
  22268. * @property {number} area - The area of this Polygon.
  22269. */
  22270. this.area = 0;
  22271. /**
  22272. * @property {array} _points - An array of Points that make up this Polygon.
  22273. * @private
  22274. */
  22275. this._points = [];
  22276. if (arguments.length > 0)
  22277. {
  22278. this.setTo.apply(this, arguments);
  22279. }
  22280. /**
  22281. * @property {boolean} closed - Is the Polygon closed or not?
  22282. */
  22283. this.closed = true;
  22284. /**
  22285. * @property {number} type - The base object type.
  22286. */
  22287. this.type = Phaser.POLYGON;
  22288. };
  22289. Phaser.Polygon.prototype = {
  22290. /**
  22291. * Export the points as an array of flat numbers, following the sequence [ x,y, x,y, x,y ]
  22292. *
  22293. * @method Phaser.Polygon#toNumberArray
  22294. * @param {array} [output] - The array to append the points to. If not specified a new array will be created.
  22295. * @return {array} The flattened array.
  22296. */
  22297. toNumberArray: function (output) {
  22298. if (output === undefined) { output = []; }
  22299. for (var i = 0; i < this._points.length; i++)
  22300. {
  22301. if (typeof this._points[i] === 'number')
  22302. {
  22303. output.push(this._points[i]);
  22304. output.push(this._points[i + 1]);
  22305. i++;
  22306. }
  22307. else
  22308. {
  22309. output.push(this._points[i].x);
  22310. output.push(this._points[i].y);
  22311. }
  22312. }
  22313. return output;
  22314. },
  22315. /**
  22316. * Flattens this Polygon so the points are a sequence of numbers. Any Point objects found are removed and replaced with two numbers.
  22317. *
  22318. * @method Phaser.Polygon#flatten
  22319. * @return {Phaser.Polygon} This Polygon object
  22320. */
  22321. flatten: function () {
  22322. this._points = this.toNumberArray();
  22323. return this;
  22324. },
  22325. /**
  22326. * Creates a copy of the given Polygon.
  22327. * This is a deep clone, the resulting copy contains new Phaser.Point objects
  22328. *
  22329. * @method Phaser.Polygon#clone
  22330. * @param {Phaser.Polygon} [output=(new Polygon)] - The polygon to update. If not specified a new polygon will be created.
  22331. * @return {Phaser.Polygon} The cloned (`output`) polygon object.
  22332. */
  22333. clone: function (output) {
  22334. var points = this._points.slice();
  22335. if (output === undefined || output === null)
  22336. {
  22337. output = new Phaser.Polygon(points);
  22338. }
  22339. else
  22340. {
  22341. output.setTo(points);
  22342. }
  22343. return output;
  22344. },
  22345. /**
  22346. * Checks whether the x and y coordinates are contained within this polygon.
  22347. *
  22348. * @method Phaser.Polygon#contains
  22349. * @param {number} x - The X value of the coordinate to test.
  22350. * @param {number} y - The Y value of the coordinate to test.
  22351. * @return {boolean} True if the coordinates are within this polygon, otherwise false.
  22352. */
  22353. contains: function (x, y) {
  22354. // Adapted from http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html by Jonas Raoni Soares Silva
  22355. var length = this._points.length;
  22356. var inside = false;
  22357. for (var i = -1, j = length - 1; ++i < length; j = i)
  22358. {
  22359. var ix = this._points[i].x;
  22360. var iy = this._points[i].y;
  22361. var jx = this._points[j].x;
  22362. var jy = this._points[j].y;
  22363. if (((iy <= y && y < jy) || (jy <= y && y < iy)) && (x < (jx - ix) * (y - iy) / (jy - iy) + ix))
  22364. {
  22365. inside = !inside;
  22366. }
  22367. }
  22368. return inside;
  22369. },
  22370. /**
  22371. * Sets this Polygon to the given points.
  22372. *
  22373. * The points can be set from a variety of formats:
  22374. *
  22375. * - An array of Point objects: `[new Phaser.Point(x1, y1), ...]`
  22376. * - An array of objects with public x/y properties: `[obj1, obj2, ...]`
  22377. * - An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]`
  22378. * - An array of arrays with two elements representing x/y coordinates: `[[x1, y1], [x2, y2], ...]`
  22379. * - As separate Point arguments: `setTo(new Phaser.Point(x1, y1), ...)`
  22380. * - As separate objects with public x/y properties arguments: `setTo(obj1, obj2, ...)`
  22381. * - As separate arguments representing point coordinates: `setTo(x1,y1, x2,y2, ...)`
  22382. *
  22383. * `setTo` may also be called without any arguments to remove all points.
  22384. *
  22385. * @method Phaser.Polygon#setTo
  22386. * @param {Phaser.Point[]|number[]|...Phaser.Point|...number} points - The points to set.
  22387. * @return {Phaser.Polygon} This Polygon object
  22388. */
  22389. setTo: function (points) {
  22390. this.area = 0;
  22391. this._points = [];
  22392. if (arguments.length > 0)
  22393. {
  22394. // If points isn't an array, use arguments as the array
  22395. if (!Array.isArray(points))
  22396. {
  22397. points = Array.prototype.slice.call(arguments);
  22398. }
  22399. var y0 = Number.MAX_VALUE;
  22400. // Allows for mixed-type arguments
  22401. for (var i = 0, len = points.length; i < len; i++)
  22402. {
  22403. if (typeof points[i] === 'number')
  22404. {
  22405. var p = new PIXI.Point(points[i], points[i + 1]);
  22406. i++;
  22407. }
  22408. else if (Array.isArray(points[i]))
  22409. {
  22410. var p = new PIXI.Point(points[i][0], points[i][1]);
  22411. }
  22412. else
  22413. {
  22414. var p = new PIXI.Point(points[i].x, points[i].y);
  22415. }
  22416. this._points.push(p);
  22417. // Lowest boundary
  22418. if (p.y < y0)
  22419. {
  22420. y0 = p.y;
  22421. }
  22422. }
  22423. this.calculateArea(y0);
  22424. }
  22425. return this;
  22426. },
  22427. /**
  22428. * Calcuates the area of the Polygon. This is available in the property Polygon.area
  22429. *
  22430. * @method Phaser.Polygon#calculateArea
  22431. * @private
  22432. * @param {number} y0 - The lowest boundary
  22433. * @return {number} The area of the Polygon.
  22434. */
  22435. calculateArea: function (y0) {
  22436. var p1;
  22437. var p2;
  22438. var avgHeight;
  22439. var width;
  22440. for (var i = 0, len = this._points.length; i < len; i++)
  22441. {
  22442. p1 = this._points[i];
  22443. if (i === len - 1)
  22444. {
  22445. p2 = this._points[0];
  22446. }
  22447. else
  22448. {
  22449. p2 = this._points[i + 1];
  22450. }
  22451. avgHeight = ((p1.y - y0) + (p2.y - y0)) / 2;
  22452. width = p1.x - p2.x;
  22453. this.area += avgHeight * width;
  22454. }
  22455. return this.area;
  22456. }
  22457. };
  22458. Phaser.Polygon.prototype.constructor = Phaser.Polygon;
  22459. /**
  22460. * Sets and modifies the points of this polygon.
  22461. *
  22462. * See {@link Phaser.Polygon#setTo setTo} for the different kinds of arrays formats that can be assigned.
  22463. *
  22464. * @name Phaser.Polygon#points
  22465. * @property {Phaser.Point[]} points - The array of vertex points.
  22466. * @deprecated Use `setTo`.
  22467. */
  22468. Object.defineProperty(Phaser.Polygon.prototype, 'points', {
  22469. get: function() {
  22470. return this._points;
  22471. },
  22472. set: function(points) {
  22473. if (points != null)
  22474. {
  22475. this.setTo(points);
  22476. }
  22477. else
  22478. {
  22479. // Clear the points
  22480. this.setTo();
  22481. }
  22482. }
  22483. });
  22484. // Because PIXI uses its own type, we'll replace it with ours to avoid duplicating code or confusion.
  22485. PIXI.Polygon = Phaser.Polygon;
  22486. /**
  22487. * @author Richard Davey <rich@photonstorm.com>
  22488. * @copyright 2016 Photon Storm Ltd.
  22489. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  22490. */
  22491. /**
  22492. * 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.
  22493. * If you call this function without parameters, a Rectangle with x, y, width, and height properties set to 0 is created.
  22494. *
  22495. * @class Phaser.Rectangle
  22496. * @constructor
  22497. * @param {number} x - The x coordinate of the top-left corner of the Rectangle.
  22498. * @param {number} y - The y coordinate of the top-left corner of the Rectangle.
  22499. * @param {number} width - The width of the Rectangle. Should always be either zero or a positive value.
  22500. * @param {number} height - The height of the Rectangle. Should always be either zero or a positive value.
  22501. */
  22502. Phaser.Rectangle = function (x, y, width, height) {
  22503. x = x || 0;
  22504. y = y || 0;
  22505. width = width || 0;
  22506. height = height || 0;
  22507. /**
  22508. * @property {number} x - The x coordinate of the top-left corner of the Rectangle.
  22509. */
  22510. this.x = x;
  22511. /**
  22512. * @property {number} y - The y coordinate of the top-left corner of the Rectangle.
  22513. */
  22514. this.y = y;
  22515. /**
  22516. * @property {number} width - The width of the Rectangle. This value should never be set to a negative.
  22517. */
  22518. this.width = width;
  22519. /**
  22520. * @property {number} height - The height of the Rectangle. This value should never be set to a negative.
  22521. */
  22522. this.height = height;
  22523. /**
  22524. * @property {number} type - The const type of this object.
  22525. * @readonly
  22526. */
  22527. this.type = Phaser.RECTANGLE;
  22528. };
  22529. Phaser.Rectangle.prototype = {
  22530. /**
  22531. * Adjusts the location of the Rectangle object, as determined by its top-left corner, by the specified amounts.
  22532. * @method Phaser.Rectangle#offset
  22533. * @param {number} dx - Moves the x value of the Rectangle object by this amount.
  22534. * @param {number} dy - Moves the y value of the Rectangle object by this amount.
  22535. * @return {Phaser.Rectangle} This Rectangle object.
  22536. */
  22537. offset: function (dx, dy) {
  22538. this.x += dx;
  22539. this.y += dy;
  22540. return this;
  22541. },
  22542. /**
  22543. * 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.
  22544. * @method Phaser.Rectangle#offsetPoint
  22545. * @param {Phaser.Point} point - A Point object to use to offset this Rectangle object.
  22546. * @return {Phaser.Rectangle} This Rectangle object.
  22547. */
  22548. offsetPoint: function (point) {
  22549. return this.offset(point.x, point.y);
  22550. },
  22551. /**
  22552. * Sets the members of Rectangle to the specified values.
  22553. * @method Phaser.Rectangle#setTo
  22554. * @param {number} x - The x coordinate of the top-left corner of the Rectangle.
  22555. * @param {number} y - The y coordinate of the top-left corner of the Rectangle.
  22556. * @param {number} width - The width of the Rectangle. Should always be either zero or a positive value.
  22557. * @param {number} height - The height of the Rectangle. Should always be either zero or a positive value.
  22558. * @return {Phaser.Rectangle} This Rectangle object
  22559. */
  22560. setTo: function (x, y, width, height) {
  22561. this.x = x;
  22562. this.y = y;
  22563. this.width = width;
  22564. this.height = height;
  22565. return this;
  22566. },
  22567. /**
  22568. * Scales the width and height of this Rectangle by the given amounts.
  22569. *
  22570. * @method Phaser.Rectangle#scale
  22571. * @param {number} x - The amount to scale the width of the Rectangle by. A value of 0.5 would reduce by half, a value of 2 would double the width, etc.
  22572. * @param {number} [y] - The amount to scale the height of the Rectangle by. A value of 0.5 would reduce by half, a value of 2 would double the height, etc.
  22573. * @return {Phaser.Rectangle} This Rectangle object
  22574. */
  22575. scale: function (x, y) {
  22576. if (y === undefined) { y = x; }
  22577. this.width *= x;
  22578. this.height *= y;
  22579. return this;
  22580. },
  22581. /**
  22582. * Centers this Rectangle so that the center coordinates match the given x and y values.
  22583. *
  22584. * @method Phaser.Rectangle#centerOn
  22585. * @param {number} x - The x coordinate to place the center of the Rectangle at.
  22586. * @param {number} y - The y coordinate to place the center of the Rectangle at.
  22587. * @return {Phaser.Rectangle} This Rectangle object
  22588. */
  22589. centerOn: function (x, y) {
  22590. this.centerX = x;
  22591. this.centerY = y;
  22592. return this;
  22593. },
  22594. /**
  22595. * Runs Math.floor() on both the x and y values of this Rectangle.
  22596. * @method Phaser.Rectangle#floor
  22597. */
  22598. floor: function () {
  22599. this.x = Math.floor(this.x);
  22600. this.y = Math.floor(this.y);
  22601. },
  22602. /**
  22603. * Runs Math.floor() on the x, y, width and height values of this Rectangle.
  22604. * @method Phaser.Rectangle#floorAll
  22605. */
  22606. floorAll: function () {
  22607. this.x = Math.floor(this.x);
  22608. this.y = Math.floor(this.y);
  22609. this.width = Math.floor(this.width);
  22610. this.height = Math.floor(this.height);
  22611. },
  22612. /**
  22613. * Runs Math.ceil() on both the x and y values of this Rectangle.
  22614. * @method Phaser.Rectangle#ceil
  22615. */
  22616. ceil: function () {
  22617. this.x = Math.ceil(this.x);
  22618. this.y = Math.ceil(this.y);
  22619. },
  22620. /**
  22621. * Runs Math.ceil() on the x, y, width and height values of this Rectangle.
  22622. * @method Phaser.Rectangle#ceilAll
  22623. */
  22624. ceilAll: function () {
  22625. this.x = Math.ceil(this.x);
  22626. this.y = Math.ceil(this.y);
  22627. this.width = Math.ceil(this.width);
  22628. this.height = Math.ceil(this.height);
  22629. },
  22630. /**
  22631. * Copies the x, y, width and height properties from any given object to this Rectangle.
  22632. * @method Phaser.Rectangle#copyFrom
  22633. * @param {any} source - The object to copy from.
  22634. * @return {Phaser.Rectangle} This Rectangle object.
  22635. */
  22636. copyFrom: function (source) {
  22637. return this.setTo(source.x, source.y, source.width, source.height);
  22638. },
  22639. /**
  22640. * Copies the x, y, width and height properties from this Rectangle to any given object.
  22641. * @method Phaser.Rectangle#copyTo
  22642. * @param {any} source - The object to copy to.
  22643. * @return {object} This object.
  22644. */
  22645. copyTo: function (dest) {
  22646. dest.x = this.x;
  22647. dest.y = this.y;
  22648. dest.width = this.width;
  22649. dest.height = this.height;
  22650. return dest;
  22651. },
  22652. /**
  22653. * 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.
  22654. * @method Phaser.Rectangle#inflate
  22655. * @param {number} dx - The amount to be added to the left side of the Rectangle.
  22656. * @param {number} dy - The amount to be added to the bottom side of the Rectangle.
  22657. * @return {Phaser.Rectangle} This Rectangle object.
  22658. */
  22659. inflate: function (dx, dy) {
  22660. return Phaser.Rectangle.inflate(this, dx, dy);
  22661. },
  22662. /**
  22663. * The size of the Rectangle object, expressed as a Point object with the values of the width and height properties.
  22664. * @method Phaser.Rectangle#size
  22665. * @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.
  22666. * @return {Phaser.Point} The size of the Rectangle object.
  22667. */
  22668. size: function (output) {
  22669. return Phaser.Rectangle.size(this, output);
  22670. },
  22671. /**
  22672. * Resize the Rectangle by providing a new width and height.
  22673. * The x and y positions remain unchanged.
  22674. *
  22675. * @method Phaser.Rectangle#resize
  22676. * @param {number} width - The width of the Rectangle. Should always be either zero or a positive value.
  22677. * @param {number} height - The height of the Rectangle. Should always be either zero or a positive value.
  22678. * @return {Phaser.Rectangle} This Rectangle object
  22679. */
  22680. resize: function (width, height) {
  22681. this.width = width;
  22682. this.height = height;
  22683. return this;
  22684. },
  22685. /**
  22686. * Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object.
  22687. * @method Phaser.Rectangle#clone
  22688. * @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.
  22689. * @return {Phaser.Rectangle}
  22690. */
  22691. clone: function (output) {
  22692. return Phaser.Rectangle.clone(this, output);
  22693. },
  22694. /**
  22695. * Determines whether the specified coordinates are contained within the region defined by this Rectangle object.
  22696. * @method Phaser.Rectangle#contains
  22697. * @param {number} x - The x coordinate of the point to test.
  22698. * @param {number} y - The y coordinate of the point to test.
  22699. * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
  22700. */
  22701. contains: function (x, y) {
  22702. return Phaser.Rectangle.contains(this, x, y);
  22703. },
  22704. /**
  22705. * Determines whether the first Rectangle object is fully contained within the second Rectangle object.
  22706. * A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first.
  22707. * @method Phaser.Rectangle#containsRect
  22708. * @param {Phaser.Rectangle} b - The second Rectangle object.
  22709. * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
  22710. */
  22711. containsRect: function (b) {
  22712. return Phaser.Rectangle.containsRect(b, this);
  22713. },
  22714. /**
  22715. * Determines whether the two Rectangles are equal.
  22716. * This method compares the x, y, width and height properties of each Rectangle.
  22717. * @method Phaser.Rectangle#equals
  22718. * @param {Phaser.Rectangle} b - The second Rectangle object.
  22719. * @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.
  22720. */
  22721. equals: function (b) {
  22722. return Phaser.Rectangle.equals(this, b);
  22723. },
  22724. /**
  22725. * 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.
  22726. * @method Phaser.Rectangle#intersection
  22727. * @param {Phaser.Rectangle} b - The second Rectangle object.
  22728. * @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.
  22729. * @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.
  22730. */
  22731. intersection: function (b, out) {
  22732. return Phaser.Rectangle.intersection(this, b, out);
  22733. },
  22734. /**
  22735. * Determines whether this Rectangle and another given Rectangle intersect with each other.
  22736. * This method checks the x, y, width, and height properties of the two Rectangles.
  22737. *
  22738. * @method Phaser.Rectangle#intersects
  22739. * @param {Phaser.Rectangle} b - The second Rectangle object.
  22740. * @return {boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false.
  22741. */
  22742. intersects: function (b) {
  22743. return Phaser.Rectangle.intersects(this, b);
  22744. },
  22745. /**
  22746. * Determines whether the coordinates given intersects (overlaps) with this Rectangle.
  22747. *
  22748. * @method Phaser.Rectangle#intersectsRaw
  22749. * @param {number} left - The x coordinate of the left of the area.
  22750. * @param {number} right - The right coordinate of the area.
  22751. * @param {number} top - The y coordinate of the area.
  22752. * @param {number} bottom - The bottom coordinate of the area.
  22753. * @param {number} tolerance - A tolerance value to allow for an intersection test with padding, default to 0
  22754. * @return {boolean} A value of true if the specified object intersects with the Rectangle; otherwise false.
  22755. */
  22756. intersectsRaw: function (left, right, top, bottom, tolerance) {
  22757. return Phaser.Rectangle.intersectsRaw(this, left, right, top, bottom, tolerance);
  22758. },
  22759. /**
  22760. * Adds two Rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two Rectangles.
  22761. * @method Phaser.Rectangle#union
  22762. * @param {Phaser.Rectangle} b - The second Rectangle object.
  22763. * @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.
  22764. * @return {Phaser.Rectangle} A Rectangle object that is the union of the two Rectangles.
  22765. */
  22766. union: function (b, out) {
  22767. return Phaser.Rectangle.union(this, b, out);
  22768. },
  22769. /**
  22770. * Returns a uniformly distributed random point from anywhere within this Rectangle.
  22771. *
  22772. * @method Phaser.Rectangle#random
  22773. * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in.
  22774. * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object.
  22775. * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties.
  22776. */
  22777. random: function (out) {
  22778. if (out === undefined) { out = new Phaser.Point(); }
  22779. out.x = this.randomX;
  22780. out.y = this.randomY;
  22781. return out;
  22782. },
  22783. /**
  22784. * Returns a string representation of this object.
  22785. * @method Phaser.Rectangle#toString
  22786. * @return {string} A string representation of the instance.
  22787. */
  22788. toString: function () {
  22789. return "[{Rectangle (x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + " empty=" + this.empty + ")}]";
  22790. }
  22791. };
  22792. /**
  22793. * @name Phaser.Rectangle#halfWidth
  22794. * @property {number} halfWidth - Half of the width of the Rectangle.
  22795. * @readonly
  22796. */
  22797. Object.defineProperty(Phaser.Rectangle.prototype, "halfWidth", {
  22798. get: function () {
  22799. return Math.round(this.width / 2);
  22800. }
  22801. });
  22802. /**
  22803. * @name Phaser.Rectangle#halfHeight
  22804. * @property {number} halfHeight - Half of the height of the Rectangle.
  22805. * @readonly
  22806. */
  22807. Object.defineProperty(Phaser.Rectangle.prototype, "halfHeight", {
  22808. get: function () {
  22809. return Math.round(this.height / 2);
  22810. }
  22811. });
  22812. /**
  22813. * 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.
  22814. * @name Phaser.Rectangle#bottom
  22815. * @property {number} bottom - The sum of the y and height properties.
  22816. */
  22817. Object.defineProperty(Phaser.Rectangle.prototype, "bottom", {
  22818. get: function () {
  22819. return this.y + this.height;
  22820. },
  22821. set: function (value) {
  22822. if (value <= this.y)
  22823. {
  22824. this.height = 0;
  22825. }
  22826. else
  22827. {
  22828. this.height = value - this.y;
  22829. }
  22830. }
  22831. });
  22832. /**
  22833. * The location of the Rectangles bottom left corner as a Point object.
  22834. * @name Phaser.Rectangle#bottomLeft
  22835. * @property {Phaser.Point} bottomLeft - Gets or sets the location of the Rectangles bottom left corner as a Point object.
  22836. */
  22837. Object.defineProperty(Phaser.Rectangle.prototype, "bottomLeft", {
  22838. get: function () {
  22839. return new Phaser.Point(this.x, this.bottom);
  22840. },
  22841. set: function (value) {
  22842. this.x = value.x;
  22843. this.bottom = value.y;
  22844. }
  22845. });
  22846. /**
  22847. * The location of the Rectangles bottom right corner as a Point object.
  22848. * @name Phaser.Rectangle#bottomRight
  22849. * @property {Phaser.Point} bottomRight - Gets or sets the location of the Rectangles bottom right corner as a Point object.
  22850. */
  22851. Object.defineProperty(Phaser.Rectangle.prototype, "bottomRight", {
  22852. get: function () {
  22853. return new Phaser.Point(this.right, this.bottom);
  22854. },
  22855. set: function (value) {
  22856. this.right = value.x;
  22857. this.bottom = value.y;
  22858. }
  22859. });
  22860. /**
  22861. * 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.
  22862. * @name Phaser.Rectangle#left
  22863. * @property {number} left - The x coordinate of the left of the Rectangle.
  22864. */
  22865. Object.defineProperty(Phaser.Rectangle.prototype, "left", {
  22866. get: function () {
  22867. return this.x;
  22868. },
  22869. set: function (value) {
  22870. if (value >= this.right) {
  22871. this.width = 0;
  22872. } else {
  22873. this.width = this.right - value;
  22874. }
  22875. this.x = value;
  22876. }
  22877. });
  22878. /**
  22879. * 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.
  22880. * @name Phaser.Rectangle#right
  22881. * @property {number} right - The sum of the x and width properties.
  22882. */
  22883. Object.defineProperty(Phaser.Rectangle.prototype, "right", {
  22884. get: function () {
  22885. return this.x + this.width;
  22886. },
  22887. set: function (value) {
  22888. if (value <= this.x) {
  22889. this.width = 0;
  22890. } else {
  22891. this.width = value - this.x;
  22892. }
  22893. }
  22894. });
  22895. /**
  22896. * The volume of the Rectangle derived from width * height.
  22897. * @name Phaser.Rectangle#volume
  22898. * @property {number} volume - The volume of the Rectangle derived from width * height.
  22899. * @readonly
  22900. */
  22901. Object.defineProperty(Phaser.Rectangle.prototype, "volume", {
  22902. get: function () {
  22903. return this.width * this.height;
  22904. }
  22905. });
  22906. /**
  22907. * The perimeter size of the Rectangle. This is the sum of all 4 sides.
  22908. * @name Phaser.Rectangle#perimeter
  22909. * @property {number} perimeter - The perimeter size of the Rectangle. This is the sum of all 4 sides.
  22910. * @readonly
  22911. */
  22912. Object.defineProperty(Phaser.Rectangle.prototype, "perimeter", {
  22913. get: function () {
  22914. return (this.width * 2) + (this.height * 2);
  22915. }
  22916. });
  22917. /**
  22918. * The x coordinate of the center of the Rectangle.
  22919. * @name Phaser.Rectangle#centerX
  22920. * @property {number} centerX - The x coordinate of the center of the Rectangle.
  22921. */
  22922. Object.defineProperty(Phaser.Rectangle.prototype, "centerX", {
  22923. get: function () {
  22924. return this.x + this.halfWidth;
  22925. },
  22926. set: function (value) {
  22927. this.x = value - this.halfWidth;
  22928. }
  22929. });
  22930. /**
  22931. * The y coordinate of the center of the Rectangle.
  22932. * @name Phaser.Rectangle#centerY
  22933. * @property {number} centerY - The y coordinate of the center of the Rectangle.
  22934. */
  22935. Object.defineProperty(Phaser.Rectangle.prototype, "centerY", {
  22936. get: function () {
  22937. return this.y + this.halfHeight;
  22938. },
  22939. set: function (value) {
  22940. this.y = value - this.halfHeight;
  22941. }
  22942. });
  22943. /**
  22944. * A random value between the left and right values (inclusive) of the Rectangle.
  22945. *
  22946. * @name Phaser.Rectangle#randomX
  22947. * @property {number} randomX - A random value between the left and right values (inclusive) of the Rectangle.
  22948. */
  22949. Object.defineProperty(Phaser.Rectangle.prototype, "randomX", {
  22950. get: function () {
  22951. return this.x + (Math.random() * this.width);
  22952. }
  22953. });
  22954. /**
  22955. * A random value between the top and bottom values (inclusive) of the Rectangle.
  22956. *
  22957. * @name Phaser.Rectangle#randomY
  22958. * @property {number} randomY - A random value between the top and bottom values (inclusive) of the Rectangle.
  22959. */
  22960. Object.defineProperty(Phaser.Rectangle.prototype, "randomY", {
  22961. get: function () {
  22962. return this.y + (Math.random() * this.height);
  22963. }
  22964. });
  22965. /**
  22966. * 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.
  22967. * However it does affect the height property, whereas changing the y value does not affect the height property.
  22968. * @name Phaser.Rectangle#top
  22969. * @property {number} top - The y coordinate of the top of the Rectangle.
  22970. */
  22971. Object.defineProperty(Phaser.Rectangle.prototype, "top", {
  22972. get: function () {
  22973. return this.y;
  22974. },
  22975. set: function (value) {
  22976. if (value >= this.bottom) {
  22977. this.height = 0;
  22978. this.y = value;
  22979. } else {
  22980. this.height = (this.bottom - value);
  22981. }
  22982. }
  22983. });
  22984. /**
  22985. * The location of the Rectangles top left corner as a Point object.
  22986. * @name Phaser.Rectangle#topLeft
  22987. * @property {Phaser.Point} topLeft - The location of the Rectangles top left corner as a Point object.
  22988. */
  22989. Object.defineProperty(Phaser.Rectangle.prototype, "topLeft", {
  22990. get: function () {
  22991. return new Phaser.Point(this.x, this.y);
  22992. },
  22993. set: function (value) {
  22994. this.x = value.x;
  22995. this.y = value.y;
  22996. }
  22997. });
  22998. /**
  22999. * The location of the Rectangles top right corner as a Point object.
  23000. * @name Phaser.Rectangle#topRight
  23001. * @property {Phaser.Point} topRight - The location of the Rectangles top left corner as a Point object.
  23002. */
  23003. Object.defineProperty(Phaser.Rectangle.prototype, "topRight", {
  23004. get: function () {
  23005. return new Phaser.Point(this.x + this.width, this.y);
  23006. },
  23007. set: function (value) {
  23008. this.right = value.x;
  23009. this.y = value.y;
  23010. }
  23011. });
  23012. /**
  23013. * 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.
  23014. * If set to true then all of the Rectangle properties are set to 0.
  23015. * @name Phaser.Rectangle#empty
  23016. * @property {boolean} empty - Gets or sets the Rectangles empty state.
  23017. */
  23018. Object.defineProperty(Phaser.Rectangle.prototype, "empty", {
  23019. get: function () {
  23020. return (!this.width || !this.height);
  23021. },
  23022. set: function (value) {
  23023. if (value === true)
  23024. {
  23025. this.setTo(0, 0, 0, 0);
  23026. }
  23027. }
  23028. });
  23029. Phaser.Rectangle.prototype.constructor = Phaser.Rectangle;
  23030. /**
  23031. * 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.
  23032. * @method Phaser.Rectangle.inflate
  23033. * @param {Phaser.Rectangle} a - The Rectangle object.
  23034. * @param {number} dx - The amount to be added to the left side of the Rectangle.
  23035. * @param {number} dy - The amount to be added to the bottom side of the Rectangle.
  23036. * @return {Phaser.Rectangle} This Rectangle object.
  23037. */
  23038. Phaser.Rectangle.inflate = function (a, dx, dy) {
  23039. a.x -= dx;
  23040. a.width += 2 * dx;
  23041. a.y -= dy;
  23042. a.height += 2 * dy;
  23043. return a;
  23044. };
  23045. /**
  23046. * 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.
  23047. * @method Phaser.Rectangle.inflatePoint
  23048. * @param {Phaser.Rectangle} a - The Rectangle object.
  23049. * @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.
  23050. * @return {Phaser.Rectangle} The Rectangle object.
  23051. */
  23052. Phaser.Rectangle.inflatePoint = function (a, point) {
  23053. return Phaser.Rectangle.inflate(a, point.x, point.y);
  23054. };
  23055. /**
  23056. * The size of the Rectangle object, expressed as a Point object with the values of the width and height properties.
  23057. * @method Phaser.Rectangle.size
  23058. * @param {Phaser.Rectangle} a - The Rectangle object.
  23059. * @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.
  23060. * @return {Phaser.Point} The size of the Rectangle object
  23061. */
  23062. Phaser.Rectangle.size = function (a, output) {
  23063. if (output === undefined || output === null)
  23064. {
  23065. output = new Phaser.Point(a.width, a.height);
  23066. }
  23067. else
  23068. {
  23069. output.setTo(a.width, a.height);
  23070. }
  23071. return output;
  23072. };
  23073. /**
  23074. * Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object.
  23075. * @method Phaser.Rectangle.clone
  23076. * @param {Phaser.Rectangle} a - The Rectangle object.
  23077. * @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.
  23078. * @return {Phaser.Rectangle}
  23079. */
  23080. Phaser.Rectangle.clone = function (a, output) {
  23081. if (output === undefined || output === null)
  23082. {
  23083. output = new Phaser.Rectangle(a.x, a.y, a.width, a.height);
  23084. }
  23085. else
  23086. {
  23087. output.setTo(a.x, a.y, a.width, a.height);
  23088. }
  23089. return output;
  23090. };
  23091. /**
  23092. * Determines whether the specified coordinates are contained within the region defined by this Rectangle object.
  23093. * @method Phaser.Rectangle.contains
  23094. * @param {Phaser.Rectangle} a - The Rectangle object.
  23095. * @param {number} x - The x coordinate of the point to test.
  23096. * @param {number} y - The y coordinate of the point to test.
  23097. * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
  23098. */
  23099. Phaser.Rectangle.contains = function (a, x, y) {
  23100. if (a.width <= 0 || a.height <= 0)
  23101. {
  23102. return false;
  23103. }
  23104. return (x >= a.x && x < a.right && y >= a.y && y < a.bottom);
  23105. };
  23106. /**
  23107. * Determines whether the specified coordinates are contained within the region defined by the given raw values.
  23108. * @method Phaser.Rectangle.containsRaw
  23109. * @param {number} rx - The x coordinate of the top left of the area.
  23110. * @param {number} ry - The y coordinate of the top left of the area.
  23111. * @param {number} rw - The width of the area.
  23112. * @param {number} rh - The height of the area.
  23113. * @param {number} x - The x coordinate of the point to test.
  23114. * @param {number} y - The y coordinate of the point to test.
  23115. * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
  23116. */
  23117. Phaser.Rectangle.containsRaw = function (rx, ry, rw, rh, x, y) {
  23118. return (x >= rx && x < (rx + rw) && y >= ry && y < (ry + rh));
  23119. };
  23120. /**
  23121. * 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.
  23122. * @method Phaser.Rectangle.containsPoint
  23123. * @param {Phaser.Rectangle} a - The Rectangle object.
  23124. * @param {Phaser.Point} point - The point object being checked. Can be Point or any object with .x and .y values.
  23125. * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
  23126. */
  23127. Phaser.Rectangle.containsPoint = function (a, point) {
  23128. return Phaser.Rectangle.contains(a, point.x, point.y);
  23129. };
  23130. /**
  23131. * Determines whether the first Rectangle object is fully contained within the second Rectangle object.
  23132. * A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first.
  23133. * @method Phaser.Rectangle.containsRect
  23134. * @param {Phaser.Rectangle} a - The first Rectangle object.
  23135. * @param {Phaser.Rectangle} b - The second Rectangle object.
  23136. * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
  23137. */
  23138. Phaser.Rectangle.containsRect = function (a, b) {
  23139. // If the given rect has a larger volume than this one then it can never contain it
  23140. if (a.volume > b.volume)
  23141. {
  23142. return false;
  23143. }
  23144. return (a.x >= b.x && a.y >= b.y && a.right < b.right && a.bottom < b.bottom);
  23145. };
  23146. /**
  23147. * Determines whether the two Rectangles are equal.
  23148. * This method compares the x, y, width and height properties of each Rectangle.
  23149. * @method Phaser.Rectangle.equals
  23150. * @param {Phaser.Rectangle} a - The first Rectangle object.
  23151. * @param {Phaser.Rectangle} b - The second Rectangle object.
  23152. * @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.
  23153. */
  23154. Phaser.Rectangle.equals = function (a, b) {
  23155. return (a.x == b.x && a.y == b.y && a.width == b.width && a.height == b.height);
  23156. };
  23157. /**
  23158. * Determines if the two objects (either Rectangles or Rectangle-like) have the same width and height values under strict equality.
  23159. * @method Phaser.Rectangle.sameDimensions
  23160. * @param {Rectangle-like} a - The first Rectangle object.
  23161. * @param {Rectangle-like} b - The second Rectangle object.
  23162. * @return {boolean} True if the object have equivalent values for the width and height properties.
  23163. */
  23164. Phaser.Rectangle.sameDimensions = function (a, b) {
  23165. return (a.width === b.width && a.height === b.height);
  23166. };
  23167. /**
  23168. * 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.
  23169. * @method Phaser.Rectangle.intersection
  23170. * @param {Phaser.Rectangle} a - The first Rectangle object.
  23171. * @param {Phaser.Rectangle} b - The second Rectangle object.
  23172. * @param {Phaser.Rectangle} [output] - 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.
  23173. * @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.
  23174. */
  23175. Phaser.Rectangle.intersection = function (a, b, output) {
  23176. if (output === undefined)
  23177. {
  23178. output = new Phaser.Rectangle();
  23179. }
  23180. if (Phaser.Rectangle.intersects(a, b))
  23181. {
  23182. output.x = Math.max(a.x, b.x);
  23183. output.y = Math.max(a.y, b.y);
  23184. output.width = Math.min(a.right, b.right) - output.x;
  23185. output.height = Math.min(a.bottom, b.bottom) - output.y;
  23186. }
  23187. return output;
  23188. };
  23189. /**
  23190. * Determines whether the two Rectangles intersect with each other.
  23191. * This method checks the x, y, width, and height properties of the Rectangles.
  23192. * @method Phaser.Rectangle.intersects
  23193. * @param {Phaser.Rectangle} a - The first Rectangle object.
  23194. * @param {Phaser.Rectangle} b - The second Rectangle object.
  23195. * @return {boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false.
  23196. */
  23197. Phaser.Rectangle.intersects = function (a, b) {
  23198. if (a.width <= 0 || a.height <= 0 || b.width <= 0 || b.height <= 0)
  23199. {
  23200. return false;
  23201. }
  23202. return !(a.right < b.x || a.bottom < b.y || a.x > b.right || a.y > b.bottom);
  23203. };
  23204. /**
  23205. * Determines whether the object specified intersects (overlaps) with the given values.
  23206. * @method Phaser.Rectangle.intersectsRaw
  23207. * @param {number} left - The x coordinate of the left of the area.
  23208. * @param {number} right - The right coordinate of the area.
  23209. * @param {number} top - The y coordinate of the area.
  23210. * @param {number} bottom - The bottom coordinate of the area.
  23211. * @param {number} tolerance - A tolerance value to allow for an intersection test with padding, default to 0
  23212. * @return {boolean} A value of true if the specified object intersects with the Rectangle; otherwise false.
  23213. */
  23214. Phaser.Rectangle.intersectsRaw = function (a, left, right, top, bottom, tolerance) {
  23215. if (tolerance === undefined) { tolerance = 0; }
  23216. return !(left > a.right + tolerance || right < a.left - tolerance || top > a.bottom + tolerance || bottom < a.top - tolerance);
  23217. };
  23218. /**
  23219. * Adds two Rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two Rectangles.
  23220. * @method Phaser.Rectangle.union
  23221. * @param {Phaser.Rectangle} a - The first Rectangle object.
  23222. * @param {Phaser.Rectangle} b - The second Rectangle object.
  23223. * @param {Phaser.Rectangle} [output] - 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.
  23224. * @return {Phaser.Rectangle} A Rectangle object that is the union of the two Rectangles.
  23225. */
  23226. Phaser.Rectangle.union = function (a, b, output) {
  23227. if (output === undefined)
  23228. {
  23229. output = new Phaser.Rectangle();
  23230. }
  23231. return output.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));
  23232. };
  23233. /**
  23234. * Calculates the Axis Aligned Bounding Box (or aabb) from an array of points.
  23235. *
  23236. * @method Phaser.Rectangle#aabb
  23237. * @param {Phaser.Point[]} points - The array of one or more points.
  23238. * @param {Phaser.Rectangle} [out] - Optional Rectangle to store the value in, if not supplied a new Rectangle object will be created.
  23239. * @return {Phaser.Rectangle} The new Rectangle object.
  23240. * @static
  23241. */
  23242. Phaser.Rectangle.aabb = function(points, out) {
  23243. if (out === undefined) {
  23244. out = new Phaser.Rectangle();
  23245. }
  23246. var xMax = Number.MIN_VALUE,
  23247. xMin = Number.MAX_VALUE,
  23248. yMax = Number.MIN_VALUE,
  23249. yMin = Number.MAX_VALUE;
  23250. points.forEach(function(point) {
  23251. if (point.x > xMax) {
  23252. xMax = point.x;
  23253. }
  23254. if (point.x < xMin) {
  23255. xMin = point.x;
  23256. }
  23257. if (point.y > yMax) {
  23258. yMax = point.y;
  23259. }
  23260. if (point.y < yMin) {
  23261. yMin = point.y;
  23262. }
  23263. });
  23264. out.setTo(xMin, yMin, xMax - xMin, yMax - yMin);
  23265. return out;
  23266. };
  23267. // Because PIXI uses its own Rectangle, we'll replace it with ours to avoid duplicating code or confusion.
  23268. PIXI.Rectangle = Phaser.Rectangle;
  23269. PIXI.EmptyRectangle = new Phaser.Rectangle(0, 0, 0, 0);
  23270. /**
  23271. * @author Mat Groves http://matgroves.com/
  23272. * @author Richard Davey <rich@photonstorm.com>
  23273. * @copyright 2016 Photon Storm Ltd.
  23274. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  23275. */
  23276. /**
  23277. * The Rounded Rectangle object is an area defined by its position and has nice rounded corners,
  23278. * as indicated by its top-left corner point (x, y) and by its width and its height.
  23279. *
  23280. * @class Phaser.RoundedRectangle
  23281. * @constructor
  23282. * @param {number} [x=0] - The x coordinate of the top-left corner of the Rectangle.
  23283. * @param {number} [y=0] - The y coordinate of the top-left corner of the Rectangle.
  23284. * @param {number} [width=0] - The width of the Rectangle. Should always be either zero or a positive value.
  23285. * @param {number} [height=0] - The height of the Rectangle. Should always be either zero or a positive value.
  23286. * @param {number} [radius=20] - Controls the radius of the rounded corners.
  23287. */
  23288. Phaser.RoundedRectangle = function(x, y, width, height, radius)
  23289. {
  23290. if (x === undefined) { x = 0; }
  23291. if (y === undefined) { y = 0; }
  23292. if (width === undefined) { width = 0; }
  23293. if (height === undefined) { height = 0; }
  23294. if (radius === undefined) { radius = 20; }
  23295. /**
  23296. * @property {number} x - The x coordinate of the top-left corner of the Rectangle.
  23297. */
  23298. this.x = x;
  23299. /**
  23300. * @property {number} y - The y coordinate of the top-left corner of the Rectangle.
  23301. */
  23302. this.y = y;
  23303. /**
  23304. * @property {number} width - The width of the Rectangle. This value should never be set to a negative.
  23305. */
  23306. this.width = width;
  23307. /**
  23308. * @property {number} height - The height of the Rectangle. This value should never be set to a negative.
  23309. */
  23310. this.height = height;
  23311. /**
  23312. * @property {number} radius - The radius of the rounded corners.
  23313. */
  23314. this.radius = radius || 20;
  23315. /**
  23316. * @property {number} type - The const type of this object.
  23317. * @readonly
  23318. */
  23319. this.type = Phaser.ROUNDEDRECTANGLE;
  23320. };
  23321. Phaser.RoundedRectangle.prototype = {
  23322. /**
  23323. * Returns a new RoundedRectangle object with the same values for the x, y, width, height and
  23324. * radius properties as this RoundedRectangle object.
  23325. *
  23326. * @method Phaser.RoundedRectangle#clone
  23327. * @return {Phaser.RoundedRectangle}
  23328. */
  23329. clone: function () {
  23330. return new Phaser.RoundedRectangle(this.x, this.y, this.width, this.height, this.radius);
  23331. },
  23332. /**
  23333. * Determines whether the specified coordinates are contained within the region defined by this Rounded Rectangle object.
  23334. *
  23335. * @method Phaser.RoundedRectangle#contains
  23336. * @param {number} x - The x coordinate of the point to test.
  23337. * @param {number} y - The y coordinate of the point to test.
  23338. * @return {boolean} A value of true if the RoundedRectangle Rectangle object contains the specified point; otherwise false.
  23339. */
  23340. contains: function (x, y) {
  23341. if (this.width <= 0 || this.height <= 0)
  23342. {
  23343. return false;
  23344. }
  23345. var x1 = this.x;
  23346. if (x >= x1 && x <= x1 + this.width)
  23347. {
  23348. var y1 = this.y;
  23349. if (y >= y1 && y <= y1 + this.height)
  23350. {
  23351. return true;
  23352. }
  23353. }
  23354. return false;
  23355. }
  23356. };
  23357. Phaser.RoundedRectangle.prototype.constructor = Phaser.RoundedRectangle;
  23358. // Because PIXI uses its own type, we'll replace it with ours to avoid duplicating code or confusion.
  23359. PIXI.RoundedRectangle = Phaser.RoundedRectangle;
  23360. /**
  23361. * @author Richard Davey <rich@photonstorm.com>
  23362. * @copyright 2016 Photon Storm Ltd.
  23363. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  23364. */
  23365. /**
  23366. * 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.
  23367. * The game automatically creates a single Stage sized camera on boot. Move the camera around the world with Phaser.Camera.x/y
  23368. *
  23369. * @class Phaser.Camera
  23370. * @constructor
  23371. * @param {Phaser.Game} game - Game reference to the currently running game.
  23372. * @param {number} id - Not being used at the moment, will be when Phaser supports multiple camera
  23373. * @param {number} x - Position of the camera on the X axis
  23374. * @param {number} y - Position of the camera on the Y axis
  23375. * @param {number} width - The width of the view rectangle
  23376. * @param {number} height - The height of the view rectangle
  23377. */
  23378. Phaser.Camera = function (game, id, x, y, width, height) {
  23379. /**
  23380. * @property {Phaser.Game} game - A reference to the currently running Game.
  23381. */
  23382. this.game = game;
  23383. /**
  23384. * @property {Phaser.World} world - A reference to the game world.
  23385. */
  23386. this.world = game.world;
  23387. /**
  23388. * @property {number} id - Reserved for future multiple camera set-ups.
  23389. * @default
  23390. */
  23391. this.id = 0;
  23392. /**
  23393. * Camera view.
  23394. * The view into the world we wish to render (by default the game dimensions).
  23395. * The x/y values are in world coordinates, not screen coordinates, the width/height is how many pixels to render.
  23396. * Sprites outside of this view are not rendered if Sprite.autoCull is set to `true`. Otherwise they are always rendered.
  23397. * @property {Phaser.Rectangle} view
  23398. */
  23399. this.view = new Phaser.Rectangle(x, y, width, height);
  23400. /**
  23401. * 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.
  23402. * 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
  23403. * at all then set this to null. The values can be anything and are in World coordinates, with 0,0 being the top-left of the world.
  23404. *
  23405. * @property {Phaser.Rectangle} bounds - The Rectangle in which the Camera is bounded. Set to null to allow for movement anywhere.
  23406. */
  23407. this.bounds = new Phaser.Rectangle(x, y, width, height);
  23408. /**
  23409. * @property {Phaser.Rectangle} deadzone - Moving inside this Rectangle will not cause the camera to move.
  23410. */
  23411. this.deadzone = null;
  23412. /**
  23413. * @property {boolean} visible - Whether this camera is visible or not.
  23414. * @default
  23415. */
  23416. this.visible = true;
  23417. /**
  23418. * @property {boolean} roundPx - If a Camera has roundPx set to `true` it will call `view.floor` as part of its update loop, keeping its boundary to integer values. Set this to `false` to disable this from happening.
  23419. * @default
  23420. */
  23421. this.roundPx = true;
  23422. /**
  23423. * @property {boolean} atLimit - Whether this camera is flush with the World Bounds or not.
  23424. */
  23425. this.atLimit = { x: false, y: false };
  23426. /**
  23427. * @property {Phaser.Sprite} target - If the camera is tracking a Sprite, this is a reference to it, otherwise null.
  23428. * @default
  23429. */
  23430. this.target = null;
  23431. /**
  23432. * @property {PIXI.DisplayObject} displayObject - The display object to which all game objects are added. Set by World.boot.
  23433. */
  23434. this.displayObject = null;
  23435. /**
  23436. * @property {Phaser.Point} scale - The scale of the display object to which all game objects are added. Set by World.boot.
  23437. */
  23438. this.scale = null;
  23439. /**
  23440. * @property {number} totalInView - The total number of Sprites with `autoCull` set to `true` that are visible by this Camera.
  23441. * @readonly
  23442. */
  23443. this.totalInView = 0;
  23444. /**
  23445. * The linear interpolation value to use when following a target.
  23446. * The default values of 1 means the camera will instantly snap to the target coordinates.
  23447. * A lower value, such as 0.1 means the camera will more slowly track the target, giving
  23448. * a smooth transition. You can set the horizontal and vertical values independently, and also
  23449. * adjust this value in real-time during your game.
  23450. * @property {Phaser.Point} lerp
  23451. * @default
  23452. */
  23453. this.lerp = new Phaser.Point(1, 1);
  23454. /**
  23455. * @property {Phaser.Signal} onShakeComplete - This signal is dispatched when the camera shake effect completes.
  23456. */
  23457. this.onShakeComplete = new Phaser.Signal();
  23458. /**
  23459. * @property {Phaser.Signal} onFlashComplete - This signal is dispatched when the camera flash effect completes.
  23460. */
  23461. this.onFlashComplete = new Phaser.Signal();
  23462. /**
  23463. * This signal is dispatched when the camera fade effect completes.
  23464. * When the fade effect completes you will be left with the screen black (or whatever
  23465. * color you faded to). In order to reset this call `Camera.resetFX`. This is called
  23466. * automatically when you change State.
  23467. * @property {Phaser.Signal} onFadeComplete
  23468. */
  23469. this.onFadeComplete = new Phaser.Signal();
  23470. /**
  23471. * The Graphics object used to handle camera fx such as fade and flash.
  23472. * @property {Phaser.Graphics} fx
  23473. * @protected
  23474. */
  23475. this.fx = null;
  23476. /**
  23477. * @property {Phaser.Point} _targetPosition - Internal point used to calculate target position.
  23478. * @private
  23479. */
  23480. this._targetPosition = new Phaser.Point();
  23481. /**
  23482. * @property {number} edge - Edge property.
  23483. * @private
  23484. * @default
  23485. */
  23486. this._edge = 0;
  23487. /**
  23488. * @property {Phaser.Point} position - Current position of the camera in world.
  23489. * @private
  23490. * @default
  23491. */
  23492. this._position = new Phaser.Point();
  23493. /**
  23494. * @property {Object} _shake - The shake effect container.
  23495. * @private
  23496. */
  23497. this._shake = {
  23498. intensity: 0,
  23499. duration: 0,
  23500. horizontal: false,
  23501. vertical: false,
  23502. shakeBounds: true,
  23503. x: 0,
  23504. y: 0
  23505. };
  23506. /**
  23507. * @property {number} _fxDuration - FX duration timer.
  23508. * @private
  23509. */
  23510. this._fxDuration = 0;
  23511. /**
  23512. * @property {number} _fxType - The FX type running.
  23513. * @private
  23514. */
  23515. this._fxType = 0;
  23516. };
  23517. /**
  23518. * @constant
  23519. * @type {number}
  23520. */
  23521. Phaser.Camera.FOLLOW_LOCKON = 0;
  23522. /**
  23523. * @constant
  23524. * @type {number}
  23525. */
  23526. Phaser.Camera.FOLLOW_PLATFORMER = 1;
  23527. /**
  23528. * @constant
  23529. * @type {number}
  23530. */
  23531. Phaser.Camera.FOLLOW_TOPDOWN = 2;
  23532. /**
  23533. * @constant
  23534. * @type {number}
  23535. */
  23536. Phaser.Camera.FOLLOW_TOPDOWN_TIGHT = 3;
  23537. /**
  23538. * @constant
  23539. * @type {number}
  23540. */
  23541. Phaser.Camera.SHAKE_BOTH = 4;
  23542. /**
  23543. * @constant
  23544. * @type {number}
  23545. */
  23546. Phaser.Camera.SHAKE_HORIZONTAL = 5;
  23547. /**
  23548. * @constant
  23549. * @type {number}
  23550. */
  23551. Phaser.Camera.SHAKE_VERTICAL = 6;
  23552. /**
  23553. * @constant
  23554. * @type {boolean}
  23555. */
  23556. Phaser.Camera.ENABLE_FX = true;
  23557. Phaser.Camera.prototype = {
  23558. /**
  23559. * Called automatically by Phaser.World.
  23560. *
  23561. * @method Phaser.Camera#boot
  23562. * @private
  23563. */
  23564. boot: function () {
  23565. this.displayObject = this.game.world;
  23566. this.scale = this.game.world.scale;
  23567. this.game.camera = this;
  23568. if (Phaser.Graphics && Phaser.Camera.ENABLE_FX)
  23569. {
  23570. this.fx = new Phaser.Graphics(this.game);
  23571. this.game.stage.addChild(this.fx);
  23572. }
  23573. },
  23574. /**
  23575. * Camera preUpdate. Sets the total view counter to zero.
  23576. *
  23577. * @method Phaser.Camera#preUpdate
  23578. */
  23579. preUpdate: function () {
  23580. this.totalInView = 0;
  23581. },
  23582. /**
  23583. * Tell the camera which sprite to follow.
  23584. *
  23585. * You can set the follow type and a linear interpolation value.
  23586. * Use low lerp values (such as 0.1) to automatically smooth the camera motion.
  23587. *
  23588. * If you find you're getting a slight "jitter" effect when following a Sprite it's probably to do with sub-pixel rendering of the Sprite position.
  23589. * This can be disabled by setting `game.renderer.renderSession.roundPixels = true` to force full pixel rendering.
  23590. *
  23591. * @method Phaser.Camera#follow
  23592. * @param {Phaser.Sprite|Phaser.Image|Phaser.Text} target - The object you want the camera to track. Set to null to not follow anything.
  23593. * @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().
  23594. * @param {float} [lerpX=1] - A value between 0 and 1. This value specifies the amount of linear interpolation to use when horizontally tracking the target. The closer the value to 1, the faster the camera will track.
  23595. * @param {float} [lerpY=1] - A value between 0 and 1. This value specifies the amount of linear interpolation to use when vertically tracking the target. The closer the value to 1, the faster the camera will track.
  23596. */
  23597. follow: function (target, style, lerpX, lerpY) {
  23598. if (style === undefined) { style = Phaser.Camera.FOLLOW_LOCKON; }
  23599. if (lerpX === undefined) { lerpX = 1; }
  23600. if (lerpY === undefined) { lerpY = 1; }
  23601. this.target = target;
  23602. this.lerp.set(lerpX, lerpY);
  23603. var helper;
  23604. switch (style) {
  23605. case Phaser.Camera.FOLLOW_PLATFORMER:
  23606. var w = this.width / 8;
  23607. var h = this.height / 3;
  23608. this.deadzone = new Phaser.Rectangle((this.width - w) / 2, (this.height - h) / 2 - h * 0.25, w, h);
  23609. break;
  23610. case Phaser.Camera.FOLLOW_TOPDOWN:
  23611. helper = Math.max(this.width, this.height) / 4;
  23612. this.deadzone = new Phaser.Rectangle((this.width - helper) / 2, (this.height - helper) / 2, helper, helper);
  23613. break;
  23614. case Phaser.Camera.FOLLOW_TOPDOWN_TIGHT:
  23615. helper = Math.max(this.width, this.height) / 8;
  23616. this.deadzone = new Phaser.Rectangle((this.width - helper) / 2, (this.height - helper) / 2, helper, helper);
  23617. break;
  23618. case Phaser.Camera.FOLLOW_LOCKON:
  23619. this.deadzone = null;
  23620. break;
  23621. default:
  23622. this.deadzone = null;
  23623. break;
  23624. }
  23625. },
  23626. /**
  23627. * Sets the Camera follow target to null, stopping it from following an object if it's doing so.
  23628. *
  23629. * @method Phaser.Camera#unfollow
  23630. */
  23631. unfollow: function () {
  23632. this.target = null;
  23633. },
  23634. /**
  23635. * Move the camera focus on a display object instantly.
  23636. * @method Phaser.Camera#focusOn
  23637. * @param {any} displayObject - The display object to focus the camera on. Must have visible x/y properties.
  23638. */
  23639. focusOn: function (displayObject) {
  23640. this.setPosition(Math.round(displayObject.x - this.view.halfWidth), Math.round(displayObject.y - this.view.halfHeight));
  23641. },
  23642. /**
  23643. * Move the camera focus on a location instantly.
  23644. * @method Phaser.Camera#focusOnXY
  23645. * @param {number} x - X position.
  23646. * @param {number} y - Y position.
  23647. */
  23648. focusOnXY: function (x, y) {
  23649. this.setPosition(Math.round(x - this.view.halfWidth), Math.round(y - this.view.halfHeight));
  23650. },
  23651. /**
  23652. * This creates a camera shake effect. It works by applying a random amount of additional
  23653. * spacing on the x and y axis each frame. You can control the intensity and duration
  23654. * of the effect, and if it should effect both axis or just one.
  23655. *
  23656. * When the shake effect ends the signal Camera.onShakeComplete is dispatched.
  23657. *
  23658. * @method Phaser.Camera#shake
  23659. * @param {float} [intensity=0.05] - The intensity of the camera shake. Given as a percentage of the camera size representing the maximum distance that the camera can move while shaking.
  23660. * @param {number} [duration=500] - The duration of the shake effect in milliseconds.
  23661. * @param {boolean} [force=true] - If a camera shake effect is already running and force is true it will replace the previous effect, resetting the duration.
  23662. * @param {number} [direction=Phaser.Camera.SHAKE_BOTH] - The directions in which the camera can shake. Either Phaser.Camera.SHAKE_BOTH, Phaser.Camera.SHAKE_HORIZONTAL or Phaser.Camera.SHAKE_VERTICAL.
  23663. * @param {boolean} [shakeBounds=true] - Is the effect allowed to shake the camera beyond its bounds (if set?).
  23664. * @return {boolean} True if the shake effect was started, otherwise false.
  23665. */
  23666. shake: function (intensity, duration, force, direction, shakeBounds) {
  23667. if (intensity === undefined) { intensity = 0.05; }
  23668. if (duration === undefined) { duration = 500; }
  23669. if (force === undefined) { force = true; }
  23670. if (direction === undefined) { direction = Phaser.Camera.SHAKE_BOTH; }
  23671. if (shakeBounds === undefined) { shakeBounds = true; }
  23672. if (!force && this._shake.duration > 0)
  23673. {
  23674. // Can't reset an already running shake
  23675. return false;
  23676. }
  23677. this._shake.intensity = intensity;
  23678. this._shake.duration = duration;
  23679. this._shake.shakeBounds = shakeBounds;
  23680. this._shake.x = 0;
  23681. this._shake.y = 0;
  23682. this._shake.horizontal = (direction === Phaser.Camera.SHAKE_BOTH || direction === Phaser.Camera.SHAKE_HORIZONTAL);
  23683. this._shake.vertical = (direction === Phaser.Camera.SHAKE_BOTH || direction === Phaser.Camera.SHAKE_VERTICAL);
  23684. return true;
  23685. },
  23686. /**
  23687. * This creates a camera flash effect. It works by filling the game with the solid fill
  23688. * color specified, and then fading it away to alpha 0 over the duration given.
  23689. *
  23690. * You can use this for things such as hit feedback effects.
  23691. *
  23692. * When the effect ends the signal Camera.onFlashComplete is dispatched.
  23693. *
  23694. * @method Phaser.Camera#flash
  23695. * @param {numer} [color=0xffffff] - The color of the flash effect. I.e. 0xffffff for white, 0xff0000 for red, etc.
  23696. * @param {number} [duration=500] - The duration of the flash effect in milliseconds.
  23697. * @param {boolean} [force=false] - If a camera flash or fade effect is already running and force is true it will replace the previous effect, resetting the duration.
  23698. * @return {boolean} True if the effect was started, otherwise false.
  23699. */
  23700. flash: function (color, duration, force) {
  23701. if (color === undefined) { color = 0xffffff; }
  23702. if (duration === undefined) { duration = 500; }
  23703. if (force === undefined) { force = false; }
  23704. if (!this.fx || (!force && this._fxDuration > 0))
  23705. {
  23706. return false;
  23707. }
  23708. this.fx.clear();
  23709. this.fx.beginFill(color);
  23710. this.fx.drawRect(0, 0, this.width, this.height);
  23711. this.fx.endFill();
  23712. this.fx.alpha = 1;
  23713. this._fxDuration = duration;
  23714. this._fxType = 0;
  23715. return true;
  23716. },
  23717. /**
  23718. * This creates a camera fade effect. It works by filling the game with the
  23719. * color specified, over the duration given, ending with a solid fill.
  23720. *
  23721. * You can use this for things such as transitioning to a new scene.
  23722. *
  23723. * The game will be left 'filled' at the end of this effect, likely obscuring
  23724. * everything. In order to reset it you can call `Camera.resetFX` and it will clear the
  23725. * fade. Or you can call `Camera.flash` with the same color as the fade, and it will
  23726. * reverse the process, bringing the game back into view again.
  23727. *
  23728. * When the effect ends the signal Camera.onFadeComplete is dispatched.
  23729. *
  23730. * @method Phaser.Camera#fade
  23731. * @param {numer} [color=0x000000] - The color the game will fade to. I.e. 0x000000 for black, 0xff0000 for red, etc.
  23732. * @param {number} [duration=500] - The duration of the fade in milliseconds.
  23733. * @param {boolean} [force=false] - If a camera flash or fade effect is already running and force is true it will replace the previous effect, resetting the duration.
  23734. * @return {boolean} True if the effect was started, otherwise false.
  23735. */
  23736. fade: function (color, duration, force) {
  23737. if (color === undefined) { color = 0x000000; }
  23738. if (duration === undefined) { duration = 500; }
  23739. if (force === undefined) { force = false; }
  23740. if (!this.fx || (!force && this._fxDuration > 0))
  23741. {
  23742. return false;
  23743. }
  23744. this.fx.clear();
  23745. this.fx.beginFill(color);
  23746. this.fx.drawRect(0, 0, this.width, this.height);
  23747. this.fx.endFill();
  23748. this.fx.alpha = 0;
  23749. this._fxDuration = duration;
  23750. this._fxType = 1;
  23751. return true;
  23752. },
  23753. /**
  23754. * The camera update loop. This is called automatically by the core game loop.
  23755. *
  23756. * @method Phaser.Camera#update
  23757. * @protected
  23758. */
  23759. update: function () {
  23760. if (this._fxDuration > 0)
  23761. {
  23762. this.updateFX();
  23763. }
  23764. if (this.target)
  23765. {
  23766. this.updateTarget();
  23767. }
  23768. if (this._shake.duration > 0)
  23769. {
  23770. this.updateShake();
  23771. }
  23772. if (this.bounds)
  23773. {
  23774. this.checkBounds();
  23775. }
  23776. if (this.roundPx)
  23777. {
  23778. this.view.floor();
  23779. this._shake.x = Math.floor(this._shake.x);
  23780. this._shake.y = Math.floor(this._shake.y);
  23781. }
  23782. // this.displayObject.position.x = -(this.view.x + this._shake.x);
  23783. // this.displayObject.position.y = -(this.view.y + this._shake.y);
  23784. this.displayObject.position.x = -this.view.x;
  23785. this.displayObject.position.y = -this.view.y;
  23786. },
  23787. /**
  23788. * Update the camera flash and fade effects.
  23789. *
  23790. * @method Phaser.Camera#updateFX
  23791. * @private
  23792. */
  23793. updateFX: function () {
  23794. if (this._fxType === 0)
  23795. {
  23796. // flash
  23797. this.fx.alpha -= this.game.time.elapsedMS / this._fxDuration;
  23798. if (this.fx.alpha <= 0)
  23799. {
  23800. this._fxDuration = 0;
  23801. this.fx.alpha = 0;
  23802. this.onFlashComplete.dispatch();
  23803. }
  23804. }
  23805. else
  23806. {
  23807. // fade
  23808. this.fx.alpha += this.game.time.elapsedMS / this._fxDuration;
  23809. if (this.fx.alpha >= 1)
  23810. {
  23811. this._fxDuration = 0;
  23812. this.fx.alpha = 1;
  23813. this.onFadeComplete.dispatch();
  23814. }
  23815. }
  23816. },
  23817. /**
  23818. * Update the camera shake effect.
  23819. *
  23820. * @method Phaser.Camera#updateShake
  23821. * @private
  23822. */
  23823. updateShake: function () {
  23824. this._shake.duration -= this.game.time.elapsedMS;
  23825. if (this._shake.duration <= 0)
  23826. {
  23827. this.onShakeComplete.dispatch();
  23828. this._shake.x = 0;
  23829. this._shake.y = 0;
  23830. }
  23831. else
  23832. {
  23833. if (this._shake.horizontal)
  23834. {
  23835. this._shake.x = this.game.rnd.frac() * this._shake.intensity * this.view.width * 2 - this._shake.intensity * this.view.width;
  23836. }
  23837. if (this._shake.vertical)
  23838. {
  23839. this._shake.y = this.game.rnd.frac() * this._shake.intensity * this.view.height * 2 - this._shake.intensity * this.view.height;
  23840. }
  23841. }
  23842. },
  23843. /**
  23844. * Internal method that handles tracking a sprite.
  23845. *
  23846. * @method Phaser.Camera#updateTarget
  23847. * @private
  23848. */
  23849. updateTarget: function () {
  23850. this._targetPosition.copyFrom(this.target.world);
  23851. if (this.deadzone)
  23852. {
  23853. this._edge = this._targetPosition.x - this.view.x;
  23854. if (this._edge < this.deadzone.left)
  23855. {
  23856. this.view.x = this.game.math.linear(this.view.x, this._targetPosition.x - this.deadzone.left, this.lerp.x);
  23857. }
  23858. else if (this._edge > this.deadzone.right)
  23859. {
  23860. this.view.x = this.game.math.linear(this.view.x, this._targetPosition.x - this.deadzone.right, this.lerp.x);
  23861. }
  23862. this._edge = this._targetPosition.y - this.view.y;
  23863. if (this._edge < this.deadzone.top)
  23864. {
  23865. this.view.y = this.game.math.linear(this.view.y, this._targetPosition.y - this.deadzone.top, this.lerp.y);
  23866. }
  23867. else if (this._edge > this.deadzone.bottom)
  23868. {
  23869. this.view.y = this.game.math.linear(this.view.y, this._targetPosition.y - this.deadzone.bottom, this.lerp.y);
  23870. }
  23871. }
  23872. else
  23873. {
  23874. this.view.x = this.game.math.linear(this.view.x, this._targetPosition.x - this.view.halfWidth, this.lerp.x);
  23875. this.view.y = this.game.math.linear(this.view.y, this._targetPosition.y - this.view.halfHeight, this.lerp.y);
  23876. }
  23877. },
  23878. /**
  23879. * Update the Camera bounds to match the game world.
  23880. *
  23881. * @method Phaser.Camera#setBoundsToWorld
  23882. */
  23883. setBoundsToWorld: function () {
  23884. if (this.bounds)
  23885. {
  23886. this.bounds.copyFrom(this.game.world.bounds);
  23887. }
  23888. },
  23889. /**
  23890. * Method called to ensure the camera doesn't venture outside of the game world.
  23891. * Called automatically by Camera.update.
  23892. *
  23893. * @method Phaser.Camera#checkBounds
  23894. * @protected
  23895. */
  23896. checkBounds: function () {
  23897. this.atLimit.x = false;
  23898. this.atLimit.y = false;
  23899. var vx = this.view.x + this._shake.x;
  23900. var vw = this.view.right + this._shake.x;
  23901. var vy = this.view.y + this._shake.y;
  23902. var vh = this.view.bottom + this._shake.y;
  23903. // Make sure we didn't go outside the cameras bounds
  23904. if (vx <= this.bounds.x * this.scale.x)
  23905. {
  23906. this.atLimit.x = true;
  23907. this.view.x = this.bounds.x * this.scale.x;
  23908. if (!this._shake.shakeBounds)
  23909. {
  23910. // The camera is up against the bounds, so reset the shake
  23911. this._shake.x = 0;
  23912. }
  23913. }
  23914. if (vw >= this.bounds.right * this.scale.x)
  23915. {
  23916. this.atLimit.x = true;
  23917. this.view.x = (this.bounds.right * this.scale.x) - this.width;
  23918. if (!this._shake.shakeBounds)
  23919. {
  23920. // The camera is up against the bounds, so reset the shake
  23921. this._shake.x = 0;
  23922. }
  23923. }
  23924. if (vy <= this.bounds.top * this.scale.y)
  23925. {
  23926. this.atLimit.y = true;
  23927. this.view.y = this.bounds.top * this.scale.y;
  23928. if (!this._shake.shakeBounds)
  23929. {
  23930. // The camera is up against the bounds, so reset the shake
  23931. this._shake.y = 0;
  23932. }
  23933. }
  23934. if (vh >= this.bounds.bottom * this.scale.y)
  23935. {
  23936. this.atLimit.y = true;
  23937. this.view.y = (this.bounds.bottom * this.scale.y) - this.height;
  23938. if (!this._shake.shakeBounds)
  23939. {
  23940. // The camera is up against the bounds, so reset the shake
  23941. this._shake.y = 0;
  23942. }
  23943. }
  23944. },
  23945. /**
  23946. * A helper function to set both the X and Y properties of the camera at once
  23947. * without having to use game.camera.x and game.camera.y.
  23948. *
  23949. * @method Phaser.Camera#setPosition
  23950. * @param {number} x - X position.
  23951. * @param {number} y - Y position.
  23952. */
  23953. setPosition: function (x, y) {
  23954. this.view.x = x;
  23955. this.view.y = y;
  23956. if (this.bounds)
  23957. {
  23958. this.checkBounds();
  23959. }
  23960. },
  23961. /**
  23962. * Sets the size of the view rectangle given the width and height in parameters.
  23963. *
  23964. * @method Phaser.Camera#setSize
  23965. * @param {number} width - The desired width.
  23966. * @param {number} height - The desired height.
  23967. */
  23968. setSize: function (width, height) {
  23969. this.view.width = width;
  23970. this.view.height = height;
  23971. },
  23972. /**
  23973. * Resets the camera back to 0,0 and un-follows any object it may have been tracking.
  23974. * Also immediately resets any camera effects that may have been running such as
  23975. * shake, flash or fade.
  23976. *
  23977. * @method Phaser.Camera#reset
  23978. */
  23979. reset: function () {
  23980. this.target = null;
  23981. this.view.x = 0;
  23982. this.view.y = 0;
  23983. this._shake.duration = 0;
  23984. this.resetFX();
  23985. },
  23986. /**
  23987. * Resets any active FX, such as a fade or flash and immediately clears it.
  23988. * Useful to calling after a fade in order to remove the fade from the Stage.
  23989. *
  23990. * @method Phaser.Camera#resetFX
  23991. */
  23992. resetFX: function () {
  23993. this.fx.clear();
  23994. this.fx.alpha = 0;
  23995. this._fxDuration = 0;
  23996. }
  23997. };
  23998. Phaser.Camera.prototype.constructor = Phaser.Camera;
  23999. /**
  24000. * The Cameras x coordinate. This value is automatically clamped if it falls outside of the World bounds.
  24001. * @name Phaser.Camera#x
  24002. * @property {number} x - Gets or sets the cameras x position.
  24003. */
  24004. Object.defineProperty(Phaser.Camera.prototype, "x", {
  24005. get: function () {
  24006. return this.view.x;
  24007. },
  24008. set: function (value) {
  24009. this.view.x = value;
  24010. if (this.bounds)
  24011. {
  24012. this.checkBounds();
  24013. }
  24014. }
  24015. });
  24016. /**
  24017. * The Cameras y coordinate. This value is automatically clamped if it falls outside of the World bounds.
  24018. * @name Phaser.Camera#y
  24019. * @property {number} y - Gets or sets the cameras y position.
  24020. */
  24021. Object.defineProperty(Phaser.Camera.prototype, "y", {
  24022. get: function () {
  24023. return this.view.y;
  24024. },
  24025. set: function (value) {
  24026. this.view.y = value;
  24027. if (this.bounds)
  24028. {
  24029. this.checkBounds();
  24030. }
  24031. }
  24032. });
  24033. /**
  24034. * The Cameras position. This value is automatically clamped if it falls outside of the World bounds.
  24035. * @name Phaser.Camera#position
  24036. * @property {Phaser.Point} position - Gets or sets the cameras xy position using Phaser.Point object.
  24037. */
  24038. Object.defineProperty(Phaser.Camera.prototype, "position", {
  24039. get: function () {
  24040. this._position.set(this.view.x, this.view.y);
  24041. return this._position;
  24042. },
  24043. set: function (value) {
  24044. if (typeof value.x !== "undefined") { this.view.x = value.x; }
  24045. if (typeof value.y !== "undefined") { this.view.y = value.y; }
  24046. if (this.bounds)
  24047. {
  24048. this.checkBounds();
  24049. }
  24050. }
  24051. });
  24052. /**
  24053. * The Cameras width. By default this is the same as the Game size and should not be adjusted for now.
  24054. * @name Phaser.Camera#width
  24055. * @property {number} width - Gets or sets the cameras width.
  24056. */
  24057. Object.defineProperty(Phaser.Camera.prototype, "width", {
  24058. get: function () {
  24059. return this.view.width;
  24060. },
  24061. set: function (value) {
  24062. this.view.width = value;
  24063. }
  24064. });
  24065. /**
  24066. * The Cameras height. By default this is the same as the Game size and should not be adjusted for now.
  24067. * @name Phaser.Camera#height
  24068. * @property {number} height - Gets or sets the cameras height.
  24069. */
  24070. Object.defineProperty(Phaser.Camera.prototype, "height", {
  24071. get: function () {
  24072. return this.view.height;
  24073. },
  24074. set: function (value) {
  24075. this.view.height = value;
  24076. }
  24077. });
  24078. /**
  24079. * @author Richard Davey <rich@photonstorm.com>
  24080. * @copyright 2016 Photon Storm Ltd.
  24081. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  24082. */
  24083. /**
  24084. * This is a base State class which can be extended if you are creating your own game.
  24085. * It provides quick access to common functions such as the camera, cache, input, match, sound and more.
  24086. *
  24087. * @class Phaser.State
  24088. * @constructor
  24089. */
  24090. Phaser.State = function () {
  24091. /**
  24092. * @property {Phaser.Game} game - This is a reference to the currently running Game.
  24093. */
  24094. this.game = null;
  24095. /**
  24096. * @property {string} key - The string based identifier given to the State when added into the State Manager.
  24097. */
  24098. this.key = '';
  24099. /**
  24100. * @property {Phaser.GameObjectFactory} add - A reference to the GameObjectFactory which can be used to add new objects to the World.
  24101. */
  24102. this.add = null;
  24103. /**
  24104. * @property {Phaser.GameObjectCreator} make - A reference to the GameObjectCreator which can be used to make new objects.
  24105. */
  24106. this.make = null;
  24107. /**
  24108. * @property {Phaser.Camera} camera - A handy reference to World.camera.
  24109. */
  24110. this.camera = null;
  24111. /**
  24112. * @property {Phaser.Cache} cache - A reference to the game cache which contains any loaded or generated assets, such as images, sound and more.
  24113. */
  24114. this.cache = null;
  24115. /**
  24116. * @property {Phaser.Input} input - A reference to the Input Manager.
  24117. */
  24118. this.input = null;
  24119. /**
  24120. * @property {Phaser.Loader} load - A reference to the Loader, which you mostly use in the preload method of your state to load external assets.
  24121. */
  24122. this.load = null;
  24123. /**
  24124. * @property {Phaser.Math} math - A reference to Math class with lots of helpful functions.
  24125. */
  24126. this.math = null;
  24127. /**
  24128. * @property {Phaser.SoundManager} sound - A reference to the Sound Manager which can create, play and stop sounds, as well as adjust global volume.
  24129. */
  24130. this.sound = null;
  24131. /**
  24132. * @property {Phaser.ScaleManager} scale - A reference to the Scale Manager which controls the way the game scales on different displays.
  24133. */
  24134. this.scale = null;
  24135. /**
  24136. * @property {Phaser.Stage} stage - A reference to the Stage.
  24137. */
  24138. this.stage = null;
  24139. /**
  24140. * @property {Phaser.Time} time - A reference to the game clock and timed events system.
  24141. */
  24142. this.time = null;
  24143. /**
  24144. * @property {Phaser.TweenManager} tweens - A reference to the tween manager.
  24145. */
  24146. this.tweens = null;
  24147. /**
  24148. * @property {Phaser.World} world - A reference to the game world. All objects live in the Game World and its size is not bound by the display resolution.
  24149. */
  24150. this.world = null;
  24151. /**
  24152. * @property {Phaser.Particles} particles - The Particle Manager. It is called during the core gameloop and updates any Particle Emitters it has created.
  24153. */
  24154. this.particles = null;
  24155. /**
  24156. * @property {Phaser.Physics} physics - A reference to the physics manager which looks after the different physics systems available within Phaser.
  24157. */
  24158. this.physics = null;
  24159. /**
  24160. * @property {Phaser.RandomDataGenerator} rnd - A reference to the seeded and repeatable random data generator.
  24161. */
  24162. this.rnd = null;
  24163. };
  24164. Phaser.State.prototype = {
  24165. /**
  24166. * init is the very first function called when your State starts up. It's called before preload, create or anything else.
  24167. * If you need to route the game away to another State you could do so here, or if you need to prepare a set of variables
  24168. * or objects before the preloading starts.
  24169. *
  24170. * @method Phaser.State#init
  24171. */
  24172. init: function () {
  24173. },
  24174. /**
  24175. * preload is called first. Normally you'd use this to load your game assets (or those needed for the current State)
  24176. * You shouldn't create any objects in this method that require assets that you're also loading in this method, as
  24177. * they won't yet be available.
  24178. *
  24179. * @method Phaser.State#preload
  24180. */
  24181. preload: function () {
  24182. },
  24183. /**
  24184. * loadUpdate is called during the Loader process. This only happens if you've set one or more assets to load in the preload method.
  24185. *
  24186. * @method Phaser.State#loadUpdate
  24187. */
  24188. loadUpdate: function () {
  24189. },
  24190. /**
  24191. * loadRender is called during the Loader process. This only happens if you've set one or more assets to load in the preload method.
  24192. * The difference between loadRender and render is that any objects you render in this method you must be sure their assets exist.
  24193. *
  24194. * @method Phaser.State#loadRender
  24195. */
  24196. loadRender: function () {
  24197. },
  24198. /**
  24199. * create is called once preload has completed, this includes the loading of any assets from the Loader.
  24200. * If you don't have a preload method then create is the first method called in your State.
  24201. *
  24202. * @method Phaser.State#create
  24203. */
  24204. create: function () {
  24205. },
  24206. /**
  24207. * The update method is left empty for your own use.
  24208. * It is called during the core game loop AFTER debug, physics, plugins and the Stage have had their preUpdate methods called.
  24209. * It is called BEFORE Stage, Tweens, Sounds, Input, Physics, Particles and Plugins have had their postUpdate methods called.
  24210. *
  24211. * @method Phaser.State#update
  24212. */
  24213. update: function () {
  24214. },
  24215. /**
  24216. * The preRender method is called after all Game Objects have been updated, but before any rendering takes place.
  24217. *
  24218. * @method Phaser.State#preRender
  24219. */
  24220. preRender: function () {
  24221. },
  24222. /**
  24223. * Nearly all display objects in Phaser render automatically, you don't need to tell them to render.
  24224. * However the render method is called AFTER the game renderer and plugins have rendered, so you're able to do any
  24225. * final post-processing style effects here. Note that this happens before plugins postRender takes place.
  24226. *
  24227. * @method Phaser.State#render
  24228. */
  24229. render: function () {
  24230. },
  24231. /**
  24232. * If your game is set to Scalemode RESIZE then each time the browser resizes it will call this function, passing in the new width and height.
  24233. *
  24234. * @method Phaser.State#resize
  24235. */
  24236. resize: function () {
  24237. },
  24238. /**
  24239. * This method will be called if the core game loop is paused.
  24240. *
  24241. * @method Phaser.State#paused
  24242. */
  24243. paused: function () {
  24244. },
  24245. /**
  24246. * This method will be called when the core game loop resumes from a paused state.
  24247. *
  24248. * @method Phaser.State#resumed
  24249. */
  24250. resumed: function () {
  24251. },
  24252. /**
  24253. * pauseUpdate is called while the game is paused instead of preUpdate, update and postUpdate.
  24254. *
  24255. * @method Phaser.State#pauseUpdate
  24256. */
  24257. pauseUpdate: function () {
  24258. },
  24259. /**
  24260. * This method will be called when the State is shutdown (i.e. you switch to another state from this one).
  24261. *
  24262. * @method Phaser.State#shutdown
  24263. */
  24264. shutdown: function () {
  24265. }
  24266. };
  24267. Phaser.State.prototype.constructor = Phaser.State;
  24268. /* jshint newcap: false */
  24269. /**
  24270. * @author Richard Davey <rich@photonstorm.com>
  24271. * @copyright 2016 Photon Storm Ltd.
  24272. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  24273. */
  24274. /**
  24275. * The State Manager is responsible for loading, setting up and switching game states.
  24276. *
  24277. * @class Phaser.StateManager
  24278. * @constructor
  24279. * @param {Phaser.Game} game - A reference to the currently running game.
  24280. * @param {Phaser.State|Object} [pendingState=null] - A State object to seed the manager with.
  24281. */
  24282. Phaser.StateManager = function (game, pendingState) {
  24283. /**
  24284. * @property {Phaser.Game} game - A reference to the currently running game.
  24285. */
  24286. this.game = game;
  24287. /**
  24288. * @property {object} states - The object containing Phaser.States.
  24289. */
  24290. this.states = {};
  24291. /**
  24292. * @property {Phaser.State} _pendingState - The state to be switched to in the next frame.
  24293. * @private
  24294. */
  24295. this._pendingState = null;
  24296. if (typeof pendingState !== 'undefined' && pendingState !== null)
  24297. {
  24298. this._pendingState = pendingState;
  24299. }
  24300. /**
  24301. * @property {boolean} _clearWorld - Clear the world when we switch state?
  24302. * @private
  24303. */
  24304. this._clearWorld = false;
  24305. /**
  24306. * @property {boolean} _clearCache - Clear the cache when we switch state?
  24307. * @private
  24308. */
  24309. this._clearCache = false;
  24310. /**
  24311. * @property {boolean} _created - Flag that sets if the State has been created or not.
  24312. * @private
  24313. */
  24314. this._created = false;
  24315. /**
  24316. * @property {any[]} _args - Temporary container when you pass vars from one State to another.
  24317. * @private
  24318. */
  24319. this._args = [];
  24320. /**
  24321. * @property {string} current - The current active State object.
  24322. * @default
  24323. */
  24324. this.current = '';
  24325. /**
  24326. * onStateChange is a Phaser.Signal that is dispatched whenever the game changes state.
  24327. *
  24328. * It is dispatched only when the new state is started, which isn't usually at the same time as StateManager.start
  24329. * is called because state swapping is done in sync with the game loop. It is dispatched *before* any of the new states
  24330. * methods (such as preload and create) are called, and *after* the previous states shutdown method has been run.
  24331. *
  24332. * The callback you specify is sent two parameters: the string based key of the new state,
  24333. * and the second parameter is the string based key of the old / previous state.
  24334. *
  24335. * @property {Phaser.Signal} onStateChange
  24336. */
  24337. this.onStateChange = new Phaser.Signal();
  24338. /**
  24339. * @property {function} onInitCallback - This is called when the state is set as the active state.
  24340. * @default
  24341. */
  24342. this.onInitCallback = null;
  24343. /**
  24344. * @property {function} onPreloadCallback - This is called when the state starts to load assets.
  24345. * @default
  24346. */
  24347. this.onPreloadCallback = null;
  24348. /**
  24349. * @property {function} onCreateCallback - This is called when the state preload has finished and creation begins.
  24350. * @default
  24351. */
  24352. this.onCreateCallback = null;
  24353. /**
  24354. * @property {function} onUpdateCallback - This is called when the state is updated, every game loop. It doesn't happen during preload (@see onLoadUpdateCallback).
  24355. * @default
  24356. */
  24357. this.onUpdateCallback = null;
  24358. /**
  24359. * @property {function} onRenderCallback - This is called post-render. It doesn't happen during preload (see onLoadRenderCallback).
  24360. * @default
  24361. */
  24362. this.onRenderCallback = null;
  24363. /**
  24364. * @property {function} onResizeCallback - This is called if ScaleManager.scalemode is RESIZE and a resize event occurs. It's passed the new width and height.
  24365. * @default
  24366. */
  24367. this.onResizeCallback = null;
  24368. /**
  24369. * @property {function} onPreRenderCallback - This is called before the state is rendered and before the stage is cleared but after all game objects have had their final properties adjusted.
  24370. * @default
  24371. */
  24372. this.onPreRenderCallback = null;
  24373. /**
  24374. * @property {function} onLoadUpdateCallback - This is called when the State is updated during the preload phase.
  24375. * @default
  24376. */
  24377. this.onLoadUpdateCallback = null;
  24378. /**
  24379. * @property {function} onLoadRenderCallback - This is called when the State is rendered during the preload phase.
  24380. * @default
  24381. */
  24382. this.onLoadRenderCallback = null;
  24383. /**
  24384. * @property {function} onPausedCallback - This is called when the game is paused.
  24385. * @default
  24386. */
  24387. this.onPausedCallback = null;
  24388. /**
  24389. * @property {function} onResumedCallback - This is called when the game is resumed from a paused state.
  24390. * @default
  24391. */
  24392. this.onResumedCallback = null;
  24393. /**
  24394. * @property {function} onPauseUpdateCallback - This is called every frame while the game is paused.
  24395. * @default
  24396. */
  24397. this.onPauseUpdateCallback = null;
  24398. /**
  24399. * @property {function} onShutDownCallback - This is called when the state is shut down (i.e. swapped to another state).
  24400. * @default
  24401. */
  24402. this.onShutDownCallback = null;
  24403. };
  24404. Phaser.StateManager.prototype = {
  24405. /**
  24406. * The Boot handler is called by Phaser.Game when it first starts up.
  24407. * @method Phaser.StateManager#boot
  24408. * @private
  24409. */
  24410. boot: function () {
  24411. this.game.onPause.add(this.pause, this);
  24412. this.game.onResume.add(this.resume, this);
  24413. if (this._pendingState !== null && typeof this._pendingState !== 'string')
  24414. {
  24415. this.add('default', this._pendingState, true);
  24416. }
  24417. },
  24418. /**
  24419. * Adds a new State into the StateManager. You must give each State a unique key by which you'll identify it.
  24420. * The State can be either a Phaser.State object (or an object that extends it), a plain JavaScript object or a function.
  24421. * If a function is given a new state object will be created by calling it.
  24422. *
  24423. * @method Phaser.StateManager#add
  24424. * @param {string} key - A unique key you use to reference this state, i.e. "MainMenu", "Level1".
  24425. * @param {Phaser.State|object|function} state - The state you want to switch to.
  24426. * @param {boolean} [autoStart=false] - If true the State will be started immediately after adding it.
  24427. */
  24428. add: function (key, state, autoStart) {
  24429. if (autoStart === undefined) { autoStart = false; }
  24430. var newState;
  24431. if (state instanceof Phaser.State)
  24432. {
  24433. newState = state;
  24434. }
  24435. else if (typeof state === 'object')
  24436. {
  24437. newState = state;
  24438. newState.game = this.game;
  24439. }
  24440. else if (typeof state === 'function')
  24441. {
  24442. newState = new state(this.game);
  24443. }
  24444. this.states[key] = newState;
  24445. if (autoStart)
  24446. {
  24447. if (this.game.isBooted)
  24448. {
  24449. this.start(key);
  24450. }
  24451. else
  24452. {
  24453. this._pendingState = key;
  24454. }
  24455. }
  24456. return newState;
  24457. },
  24458. /**
  24459. * Delete the given state.
  24460. * @method Phaser.StateManager#remove
  24461. * @param {string} key - A unique key you use to reference this state, i.e. "MainMenu", "Level1".
  24462. */
  24463. remove: function (key) {
  24464. if (this.current === key)
  24465. {
  24466. this.callbackContext = null;
  24467. this.onInitCallback = null;
  24468. this.onShutDownCallback = null;
  24469. this.onPreloadCallback = null;
  24470. this.onLoadRenderCallback = null;
  24471. this.onLoadUpdateCallback = null;
  24472. this.onCreateCallback = null;
  24473. this.onUpdateCallback = null;
  24474. this.onPreRenderCallback = null;
  24475. this.onRenderCallback = null;
  24476. this.onResizeCallback = null;
  24477. this.onPausedCallback = null;
  24478. this.onResumedCallback = null;
  24479. this.onPauseUpdateCallback = null;
  24480. }
  24481. delete this.states[key];
  24482. },
  24483. /**
  24484. * Start the given State. If a State is already running then State.shutDown will be called (if it exists) before switching to the new State.
  24485. *
  24486. * @method Phaser.StateManager#start
  24487. * @param {string} key - The key of the state you want to start.
  24488. * @param {boolean} [clearWorld=true] - Clear everything in the world? This clears the World display list fully (but not the Stage, so if you've added your own objects to the Stage they will need managing directly)
  24489. * @param {boolean} [clearCache=false] - Clear the Game.Cache? This purges out all loaded assets. The default is false and you must have clearWorld=true if you want to clearCache as well.
  24490. * @param {...*} parameter - Additional parameters that will be passed to the State.init function (if it has one).
  24491. */
  24492. start: function (key, clearWorld, clearCache) {
  24493. if (clearWorld === undefined) { clearWorld = true; }
  24494. if (clearCache === undefined) { clearCache = false; }
  24495. if (this.checkState(key))
  24496. {
  24497. // Place the state in the queue. It will be started the next time the game loop begins.
  24498. this._pendingState = key;
  24499. this._clearWorld = clearWorld;
  24500. this._clearCache = clearCache;
  24501. if (arguments.length > 3)
  24502. {
  24503. this._args = Array.prototype.splice.call(arguments, 3);
  24504. }
  24505. }
  24506. },
  24507. /**
  24508. * Restarts the current State. State.shutDown will be called (if it exists) before the State is restarted.
  24509. *
  24510. * @method Phaser.StateManager#restart
  24511. * @param {boolean} [clearWorld=true] - Clear everything in the world? This clears the World display list fully (but not the Stage, so if you've added your own objects to the Stage they will need managing directly)
  24512. * @param {boolean} [clearCache=false] - Clear the Game.Cache? This purges out all loaded assets. The default is false and you must have clearWorld=true if you want to clearCache as well.
  24513. * @param {...*} parameter - Additional parameters that will be passed to the State.init function if it has one.
  24514. */
  24515. restart: function (clearWorld, clearCache) {
  24516. if (clearWorld === undefined) { clearWorld = true; }
  24517. if (clearCache === undefined) { clearCache = false; }
  24518. // Place the state in the queue. It will be started the next time the game loop starts.
  24519. this._pendingState = this.current;
  24520. this._clearWorld = clearWorld;
  24521. this._clearCache = clearCache;
  24522. if (arguments.length > 2)
  24523. {
  24524. this._args = Array.prototype.slice.call(arguments, 2);
  24525. }
  24526. },
  24527. /**
  24528. * Used by onInit and onShutdown when those functions don't exist on the state
  24529. * @method Phaser.StateManager#dummy
  24530. * @private
  24531. */
  24532. dummy: function () {
  24533. },
  24534. /**
  24535. * preUpdate is called right at the start of the game loop. It is responsible for changing to a new state that was requested previously.
  24536. *
  24537. * @method Phaser.StateManager#preUpdate
  24538. */
  24539. preUpdate: function () {
  24540. if (this._pendingState && this.game.isBooted)
  24541. {
  24542. var previousStateKey = this.current;
  24543. // Already got a state running?
  24544. this.clearCurrentState();
  24545. this.setCurrentState(this._pendingState);
  24546. this.onStateChange.dispatch(this.current, previousStateKey);
  24547. if (this.current !== this._pendingState)
  24548. {
  24549. return;
  24550. }
  24551. else
  24552. {
  24553. this._pendingState = null;
  24554. }
  24555. // If StateManager.start has been called from the init of a State that ALSO has a preload, then
  24556. // onPreloadCallback will be set, but must be ignored
  24557. if (this.onPreloadCallback)
  24558. {
  24559. this.game.load.reset(true);
  24560. this.onPreloadCallback.call(this.callbackContext, this.game);
  24561. // Is the loader empty?
  24562. if (this.game.load.totalQueuedFiles() === 0 && this.game.load.totalQueuedPacks() === 0)
  24563. {
  24564. this.loadComplete();
  24565. }
  24566. else
  24567. {
  24568. // Start the loader going as we have something in the queue
  24569. this.game.load.start();
  24570. }
  24571. }
  24572. else
  24573. {
  24574. // No init? Then there was nothing to load either
  24575. this.loadComplete();
  24576. }
  24577. }
  24578. },
  24579. /**
  24580. * This method clears the current State, calling its shutdown callback. The process also removes any active tweens,
  24581. * resets the camera, resets input, clears physics, removes timers and if set clears the world and cache too.
  24582. *
  24583. * @method Phaser.StateManager#clearCurrentState
  24584. */
  24585. clearCurrentState: function () {
  24586. if (this.current)
  24587. {
  24588. if (this.onShutDownCallback)
  24589. {
  24590. this.onShutDownCallback.call(this.callbackContext, this.game);
  24591. }
  24592. this.game.tweens.removeAll();
  24593. this.game.camera.reset();
  24594. this.game.input.reset(true);
  24595. this.game.physics.clear();
  24596. this.game.time.removeAll();
  24597. this.game.scale.reset(this._clearWorld);
  24598. if (this.game.debug)
  24599. {
  24600. this.game.debug.reset();
  24601. }
  24602. if (this._clearWorld)
  24603. {
  24604. this.game.world.shutdown();
  24605. if (this._clearCache)
  24606. {
  24607. this.game.cache.destroy();
  24608. }
  24609. }
  24610. }
  24611. },
  24612. /**
  24613. * Checks if a given phaser state is valid. A State is considered valid if it has at least one of the core functions: preload, create, update or render.
  24614. *
  24615. * @method Phaser.StateManager#checkState
  24616. * @param {string} key - The key of the state you want to check.
  24617. * @return {boolean} true if the State has the required functions, otherwise false.
  24618. */
  24619. checkState: function (key) {
  24620. if (this.states[key])
  24621. {
  24622. if (this.states[key]['preload'] || this.states[key]['create'] || this.states[key]['update'] || this.states[key]['render'])
  24623. {
  24624. return true;
  24625. }
  24626. else
  24627. {
  24628. console.warn("Invalid Phaser State object given. Must contain at least a one of the required functions: preload, create, update or render");
  24629. return false;
  24630. }
  24631. }
  24632. else
  24633. {
  24634. console.warn("Phaser.StateManager - No state found with the key: " + key);
  24635. return false;
  24636. }
  24637. },
  24638. /**
  24639. * Links game properties to the State given by the key.
  24640. *
  24641. * @method Phaser.StateManager#link
  24642. * @param {string} key - State key.
  24643. * @protected
  24644. */
  24645. link: function (key) {
  24646. this.states[key].game = this.game;
  24647. this.states[key].add = this.game.add;
  24648. this.states[key].make = this.game.make;
  24649. this.states[key].camera = this.game.camera;
  24650. this.states[key].cache = this.game.cache;
  24651. this.states[key].input = this.game.input;
  24652. this.states[key].load = this.game.load;
  24653. this.states[key].math = this.game.math;
  24654. this.states[key].sound = this.game.sound;
  24655. this.states[key].scale = this.game.scale;
  24656. this.states[key].state = this;
  24657. this.states[key].stage = this.game.stage;
  24658. this.states[key].time = this.game.time;
  24659. this.states[key].tweens = this.game.tweens;
  24660. this.states[key].world = this.game.world;
  24661. this.states[key].particles = this.game.particles;
  24662. this.states[key].rnd = this.game.rnd;
  24663. this.states[key].physics = this.game.physics;
  24664. this.states[key].key = key;
  24665. },
  24666. /**
  24667. * Nulls all State level Phaser properties, including a reference to Game.
  24668. *
  24669. * @method Phaser.StateManager#unlink
  24670. * @param {string} key - State key.
  24671. * @protected
  24672. */
  24673. unlink: function (key) {
  24674. if (this.states[key])
  24675. {
  24676. this.states[key].game = null;
  24677. this.states[key].add = null;
  24678. this.states[key].make = null;
  24679. this.states[key].camera = null;
  24680. this.states[key].cache = null;
  24681. this.states[key].input = null;
  24682. this.states[key].load = null;
  24683. this.states[key].math = null;
  24684. this.states[key].sound = null;
  24685. this.states[key].scale = null;
  24686. this.states[key].state = null;
  24687. this.states[key].stage = null;
  24688. this.states[key].time = null;
  24689. this.states[key].tweens = null;
  24690. this.states[key].world = null;
  24691. this.states[key].particles = null;
  24692. this.states[key].rnd = null;
  24693. this.states[key].physics = null;
  24694. }
  24695. },
  24696. /**
  24697. * Sets the current State. Should not be called directly (use StateManager.start)
  24698. *
  24699. * @method Phaser.StateManager#setCurrentState
  24700. * @param {string} key - State key.
  24701. * @private
  24702. */
  24703. setCurrentState: function (key) {
  24704. this.callbackContext = this.states[key];
  24705. this.link(key);
  24706. // Used when the state is set as being the current active state
  24707. this.onInitCallback = this.states[key]['init'] || this.dummy;
  24708. this.onPreloadCallback = this.states[key]['preload'] || null;
  24709. this.onLoadRenderCallback = this.states[key]['loadRender'] || null;
  24710. this.onLoadUpdateCallback = this.states[key]['loadUpdate'] || null;
  24711. this.onCreateCallback = this.states[key]['create'] || null;
  24712. this.onUpdateCallback = this.states[key]['update'] || null;
  24713. this.onPreRenderCallback = this.states[key]['preRender'] || null;
  24714. this.onRenderCallback = this.states[key]['render'] || null;
  24715. this.onResizeCallback = this.states[key]['resize'] || null;
  24716. this.onPausedCallback = this.states[key]['paused'] || null;
  24717. this.onResumedCallback = this.states[key]['resumed'] || null;
  24718. this.onPauseUpdateCallback = this.states[key]['pauseUpdate'] || null;
  24719. // Used when the state is no longer the current active state
  24720. this.onShutDownCallback = this.states[key]['shutdown'] || this.dummy;
  24721. // Reset the physics system, but not on the first state start
  24722. if (this.current !== '')
  24723. {
  24724. this.game.physics.reset();
  24725. }
  24726. this.current = key;
  24727. this._created = false;
  24728. // At this point key and pendingState should equal each other
  24729. this.onInitCallback.apply(this.callbackContext, this._args);
  24730. // If they no longer do then the init callback hit StateManager.start
  24731. if (key === this._pendingState)
  24732. {
  24733. this._args = [];
  24734. }
  24735. this.game._kickstart = true;
  24736. },
  24737. /**
  24738. * Gets the current State.
  24739. *
  24740. * @method Phaser.StateManager#getCurrentState
  24741. * @return {Phaser.State}
  24742. * @public
  24743. */
  24744. getCurrentState: function() {
  24745. return this.states[this.current];
  24746. },
  24747. /**
  24748. * @method Phaser.StateManager#loadComplete
  24749. * @protected
  24750. */
  24751. loadComplete: function () {
  24752. // Make sure to do load-update one last time before state is set to _created
  24753. if (this._created === false && this.onLoadUpdateCallback)
  24754. {
  24755. this.onLoadUpdateCallback.call(this.callbackContext, this.game);
  24756. }
  24757. if (this._created === false && this.onCreateCallback)
  24758. {
  24759. this._created = true;
  24760. this.onCreateCallback.call(this.callbackContext, this.game);
  24761. }
  24762. else
  24763. {
  24764. this._created = true;
  24765. }
  24766. },
  24767. /**
  24768. * @method Phaser.StateManager#pause
  24769. * @protected
  24770. */
  24771. pause: function () {
  24772. if (this._created && this.onPausedCallback)
  24773. {
  24774. this.onPausedCallback.call(this.callbackContext, this.game);
  24775. }
  24776. },
  24777. /**
  24778. * @method Phaser.StateManager#resume
  24779. * @protected
  24780. */
  24781. resume: function () {
  24782. if (this._created && this.onResumedCallback)
  24783. {
  24784. this.onResumedCallback.call(this.callbackContext, this.game);
  24785. }
  24786. },
  24787. /**
  24788. * @method Phaser.StateManager#update
  24789. * @protected
  24790. */
  24791. update: function () {
  24792. if (this._created)
  24793. {
  24794. if (this.onUpdateCallback)
  24795. {
  24796. this.onUpdateCallback.call(this.callbackContext, this.game);
  24797. }
  24798. }
  24799. else
  24800. {
  24801. if (this.onLoadUpdateCallback)
  24802. {
  24803. this.onLoadUpdateCallback.call(this.callbackContext, this.game);
  24804. }
  24805. }
  24806. },
  24807. /**
  24808. * @method Phaser.StateManager#pauseUpdate
  24809. * @protected
  24810. */
  24811. pauseUpdate: function () {
  24812. if (this._created)
  24813. {
  24814. if (this.onPauseUpdateCallback)
  24815. {
  24816. this.onPauseUpdateCallback.call(this.callbackContext, this.game);
  24817. }
  24818. }
  24819. else
  24820. {
  24821. if (this.onLoadUpdateCallback)
  24822. {
  24823. this.onLoadUpdateCallback.call(this.callbackContext, this.game);
  24824. }
  24825. }
  24826. },
  24827. /**
  24828. * @method Phaser.StateManager#preRender
  24829. * @protected
  24830. * @param {number} elapsedTime - The time elapsed since the last update.
  24831. */
  24832. preRender: function (elapsedTime) {
  24833. if (this._created && this.onPreRenderCallback)
  24834. {
  24835. this.onPreRenderCallback.call(this.callbackContext, this.game, elapsedTime);
  24836. }
  24837. },
  24838. /**
  24839. * @method Phaser.StateManager#resize
  24840. * @protected
  24841. */
  24842. resize: function (width, height) {
  24843. if (this.onResizeCallback)
  24844. {
  24845. this.onResizeCallback.call(this.callbackContext, width, height);
  24846. }
  24847. },
  24848. /**
  24849. * @method Phaser.StateManager#render
  24850. * @protected
  24851. */
  24852. render: function () {
  24853. if (this._created)
  24854. {
  24855. if (this.onRenderCallback)
  24856. {
  24857. if (this.game.renderType === Phaser.CANVAS)
  24858. {
  24859. this.game.context.save();
  24860. this.game.context.setTransform(1, 0, 0, 1, 0, 0);
  24861. this.onRenderCallback.call(this.callbackContext, this.game);
  24862. this.game.context.restore();
  24863. }
  24864. else
  24865. {
  24866. this.onRenderCallback.call(this.callbackContext, this.game);
  24867. }
  24868. }
  24869. }
  24870. else
  24871. {
  24872. if (this.onLoadRenderCallback)
  24873. {
  24874. this.onLoadRenderCallback.call(this.callbackContext, this.game);
  24875. }
  24876. }
  24877. },
  24878. /**
  24879. * Removes all StateManager callback references to the State object, nulls the game reference and clears the States object.
  24880. * You don't recover from this without rebuilding the Phaser instance again.
  24881. * @method Phaser.StateManager#destroy
  24882. */
  24883. destroy: function () {
  24884. this._clearWorld = true;
  24885. this._clearCache = true;
  24886. this.clearCurrentState();
  24887. this.callbackContext = null;
  24888. this.onInitCallback = null;
  24889. this.onShutDownCallback = null;
  24890. this.onPreloadCallback = null;
  24891. this.onLoadRenderCallback = null;
  24892. this.onLoadUpdateCallback = null;
  24893. this.onCreateCallback = null;
  24894. this.onUpdateCallback = null;
  24895. this.onRenderCallback = null;
  24896. this.onPausedCallback = null;
  24897. this.onResumedCallback = null;
  24898. this.onPauseUpdateCallback = null;
  24899. this.game = null;
  24900. this.states = {};
  24901. this._pendingState = null;
  24902. this.current = '';
  24903. }
  24904. };
  24905. Phaser.StateManager.prototype.constructor = Phaser.StateManager;
  24906. /**
  24907. * @name Phaser.StateManager#created
  24908. * @property {boolean} created - True if the current state has had its `create` method run (if it has one, if not this is true by default).
  24909. * @readOnly
  24910. */
  24911. Object.defineProperty(Phaser.StateManager.prototype, "created", {
  24912. get: function () {
  24913. return this._created;
  24914. }
  24915. });
  24916. /**
  24917. * "It's like nailing jelly to a kitten" - Gary Penn
  24918. */
  24919. /**
  24920. * @author Miller Medeiros http://millermedeiros.github.com/js-signals/
  24921. * @author Richard Davey <rich@photonstorm.com>
  24922. * @copyright 2016 Photon Storm Ltd.
  24923. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  24924. */
  24925. /**
  24926. * Signals are what Phaser uses to handle events and event dispatching.
  24927. * You can listen for a Signal by binding a callback / function to it.
  24928. * This is done by using either `Signal.add` or `Signal.addOnce`.
  24929. *
  24930. * For example you can listen for a touch or click event from the Input Manager
  24931. * by using its `onDown` Signal:
  24932. *
  24933. * `game.input.onDown.add(function() { ... });`
  24934. *
  24935. * Rather than inline your function, you can pass a reference:
  24936. *
  24937. * `game.input.onDown.add(clicked, this);`
  24938. * `function clicked () { ... }`
  24939. *
  24940. * In this case the second argument (`this`) is the context in which your function should be called.
  24941. *
  24942. * Now every time the InputManager dispatches the `onDown` signal (or event), your function
  24943. * will be called.
  24944. *
  24945. * Very often a Signal will send arguments to your function.
  24946. * This is specific to the Signal itself.
  24947. * If you're unsure then check the documentation, or failing that simply do:
  24948. *
  24949. * `Signal.add(function() { console.log(arguments); })`
  24950. *
  24951. * and it will log all of the arguments your function received from the Signal.
  24952. *
  24953. * Sprites have lots of default signals you can listen to in their Events class, such as:
  24954. *
  24955. * `sprite.events.onKilled`
  24956. *
  24957. * Which is called automatically whenever the Sprite is killed.
  24958. * There are lots of other events, see the Events component for a list.
  24959. *
  24960. * As well as listening to pre-defined Signals you can also create your own:
  24961. *
  24962. * `var mySignal = new Phaser.Signal();`
  24963. *
  24964. * This creates a new Signal. You can bind a callback to it:
  24965. *
  24966. * `mySignal.add(myCallback, this);`
  24967. *
  24968. * and then finally when ready you can dispatch the Signal:
  24969. *
  24970. * `mySignal.dispatch(your arguments);`
  24971. *
  24972. * And your callback will be invoked. See the dispatch method for more details.
  24973. *
  24974. * @class Phaser.Signal
  24975. * @constructor
  24976. */
  24977. Phaser.Signal = function () {};
  24978. Phaser.Signal.prototype = {
  24979. /**
  24980. * @property {?Array.<Phaser.SignalBinding>} _bindings - Internal variable.
  24981. * @private
  24982. */
  24983. _bindings: null,
  24984. /**
  24985. * @property {any} _prevParams - Internal variable.
  24986. * @private
  24987. */
  24988. _prevParams: null,
  24989. /**
  24990. * Memorize the previously dispatched event?
  24991. *
  24992. * If an event has been memorized it is automatically dispatched when a new listener is added with {@link #add} or {@link #addOnce}.
  24993. * Use {@link #forget} to clear any currently memorized event.
  24994. *
  24995. * @property {boolean} memorize
  24996. */
  24997. memorize: false,
  24998. /**
  24999. * @property {boolean} _shouldPropagate
  25000. * @private
  25001. */
  25002. _shouldPropagate: true,
  25003. /**
  25004. * Is the Signal active? Only active signals will broadcast dispatched events.
  25005. *
  25006. * Setting this property during a dispatch will only affect the next dispatch. To stop the propagation of a signal from a listener use {@link #halt}.
  25007. *
  25008. * @property {boolean} active
  25009. * @default
  25010. */
  25011. active: true,
  25012. /**
  25013. * @property {function} _boundDispatch - The bound dispatch function, if any.
  25014. * @private
  25015. */
  25016. _boundDispatch: false,
  25017. /**
  25018. * @method Phaser.Signal#validateListener
  25019. * @param {function} listener - Signal handler function.
  25020. * @param {string} fnName - Function name.
  25021. * @private
  25022. */
  25023. validateListener: function (listener, fnName) {
  25024. if (typeof listener !== 'function')
  25025. {
  25026. throw new Error('Phaser.Signal: listener is a required param of {fn}() and should be a Function.'.replace('{fn}', fnName));
  25027. }
  25028. },
  25029. /**
  25030. * @method Phaser.Signal#_registerListener
  25031. * @private
  25032. * @param {function} listener - Signal handler function.
  25033. * @param {boolean} isOnce - Should the listener only be called once?
  25034. * @param {object} [listenerContext] - The context under which the listener is invoked.
  25035. * @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).
  25036. * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener.
  25037. */
  25038. _registerListener: function (listener, isOnce, listenerContext, priority, args) {
  25039. var prevIndex = this._indexOfListener(listener, listenerContext);
  25040. var binding;
  25041. if (prevIndex !== -1)
  25042. {
  25043. binding = this._bindings[prevIndex];
  25044. if (binding.isOnce() !== isOnce)
  25045. {
  25046. throw new Error('You cannot add' + (isOnce ? '' : 'Once') + '() then add' + (!isOnce ? '' : 'Once') + '() the same listener without removing the relationship first.');
  25047. }
  25048. }
  25049. else
  25050. {
  25051. binding = new Phaser.SignalBinding(this, listener, isOnce, listenerContext, priority, args);
  25052. this._addBinding(binding);
  25053. }
  25054. if (this.memorize && this._prevParams)
  25055. {
  25056. binding.execute(this._prevParams);
  25057. }
  25058. return binding;
  25059. },
  25060. /**
  25061. * @method Phaser.Signal#_addBinding
  25062. * @private
  25063. * @param {Phaser.SignalBinding} binding - An Object representing the binding between the Signal and listener.
  25064. */
  25065. _addBinding: function (binding) {
  25066. if (!this._bindings)
  25067. {
  25068. this._bindings = [];
  25069. }
  25070. // Simplified insertion sort
  25071. var n = this._bindings.length;
  25072. do {
  25073. n--;
  25074. }
  25075. while (this._bindings[n] && binding._priority <= this._bindings[n]._priority);
  25076. this._bindings.splice(n + 1, 0, binding);
  25077. },
  25078. /**
  25079. * @method Phaser.Signal#_indexOfListener
  25080. * @private
  25081. * @param {function} listener - Signal handler function.
  25082. * @param {object} [context=null] - Signal handler function.
  25083. * @return {number} The index of the listener within the private bindings array.
  25084. */
  25085. _indexOfListener: function (listener, context) {
  25086. if (!this._bindings)
  25087. {
  25088. return -1;
  25089. }
  25090. if (context === undefined) { context = null; }
  25091. var n = this._bindings.length;
  25092. var cur;
  25093. while (n--)
  25094. {
  25095. cur = this._bindings[n];
  25096. if (cur._listener === listener && cur.context === context)
  25097. {
  25098. return n;
  25099. }
  25100. }
  25101. return -1;
  25102. },
  25103. /**
  25104. * Check if a specific listener is attached.
  25105. *
  25106. * @method Phaser.Signal#has
  25107. * @param {function} listener - Signal handler function.
  25108. * @param {object} [context] - Context on which listener will be executed (object that should represent the `this` variable inside listener function).
  25109. * @return {boolean} If Signal has the specified listener.
  25110. */
  25111. has: function (listener, context) {
  25112. return this._indexOfListener(listener, context) !== -1;
  25113. },
  25114. /**
  25115. * Add an event listener for this signal.
  25116. *
  25117. * An event listener is a callback with a related context and priority.
  25118. *
  25119. * You can optionally provide extra arguments which will be passed to the callback after any internal parameters.
  25120. *
  25121. * For example: `Phaser.Key.onDown` when dispatched will send the Phaser.Key object that caused the signal as the first parameter.
  25122. * Any arguments you've specified after `priority` will be sent as well:
  25123. *
  25124. * `fireButton.onDown.add(shoot, this, 0, 'lazer', 100);`
  25125. *
  25126. * When onDown dispatches it will call the `shoot` callback passing it: `Phaser.Key, 'lazer', 100`.
  25127. *
  25128. * Where the first parameter is the one that Key.onDown dispatches internally and 'lazer',
  25129. * and the value 100 were the custom arguments given in the call to 'add'.
  25130. *
  25131. * @method Phaser.Signal#add
  25132. * @param {function} listener - The function to call when this Signal is dispatched.
  25133. * @param {object} [listenerContext] - The context under which the listener will be executed (i.e. the object that should represent the `this` variable).
  25134. * @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)
  25135. * @param {...any} [args=(none)] - Additional arguments to pass to the callback (listener) function. They will be appended after any arguments usually dispatched.
  25136. * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener.
  25137. */
  25138. add: function (listener, listenerContext, priority) {
  25139. this.validateListener(listener, 'add');
  25140. var args = [];
  25141. if (arguments.length > 3)
  25142. {
  25143. for (var i = 3; i < arguments.length; i++)
  25144. {
  25145. args.push(arguments[i]);
  25146. }
  25147. }
  25148. return this._registerListener(listener, false, listenerContext, priority, args);
  25149. },
  25150. /**
  25151. * Add a one-time listener - the listener is automatically removed after the first execution.
  25152. *
  25153. * If there is as {@link Phaser.Signal#memorize memorized} event then it will be dispatched and
  25154. * the listener will be removed immediately.
  25155. *
  25156. * @method Phaser.Signal#addOnce
  25157. * @param {function} listener - The function to call when this Signal is dispatched.
  25158. * @param {object} [listenerContext] - The context under which the listener will be executed (i.e. the object that should represent the `this` variable).
  25159. * @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)
  25160. * @param {...any} [args=(none)] - Additional arguments to pass to the callback (listener) function. They will be appended after any arguments usually dispatched.
  25161. * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener.
  25162. */
  25163. addOnce: function (listener, listenerContext, priority) {
  25164. this.validateListener(listener, 'addOnce');
  25165. var args = [];
  25166. if (arguments.length > 3)
  25167. {
  25168. for (var i = 3; i < arguments.length; i++)
  25169. {
  25170. args.push(arguments[i]);
  25171. }
  25172. }
  25173. return this._registerListener(listener, true, listenerContext, priority, args);
  25174. },
  25175. /**
  25176. * Remove a single event listener.
  25177. *
  25178. * @method Phaser.Signal#remove
  25179. * @param {function} listener - Handler function that should be removed.
  25180. * @param {object} [context=null] - Execution context (since you can add the same handler multiple times if executing in a different context).
  25181. * @return {function} Listener handler function.
  25182. */
  25183. remove: function (listener, context) {
  25184. this.validateListener(listener, 'remove');
  25185. var i = this._indexOfListener(listener, context);
  25186. if (i !== -1)
  25187. {
  25188. this._bindings[i]._destroy(); //no reason to a Phaser.SignalBinding exist if it isn't attached to a signal
  25189. this._bindings.splice(i, 1);
  25190. }
  25191. return listener;
  25192. },
  25193. /**
  25194. * Remove all event listeners.
  25195. *
  25196. * @method Phaser.Signal#removeAll
  25197. * @param {object} [context=null] - If specified only listeners for the given context will be removed.
  25198. */
  25199. removeAll: function (context) {
  25200. if (context === undefined) { context = null; }
  25201. if (!this._bindings)
  25202. {
  25203. return;
  25204. }
  25205. var n = this._bindings.length;
  25206. while (n--)
  25207. {
  25208. if (context)
  25209. {
  25210. if (this._bindings[n].context === context)
  25211. {
  25212. this._bindings[n]._destroy();
  25213. this._bindings.splice(n, 1);
  25214. }
  25215. }
  25216. else
  25217. {
  25218. this._bindings[n]._destroy();
  25219. }
  25220. }
  25221. if (!context)
  25222. {
  25223. this._bindings.length = 0;
  25224. }
  25225. },
  25226. /**
  25227. * Gets the total number of listeners attached to this Signal.
  25228. *
  25229. * @method Phaser.Signal#getNumListeners
  25230. * @return {integer} Number of listeners attached to the Signal.
  25231. */
  25232. getNumListeners: function () {
  25233. return this._bindings ? this._bindings.length : 0;
  25234. },
  25235. /**
  25236. * Stop propagation of the event, blocking the dispatch to next listener on the queue.
  25237. *
  25238. * This should be called only during event dispatch as calling it before/after dispatch won't affect another broadcast.
  25239. * See {@link #active} to enable/disable the signal entirely.
  25240. *
  25241. * @method Phaser.Signal#halt
  25242. */
  25243. halt: function () {
  25244. this._shouldPropagate = false;
  25245. },
  25246. /**
  25247. * Dispatch / broadcast the event to all listeners.
  25248. *
  25249. * To create an instance-bound dispatch for this Signal, use {@link #boundDispatch}.
  25250. *
  25251. * @method Phaser.Signal#dispatch
  25252. * @param {any} [params] - Parameters that should be passed to each handler.
  25253. */
  25254. dispatch: function () {
  25255. if (!this.active || !this._bindings)
  25256. {
  25257. return;
  25258. }
  25259. var paramsArr = Array.prototype.slice.call(arguments);
  25260. var n = this._bindings.length;
  25261. var bindings;
  25262. if (this.memorize)
  25263. {
  25264. this._prevParams = paramsArr;
  25265. }
  25266. if (!n)
  25267. {
  25268. // Should come after memorize
  25269. return;
  25270. }
  25271. bindings = this._bindings.slice(); //clone array in case add/remove items during dispatch
  25272. this._shouldPropagate = true; //in case `halt` was called before dispatch or during the previous dispatch.
  25273. //execute all callbacks until end of the list or until a callback returns `false` or stops propagation
  25274. //reverse loop since listeners with higher priority will be added at the end of the list
  25275. do {
  25276. n--;
  25277. }
  25278. while (bindings[n] && this._shouldPropagate && bindings[n].execute(paramsArr) !== false);
  25279. },
  25280. /**
  25281. * Forget the currently {@link Phaser.Signal#memorize memorized} event, if any.
  25282. *
  25283. * @method Phaser.Signal#forget
  25284. */
  25285. forget: function() {
  25286. if (this._prevParams)
  25287. {
  25288. this._prevParams = null;
  25289. }
  25290. },
  25291. /**
  25292. * Dispose the signal - no more events can be dispatched.
  25293. *
  25294. * This removes all event listeners and clears references to external objects.
  25295. * Calling methods on a disposed objects results in undefined behavior.
  25296. *
  25297. * @method Phaser.Signal#dispose
  25298. */
  25299. dispose: function () {
  25300. this.removeAll();
  25301. this._bindings = null;
  25302. if (this._prevParams)
  25303. {
  25304. this._prevParams = null;
  25305. }
  25306. },
  25307. /**
  25308. * A string representation of the object.
  25309. *
  25310. * @method Phaser.Signal#toString
  25311. * @return {string} String representation of the object.
  25312. */
  25313. toString: function () {
  25314. return '[Phaser.Signal active:'+ this.active +' numListeners:'+ this.getNumListeners() +']';
  25315. }
  25316. };
  25317. /**
  25318. * Create a `dispatch` function that maintains a binding to the original Signal context.
  25319. *
  25320. * Use the resulting value if the dispatch function needs to be passed somewhere
  25321. * or called independently of the Signal object.
  25322. *
  25323. * @memberof Phaser.Signal
  25324. * @property {function} boundDispatch
  25325. */
  25326. Object.defineProperty(Phaser.Signal.prototype, "boundDispatch", {
  25327. get: function () {
  25328. var _this = this;
  25329. return this._boundDispatch || (this._boundDispatch = function () {
  25330. return _this.dispatch.apply(_this, arguments);
  25331. });
  25332. }
  25333. });
  25334. Phaser.Signal.prototype.constructor = Phaser.Signal;
  25335. /**
  25336. * @author Miller Medeiros http://millermedeiros.github.com/js-signals/
  25337. * @author Richard Davey <rich@photonstorm.com>
  25338. * @copyright 2016 Photon Storm Ltd.
  25339. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  25340. */
  25341. /**
  25342. * Object that represents a binding between a Signal and a listener function.
  25343. * This is an internal constructor and shouldn't be created directly.
  25344. * Inspired by Joa Ebert AS3 SignalBinding and Robert Penner's Slot classes.
  25345. *
  25346. * @class Phaser.SignalBinding
  25347. * @constructor
  25348. * @param {Phaser.Signal} signal - Reference to Signal object that listener is currently bound to.
  25349. * @param {function} listener - Handler function bound to the signal.
  25350. * @param {boolean} isOnce - If binding should be executed just once.
  25351. * @param {object} [listenerContext=null] - Context on which listener will be executed (object that should represent the `this` variable inside listener function).
  25352. * @param {number} [priority] - The priority level of the event listener. (default = 0).
  25353. * @param {...any} [args=(none)] - Additional arguments to pass to the callback (listener) function. They will be appended after any arguments usually dispatched.
  25354. */
  25355. Phaser.SignalBinding = function (signal, listener, isOnce, listenerContext, priority, args) {
  25356. /**
  25357. * @property {Phaser.Game} _listener - Handler function bound to the signal.
  25358. * @private
  25359. */
  25360. this._listener = listener;
  25361. if (isOnce)
  25362. {
  25363. this._isOnce = true;
  25364. }
  25365. if (listenerContext != null) /* not null/undefined */
  25366. {
  25367. this.context = listenerContext;
  25368. }
  25369. /**
  25370. * @property {Phaser.Signal} _signal - Reference to Signal object that listener is currently bound to.
  25371. * @private
  25372. */
  25373. this._signal = signal;
  25374. if (priority)
  25375. {
  25376. this._priority = priority;
  25377. }
  25378. if (args && args.length)
  25379. {
  25380. this._args = args;
  25381. }
  25382. };
  25383. Phaser.SignalBinding.prototype = {
  25384. /**
  25385. * @property {?object} context - Context on which listener will be executed (object that should represent the `this` variable inside listener function).
  25386. */
  25387. context: null,
  25388. /**
  25389. * @property {boolean} _isOnce - If binding should be executed just once.
  25390. * @private
  25391. */
  25392. _isOnce: false,
  25393. /**
  25394. * @property {number} _priority - Listener priority.
  25395. * @private
  25396. */
  25397. _priority: 0,
  25398. /**
  25399. * @property {array} _args - Listener arguments.
  25400. * @private
  25401. */
  25402. _args: null,
  25403. /**
  25404. * @property {number} callCount - The number of times the handler function has been called.
  25405. */
  25406. callCount: 0,
  25407. /**
  25408. * If binding is active and should be executed.
  25409. * @property {boolean} active
  25410. * @default
  25411. */
  25412. active: true,
  25413. /**
  25414. * Default parameters passed to listener during `Signal.dispatch` and `SignalBinding.execute` (curried parameters).
  25415. * @property {array|null} params
  25416. * @default
  25417. */
  25418. params: null,
  25419. /**
  25420. * Call listener passing arbitrary parameters.
  25421. * 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.
  25422. * @method Phaser.SignalBinding#execute
  25423. * @param {any[]} [paramsArr] - Array of parameters that should be passed to the listener.
  25424. * @return {any} Value returned by the listener.
  25425. */
  25426. execute: function(paramsArr) {
  25427. var handlerReturn, params;
  25428. if (this.active && !!this._listener)
  25429. {
  25430. params = this.params ? this.params.concat(paramsArr) : paramsArr;
  25431. if (this._args)
  25432. {
  25433. params = params.concat(this._args);
  25434. }
  25435. handlerReturn = this._listener.apply(this.context, params);
  25436. this.callCount++;
  25437. if (this._isOnce)
  25438. {
  25439. this.detach();
  25440. }
  25441. }
  25442. return handlerReturn;
  25443. },
  25444. /**
  25445. * Detach binding from signal.
  25446. * alias to: @see mySignal.remove(myBinding.getListener());
  25447. * @method Phaser.SignalBinding#detach
  25448. * @return {function|null} Handler function bound to the signal or `null` if binding was previously detached.
  25449. */
  25450. detach: function () {
  25451. return this.isBound() ? this._signal.remove(this._listener, this.context) : null;
  25452. },
  25453. /**
  25454. * @method Phaser.SignalBinding#isBound
  25455. * @return {boolean} True if binding is still bound to the signal and has a listener.
  25456. */
  25457. isBound: function () {
  25458. return (!!this._signal && !!this._listener);
  25459. },
  25460. /**
  25461. * @method Phaser.SignalBinding#isOnce
  25462. * @return {boolean} If SignalBinding will only be executed once.
  25463. */
  25464. isOnce: function () {
  25465. return this._isOnce;
  25466. },
  25467. /**
  25468. * @method Phaser.SignalBinding#getListener
  25469. * @return {function} Handler function bound to the signal.
  25470. */
  25471. getListener: function () {
  25472. return this._listener;
  25473. },
  25474. /**
  25475. * @method Phaser.SignalBinding#getSignal
  25476. * @return {Phaser.Signal} Signal that listener is currently bound to.
  25477. */
  25478. getSignal: function () {
  25479. return this._signal;
  25480. },
  25481. /**
  25482. * Delete instance properties
  25483. * @method Phaser.SignalBinding#_destroy
  25484. * @private
  25485. */
  25486. _destroy: function () {
  25487. delete this._signal;
  25488. delete this._listener;
  25489. delete this.context;
  25490. },
  25491. /**
  25492. * @method Phaser.SignalBinding#toString
  25493. * @return {string} String representation of the object.
  25494. */
  25495. toString: function () {
  25496. return '[Phaser.SignalBinding isOnce:' + this._isOnce +', isBound:'+ this.isBound() +', active:' + this.active + ']';
  25497. }
  25498. };
  25499. Phaser.SignalBinding.prototype.constructor = Phaser.SignalBinding;
  25500. /**
  25501. * @author Richard Davey <rich@photonstorm.com>
  25502. * @copyright 2016 Photon Storm Ltd.
  25503. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  25504. */
  25505. /**
  25506. * This is a base Filter class to use for any Phaser filter development.
  25507. *
  25508. * The vast majority of filters (including all of those that ship with Phaser) use fragment shaders, and
  25509. * therefore only work in WebGL and are not supported by Canvas at all.
  25510. *
  25511. * @class Phaser.Filter
  25512. * @constructor
  25513. * @param {Phaser.Game} game - A reference to the currently running game.
  25514. * @param {object} uniforms - Uniform mappings object
  25515. * @param {Array|string} fragmentSrc - The fragment shader code. Either an array, one element per line of code, or a string.
  25516. */
  25517. Phaser.Filter = function (game, uniforms, fragmentSrc) {
  25518. /**
  25519. * @property {Phaser.Game} game - A reference to the currently running game.
  25520. */
  25521. this.game = game;
  25522. /**
  25523. * @property {number} type - The const type of this object, either Phaser.WEBGL_FILTER or Phaser.CANVAS_FILTER.
  25524. * @default
  25525. */
  25526. this.type = Phaser.WEBGL_FILTER;
  25527. /**
  25528. * An array of passes - some filters contain a few steps this array simply stores the steps in a linear fashion.
  25529. * For example the blur filter has two passes blurX and blurY.
  25530. * @property {array} passes - An array of filter objects.
  25531. * @private
  25532. */
  25533. this.passes = [this];
  25534. /**
  25535. * @property {array} shaders - Array an array of shaders.
  25536. * @private
  25537. */
  25538. this.shaders = [];
  25539. /**
  25540. * @property {boolean} dirty - Internal PIXI var.
  25541. * @default
  25542. */
  25543. this.dirty = true;
  25544. /**
  25545. * @property {number} padding - Internal PIXI var.
  25546. * @default
  25547. */
  25548. this.padding = 0;
  25549. /**
  25550. * @property {Phaser.Point} prevPoint - The previous position of the pointer (we don't update the uniform if the same)
  25551. */
  25552. this.prevPoint = new Phaser.Point();
  25553. /*
  25554. * The supported types are: 1f, 1fv, 1i, 2f, 2fv, 2i, 2iv, 3f, 3fv, 3i, 3iv, 4f, 4fv, 4i, 4iv, mat2, mat3, mat4 and sampler2D.
  25555. */
  25556. var d = new Date();
  25557. /**
  25558. * @property {object} uniforms - Default uniform mappings. Compatible with ShaderToy and GLSLSandbox.
  25559. */
  25560. this.uniforms = {
  25561. resolution: { type: '2f', value: { x: 256, y: 256 }},
  25562. time: { type: '1f', value: 0 },
  25563. mouse: { type: '2f', value: { x: 0.0, y: 0.0 } },
  25564. date: { type: '4fv', value: [ d.getFullYear(), d.getMonth(), d.getDate(), d.getHours() *60 * 60 + d.getMinutes() * 60 + d.getSeconds() ] },
  25565. sampleRate: { type: '1f', value: 44100.0 },
  25566. iChannel0: { type: 'sampler2D', value: null, textureData: { repeat: true } },
  25567. iChannel1: { type: 'sampler2D', value: null, textureData: { repeat: true } },
  25568. iChannel2: { type: 'sampler2D', value: null, textureData: { repeat: true } },
  25569. iChannel3: { type: 'sampler2D', value: null, textureData: { repeat: true } }
  25570. };
  25571. // Copy over/replace any passed in the constructor
  25572. if (uniforms)
  25573. {
  25574. for (var key in uniforms)
  25575. {
  25576. this.uniforms[key] = uniforms[key];
  25577. }
  25578. }
  25579. /**
  25580. * @property {array|string} fragmentSrc - The fragment shader code.
  25581. */
  25582. this.fragmentSrc = fragmentSrc || '';
  25583. };
  25584. Phaser.Filter.prototype = {
  25585. /**
  25586. * Should be over-ridden.
  25587. * @method Phaser.Filter#init
  25588. */
  25589. init: function () {
  25590. // This should be over-ridden. Will receive a variable number of arguments.
  25591. },
  25592. /**
  25593. * Set the resolution uniforms on the filter.
  25594. * @method Phaser.Filter#setResolution
  25595. * @param {number} width - The width of the display.
  25596. * @param {number} height - The height of the display.
  25597. */
  25598. setResolution: function (width, height) {
  25599. this.uniforms.resolution.value.x = width;
  25600. this.uniforms.resolution.value.y = height;
  25601. },
  25602. /**
  25603. * Updates the filter.
  25604. * @method Phaser.Filter#update
  25605. * @param {Phaser.Pointer} [pointer] - A Pointer object to use for the filter. The coordinates are mapped to the mouse uniform.
  25606. */
  25607. update: function (pointer) {
  25608. if (typeof pointer !== 'undefined')
  25609. {
  25610. var x = pointer.x / this.game.width;
  25611. var y = 1 - pointer.y / this.game.height;
  25612. if (x !== this.prevPoint.x || y !== this.prevPoint.y)
  25613. {
  25614. this.uniforms.mouse.value.x = x.toFixed(2);
  25615. this.uniforms.mouse.value.y = y.toFixed(2);
  25616. this.prevPoint.set(x, y);
  25617. }
  25618. }
  25619. this.uniforms.time.value = this.game.time.totalElapsedSeconds();
  25620. },
  25621. /**
  25622. * Creates a new Phaser.Image object using a blank texture and assigns
  25623. * this Filter to it. The image is then added to the world.
  25624. *
  25625. * If you don't provide width and height values then Filter.width and Filter.height are used.
  25626. *
  25627. * If you do provide width and height values then this filter will be resized to match those
  25628. * values.
  25629. *
  25630. * @method Phaser.Filter#addToWorld
  25631. * @param {number} [x=0] - The x coordinate to place the Image at.
  25632. * @param {number} [y=0] - The y coordinate to place the Image at.
  25633. * @param {number} [width] - The width of the Image. If not specified (or null) it will use Filter.width. If specified Filter.width will be set to this value.
  25634. * @param {number} [height] - The height of the Image. If not specified (or null) it will use Filter.height. If specified Filter.height will be set to this value.
  25635. * @param {number} [anchorX=0] - Set the x anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right.
  25636. * @param {number} [anchorY=0] - Set the y anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right.
  25637. * @return {Phaser.Image} The newly added Image object.
  25638. */
  25639. addToWorld: function (x, y, width, height, anchorX, anchorY) {
  25640. if (anchorX === undefined) { anchorX = 0; }
  25641. if (anchorY === undefined) { anchorY = 0; }
  25642. if (width !== undefined && width !== null)
  25643. {
  25644. this.width = width;
  25645. }
  25646. else
  25647. {
  25648. width = this.width;
  25649. }
  25650. if (height !== undefined && height !== null)
  25651. {
  25652. this.height = height;
  25653. }
  25654. else
  25655. {
  25656. height = this.height;
  25657. }
  25658. var image = this.game.add.image(x, y, '__default');
  25659. image.width = width;
  25660. image.height = height;
  25661. image.anchor.set(anchorX, anchorY);
  25662. image.filters = [ this ];
  25663. return image;
  25664. },
  25665. /**
  25666. * Clear down this Filter and null out references
  25667. * @method Phaser.Filter#destroy
  25668. */
  25669. destroy: function () {
  25670. this.game = null;
  25671. }
  25672. };
  25673. Phaser.Filter.prototype.constructor = Phaser.Filter;
  25674. /**
  25675. * @name Phaser.Filter#width
  25676. * @property {number} width - The width (resolution uniform)
  25677. */
  25678. Object.defineProperty(Phaser.Filter.prototype, 'width', {
  25679. get: function() {
  25680. return this.uniforms.resolution.value.x;
  25681. },
  25682. set: function(value) {
  25683. this.uniforms.resolution.value.x = value;
  25684. }
  25685. });
  25686. /**
  25687. * @name Phaser.Filter#height
  25688. * @property {number} height - The height (resolution uniform)
  25689. */
  25690. Object.defineProperty(Phaser.Filter.prototype, 'height', {
  25691. get: function() {
  25692. return this.uniforms.resolution.value.y;
  25693. },
  25694. set: function(value) {
  25695. this.uniforms.resolution.value.y = value;
  25696. }
  25697. });
  25698. /**
  25699. * @author Richard Davey <rich@photonstorm.com>
  25700. * @copyright 2016 Photon Storm Ltd.
  25701. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  25702. */
  25703. /**
  25704. * This is a base Plugin template to use for any Phaser plugin development.
  25705. *
  25706. * @class Phaser.Plugin
  25707. * @constructor
  25708. * @param {Phaser.Game} game - A reference to the currently running game.
  25709. * @param {any} parent - The object that owns this plugin, usually Phaser.PluginManager.
  25710. */
  25711. Phaser.Plugin = function (game, parent) {
  25712. if (parent === undefined) { parent = null; }
  25713. /**
  25714. * @property {Phaser.Game} game - A reference to the currently running game.
  25715. */
  25716. this.game = game;
  25717. /**
  25718. * @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.
  25719. */
  25720. this.parent = parent;
  25721. /**
  25722. * @property {boolean} active - A Plugin with active=true has its preUpdate and update methods called by the parent, otherwise they are skipped.
  25723. * @default
  25724. */
  25725. this.active = false;
  25726. /**
  25727. * @property {boolean} visible - A Plugin with visible=true has its render and postRender methods called by the parent, otherwise they are skipped.
  25728. * @default
  25729. */
  25730. this.visible = false;
  25731. /**
  25732. * @property {boolean} hasPreUpdate - A flag to indicate if this plugin has a preUpdate method.
  25733. * @default
  25734. */
  25735. this.hasPreUpdate = false;
  25736. /**
  25737. * @property {boolean} hasUpdate - A flag to indicate if this plugin has an update method.
  25738. * @default
  25739. */
  25740. this.hasUpdate = false;
  25741. /**
  25742. * @property {boolean} hasPostUpdate - A flag to indicate if this plugin has a postUpdate method.
  25743. * @default
  25744. */
  25745. this.hasPostUpdate = false;
  25746. /**
  25747. * @property {boolean} hasRender - A flag to indicate if this plugin has a render method.
  25748. * @default
  25749. */
  25750. this.hasRender = false;
  25751. /**
  25752. * @property {boolean} hasPostRender - A flag to indicate if this plugin has a postRender method.
  25753. * @default
  25754. */
  25755. this.hasPostRender = false;
  25756. };
  25757. Phaser.Plugin.prototype = {
  25758. /**
  25759. * Pre-update is called at the very start of the update cycle, before any other subsystems have been updated (including Physics).
  25760. * It is only called if active is set to true.
  25761. * @method Phaser.Plugin#preUpdate
  25762. */
  25763. preUpdate: function () {
  25764. },
  25765. /**
  25766. * Update is called after all the core subsystems (Input, Tweens, Sound, etc) and the State have updated, but before the render.
  25767. * It is only called if active is set to true.
  25768. * @method Phaser.Plugin#update
  25769. */
  25770. update: function () {
  25771. },
  25772. /**
  25773. * Render is called right after the Game Renderer completes, but before the State.render.
  25774. * It is only called if visible is set to true.
  25775. * @method Phaser.Plugin#render
  25776. */
  25777. render: function () {
  25778. },
  25779. /**
  25780. * Post-render is called after the Game Renderer and State.render have run.
  25781. * It is only called if visible is set to true.
  25782. * @method Phaser.Plugin#postRender
  25783. */
  25784. postRender: function () {
  25785. },
  25786. /**
  25787. * Clear down this Plugin and null out references
  25788. * @method Phaser.Plugin#destroy
  25789. */
  25790. destroy: function () {
  25791. this.game = null;
  25792. this.parent = null;
  25793. this.active = false;
  25794. this.visible = false;
  25795. }
  25796. };
  25797. Phaser.Plugin.prototype.constructor = Phaser.Plugin;
  25798. /* jshint newcap: false */
  25799. /**
  25800. * @author Richard Davey <rich@photonstorm.com>
  25801. * @copyright 2016 Photon Storm Ltd.
  25802. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  25803. */
  25804. /**
  25805. * The Plugin Manager is responsible for the loading, running and unloading of Phaser Plugins.
  25806. *
  25807. * @class Phaser.PluginManager
  25808. * @constructor
  25809. * @param {Phaser.Game} game - A reference to the currently running game.
  25810. */
  25811. Phaser.PluginManager = function(game) {
  25812. /**
  25813. * @property {Phaser.Game} game - A reference to the currently running game.
  25814. */
  25815. this.game = game;
  25816. /**
  25817. * @property {Phaser.Plugin[]} plugins - An array of all the plugins being managed by this PluginManager.
  25818. */
  25819. this.plugins = [];
  25820. /**
  25821. * @property {number} _len - Internal cache var.
  25822. * @private
  25823. */
  25824. this._len = 0;
  25825. /**
  25826. * @property {number} _i - Internal cache var.
  25827. * @private
  25828. */
  25829. this._i = 0;
  25830. };
  25831. Phaser.PluginManager.prototype = {
  25832. /**
  25833. * Add a new Plugin into the PluginManager.
  25834. * The Plugin must have 2 properties: game and parent. Plugin.game is set to the game reference the PluginManager uses, and parent is set to the PluginManager.
  25835. *
  25836. * @method Phaser.PluginManager#add
  25837. * @param {object|Phaser.Plugin} plugin - The Plugin to add into the PluginManager. This can be a function or an existing object.
  25838. * @param {...*} parameter - Additional arguments that will be passed to the Plugin.init method.
  25839. * @return {Phaser.Plugin} The Plugin that was added to the manager.
  25840. */
  25841. add: function (plugin) {
  25842. var args = Array.prototype.slice.call(arguments, 1);
  25843. var result = false;
  25844. // Prototype?
  25845. if (typeof plugin === 'function')
  25846. {
  25847. plugin = new plugin(this.game, this);
  25848. }
  25849. else
  25850. {
  25851. plugin.game = this.game;
  25852. plugin.parent = this;
  25853. }
  25854. // Check for methods now to avoid having to do this every loop
  25855. if (typeof plugin['preUpdate'] === 'function')
  25856. {
  25857. plugin.hasPreUpdate = true;
  25858. result = true;
  25859. }
  25860. if (typeof plugin['update'] === 'function')
  25861. {
  25862. plugin.hasUpdate = true;
  25863. result = true;
  25864. }
  25865. if (typeof plugin['postUpdate'] === 'function')
  25866. {
  25867. plugin.hasPostUpdate = true;
  25868. result = true;
  25869. }
  25870. if (typeof plugin['render'] === 'function')
  25871. {
  25872. plugin.hasRender = true;
  25873. result = true;
  25874. }
  25875. if (typeof plugin['postRender'] === 'function')
  25876. {
  25877. plugin.hasPostRender = true;
  25878. result = true;
  25879. }
  25880. // The plugin must have at least one of the above functions to be added to the PluginManager.
  25881. if (result)
  25882. {
  25883. if (plugin.hasPreUpdate || plugin.hasUpdate || plugin.hasPostUpdate)
  25884. {
  25885. plugin.active = true;
  25886. }
  25887. if (plugin.hasRender || plugin.hasPostRender)
  25888. {
  25889. plugin.visible = true;
  25890. }
  25891. this._len = this.plugins.push(plugin);
  25892. // Allows plugins to run potentially destructive code outside of the constructor, and only if being added to the PluginManager
  25893. if (typeof plugin['init'] === 'function')
  25894. {
  25895. plugin.init.apply(plugin, args);
  25896. }
  25897. return plugin;
  25898. }
  25899. else
  25900. {
  25901. return null;
  25902. }
  25903. },
  25904. /**
  25905. * Remove a Plugin from the PluginManager. It calls Plugin.destroy on the plugin before removing it from the manager.
  25906. *
  25907. * @method Phaser.PluginManager#remove
  25908. * @param {Phaser.Plugin} plugin - The plugin to be removed.
  25909. */
  25910. remove: function (plugin) {
  25911. this._i = this._len;
  25912. while (this._i--)
  25913. {
  25914. if (this.plugins[this._i] === plugin)
  25915. {
  25916. plugin.destroy();
  25917. this.plugins.splice(this._i, 1);
  25918. this._len--;
  25919. return;
  25920. }
  25921. }
  25922. },
  25923. /**
  25924. * Remove all Plugins from the PluginManager. It calls Plugin.destroy on every plugin before removing it from the manager.
  25925. *
  25926. * @method Phaser.PluginManager#removeAll
  25927. */
  25928. removeAll: function() {
  25929. this._i = this._len;
  25930. while (this._i--)
  25931. {
  25932. this.plugins[this._i].destroy();
  25933. }
  25934. this.plugins.length = 0;
  25935. this._len = 0;
  25936. },
  25937. /**
  25938. * Pre-update is called at the very start of the update cycle, before any other subsystems have been updated (including Physics).
  25939. * It only calls plugins who have active=true.
  25940. *
  25941. * @method Phaser.PluginManager#preUpdate
  25942. */
  25943. preUpdate: function () {
  25944. this._i = this._len;
  25945. while (this._i--)
  25946. {
  25947. if (this.plugins[this._i].active && this.plugins[this._i].hasPreUpdate)
  25948. {
  25949. this.plugins[this._i].preUpdate();
  25950. }
  25951. }
  25952. },
  25953. /**
  25954. * Update is called after all the core subsystems (Input, Tweens, Sound, etc) and the State have updated, but before the render.
  25955. * It only calls plugins who have active=true.
  25956. *
  25957. * @method Phaser.PluginManager#update
  25958. */
  25959. update: function () {
  25960. this._i = this._len;
  25961. while (this._i--)
  25962. {
  25963. if (this.plugins[this._i].active && this.plugins[this._i].hasUpdate)
  25964. {
  25965. this.plugins[this._i].update();
  25966. }
  25967. }
  25968. },
  25969. /**
  25970. * PostUpdate is the last thing to be called before the world render.
  25971. * In particular, it is called after the world postUpdate, which means the camera has been adjusted.
  25972. * It only calls plugins who have active=true.
  25973. *
  25974. * @method Phaser.PluginManager#postUpdate
  25975. */
  25976. postUpdate: function () {
  25977. this._i = this._len;
  25978. while (this._i--)
  25979. {
  25980. if (this.plugins[this._i].active && this.plugins[this._i].hasPostUpdate)
  25981. {
  25982. this.plugins[this._i].postUpdate();
  25983. }
  25984. }
  25985. },
  25986. /**
  25987. * Render is called right after the Game Renderer completes, but before the State.render.
  25988. * It only calls plugins who have visible=true.
  25989. *
  25990. * @method Phaser.PluginManager#render
  25991. */
  25992. render: function () {
  25993. this._i = this._len;
  25994. while (this._i--)
  25995. {
  25996. if (this.plugins[this._i].visible && this.plugins[this._i].hasRender)
  25997. {
  25998. this.plugins[this._i].render();
  25999. }
  26000. }
  26001. },
  26002. /**
  26003. * Post-render is called after the Game Renderer and State.render have run.
  26004. * It only calls plugins who have visible=true.
  26005. *
  26006. * @method Phaser.PluginManager#postRender
  26007. */
  26008. postRender: function () {
  26009. this._i = this._len;
  26010. while (this._i--)
  26011. {
  26012. if (this.plugins[this._i].visible && this.plugins[this._i].hasPostRender)
  26013. {
  26014. this.plugins[this._i].postRender();
  26015. }
  26016. }
  26017. },
  26018. /**
  26019. * Clear down this PluginManager, calls destroy on every plugin and nulls out references.
  26020. *
  26021. * @method Phaser.PluginManager#destroy
  26022. */
  26023. destroy: function () {
  26024. this.removeAll();
  26025. this.game = null;
  26026. }
  26027. };
  26028. Phaser.PluginManager.prototype.constructor = Phaser.PluginManager;
  26029. /**
  26030. * @author Richard Davey <rich@photonstorm.com>
  26031. * @copyright 2016 Photon Storm Ltd.
  26032. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  26033. */
  26034. /**
  26035. * The Stage controls root level display objects upon which everything is displayed.
  26036. * It also handles browser visibility handling and the pausing due to loss of focus.
  26037. *
  26038. * @class Phaser.Stage
  26039. * @extends PIXI.DisplayObjectContainer
  26040. * @constructor
  26041. * @param {Phaser.Game} game - Game reference to the currently running game.
  26042. */
  26043. Phaser.Stage = function (game) {
  26044. /**
  26045. * @property {Phaser.Game} game - A reference to the currently running Game.
  26046. */
  26047. this.game = game;
  26048. PIXI.DisplayObjectContainer.call(this);
  26049. /**
  26050. * @property {string} name - The name of this object.
  26051. * @default
  26052. */
  26053. this.name = '_stage_root';
  26054. /**
  26055. * By default if the browser tab loses focus the game will pause.
  26056. * You can stop that behavior by setting this property to true.
  26057. * Note that the browser can still elect to pause your game if it wishes to do so,
  26058. * for example swapping to another browser tab. This will cause the RAF callback to halt,
  26059. * effectively pausing your game, even though no in-game pause event is triggered if you enable this property.
  26060. * @property {boolean} disableVisibilityChange
  26061. * @default
  26062. */
  26063. this.disableVisibilityChange = false;
  26064. /**
  26065. * @property {boolean} exists - If exists is true the Stage and all children are updated, otherwise it is skipped.
  26066. * @default
  26067. */
  26068. this.exists = true;
  26069. /**
  26070. * @property {PIXI.Matrix} worldTransform - Current transform of the object based on world (parent) factors
  26071. * @private
  26072. * @readOnly
  26073. */
  26074. this.worldTransform = new PIXI.Matrix();
  26075. /**
  26076. * @property {Phaser.Stage} stage - The stage reference (the Stage is its own stage)
  26077. * @private
  26078. * @readOnly
  26079. */
  26080. this.stage = this;
  26081. /**
  26082. * @property {number} currentRenderOrderID - Reset each frame, keeps a count of the total number of objects updated.
  26083. */
  26084. this.currentRenderOrderID = 0;
  26085. /**
  26086. * @property {string} hiddenVar - The page visibility API event name.
  26087. * @private
  26088. */
  26089. this._hiddenVar = 'hidden';
  26090. /**
  26091. * @property {function} _onChange - The blur/focus event handler.
  26092. * @private
  26093. */
  26094. this._onChange = null;
  26095. /**
  26096. * @property {number} _bgColor - Stage background color object. Populated by setBackgroundColor.
  26097. * @private
  26098. */
  26099. this._bgColor = { r: 0, g: 0, b: 0, a: 0, color: 0, rgba: '#000000' };
  26100. if (!this.game.transparent)
  26101. {
  26102. // transparent = 0,0,0,0 - otherwise r,g,b,1
  26103. this._bgColor.a = 1;
  26104. }
  26105. if (game.config)
  26106. {
  26107. this.parseConfig(game.config);
  26108. }
  26109. };
  26110. Phaser.Stage.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
  26111. Phaser.Stage.prototype.constructor = Phaser.Stage;
  26112. /**
  26113. * Parses a Game configuration object.
  26114. *
  26115. * @method Phaser.Stage#parseConfig
  26116. * @protected
  26117. * @param {object} config -The configuration object to parse.
  26118. */
  26119. Phaser.Stage.prototype.parseConfig = function (config) {
  26120. if (config['disableVisibilityChange'])
  26121. {
  26122. this.disableVisibilityChange = config['disableVisibilityChange'];
  26123. }
  26124. if (config['backgroundColor'])
  26125. {
  26126. this.setBackgroundColor(config['backgroundColor']);
  26127. }
  26128. };
  26129. /**
  26130. * Initialises the stage and adds the event listeners.
  26131. * @method Phaser.Stage#boot
  26132. * @private
  26133. */
  26134. Phaser.Stage.prototype.boot = function () {
  26135. Phaser.DOM.getOffset(this.game.canvas, this.offset);
  26136. Phaser.Canvas.setUserSelect(this.game.canvas, 'none');
  26137. Phaser.Canvas.setTouchAction(this.game.canvas, 'none');
  26138. this.checkVisibility();
  26139. };
  26140. /**
  26141. * This is called automatically after the plugins preUpdate and before the State.update.
  26142. * Most objects have preUpdate methods and it's where initial movement and positioning is done.
  26143. *
  26144. * @method Phaser.Stage#preUpdate
  26145. */
  26146. Phaser.Stage.prototype.preUpdate = function () {
  26147. this.currentRenderOrderID = 0;
  26148. // This can't loop in reverse, we need the orderID to be in sequence
  26149. for (var i = 0; i < this.children.length; i++)
  26150. {
  26151. this.children[i].preUpdate();
  26152. }
  26153. };
  26154. /**
  26155. * This is called automatically after the State.update, but before particles or plugins update.
  26156. *
  26157. * @method Phaser.Stage#update
  26158. */
  26159. Phaser.Stage.prototype.update = function () {
  26160. var i = this.children.length;
  26161. while (i--)
  26162. {
  26163. this.children[i].update();
  26164. }
  26165. };
  26166. /**
  26167. * This is called automatically before the renderer runs and after the plugins have updated.
  26168. * In postUpdate this is where all the final physics calculations and object positioning happens.
  26169. * The objects are processed in the order of the display list.
  26170. * The only exception to this is if the camera is following an object, in which case that is updated first.
  26171. *
  26172. * @method Phaser.Stage#postUpdate
  26173. */
  26174. Phaser.Stage.prototype.postUpdate = function () {
  26175. if (this.game.world.camera.target)
  26176. {
  26177. this.game.world.camera.target.postUpdate();
  26178. this.game.world.camera.update();
  26179. var i = this.children.length;
  26180. while (i--)
  26181. {
  26182. if (this.children[i] !== this.game.world.camera.target)
  26183. {
  26184. this.children[i].postUpdate();
  26185. }
  26186. }
  26187. }
  26188. else
  26189. {
  26190. this.game.world.camera.update();
  26191. var i = this.children.length;
  26192. while (i--)
  26193. {
  26194. this.children[i].postUpdate();
  26195. }
  26196. }
  26197. };
  26198. /**
  26199. * Updates the transforms for all objects on the display list.
  26200. * This overrides the Pixi default as we don't need the interactionManager, but do need the game property check.
  26201. *
  26202. * @method Phaser.Stage#updateTransform
  26203. */
  26204. Phaser.Stage.prototype.updateTransform = function () {
  26205. this.worldAlpha = 1;
  26206. for (var i = 0; i < this.children.length; i++)
  26207. {
  26208. this.children[i].updateTransform();
  26209. }
  26210. };
  26211. /**
  26212. * Starts a page visibility event listener running, or window.onpagehide/onpageshow if not supported by the browser.
  26213. * Also listens for window.onblur and window.onfocus.
  26214. *
  26215. * @method Phaser.Stage#checkVisibility
  26216. */
  26217. Phaser.Stage.prototype.checkVisibility = function () {
  26218. if (document.webkitHidden !== undefined)
  26219. {
  26220. this._hiddenVar = 'webkitvisibilitychange';
  26221. }
  26222. else if (document.mozHidden !== undefined)
  26223. {
  26224. this._hiddenVar = 'mozvisibilitychange';
  26225. }
  26226. else if (document.msHidden !== undefined)
  26227. {
  26228. this._hiddenVar = 'msvisibilitychange';
  26229. }
  26230. else if (document.hidden !== undefined)
  26231. {
  26232. this._hiddenVar = 'visibilitychange';
  26233. }
  26234. else
  26235. {
  26236. this._hiddenVar = null;
  26237. }
  26238. var _this = this;
  26239. this._onChange = function (event) {
  26240. return _this.visibilityChange(event);
  26241. };
  26242. // Does browser support it? If not (like in IE9 or old Android) we need to fall back to blur/focus
  26243. if (this._hiddenVar)
  26244. {
  26245. document.addEventListener(this._hiddenVar, this._onChange, false);
  26246. }
  26247. window.onblur = this._onChange;
  26248. window.onfocus = this._onChange;
  26249. window.onpagehide = this._onChange;
  26250. window.onpageshow = this._onChange;
  26251. if (this.game.device.cocoonJSApp)
  26252. {
  26253. CocoonJS.App.onSuspended.addEventListener(function () {
  26254. Phaser.Stage.prototype.visibilityChange.call(_this, { type: "pause" });
  26255. });
  26256. CocoonJS.App.onActivated.addEventListener(function () {
  26257. Phaser.Stage.prototype.visibilityChange.call(_this, { type: "resume" });
  26258. });
  26259. }
  26260. };
  26261. /**
  26262. * This method is called when the document visibility is changed.
  26263. *
  26264. * @method Phaser.Stage#visibilityChange
  26265. * @param {Event} event - Its type will be used to decide whether the game should be paused or not.
  26266. */
  26267. Phaser.Stage.prototype.visibilityChange = function (event) {
  26268. if (event.type === 'pagehide' || event.type === 'blur' || event.type === 'pageshow' || event.type === 'focus')
  26269. {
  26270. if (event.type === 'pagehide' || event.type === 'blur')
  26271. {
  26272. this.game.focusLoss(event);
  26273. }
  26274. else if (event.type === 'pageshow' || event.type === 'focus')
  26275. {
  26276. this.game.focusGain(event);
  26277. }
  26278. return;
  26279. }
  26280. if (this.disableVisibilityChange)
  26281. {
  26282. return;
  26283. }
  26284. if (document.hidden || document.mozHidden || document.msHidden || document.webkitHidden || event.type === "pause")
  26285. {
  26286. this.game.gamePaused(event);
  26287. }
  26288. else
  26289. {
  26290. this.game.gameResumed(event);
  26291. }
  26292. };
  26293. /**
  26294. * Sets the background color for the Stage.
  26295. *
  26296. * The color can be given as a hex string (`'#RRGGBB'`), a CSS color string (`'rgb(r,g,b)'`), or a numeric value (`0xRRGGBB`).
  26297. *
  26298. * An alpha channel is _not_ supported and will be ignored.
  26299. *
  26300. * If you've set your game to be transparent then calls to setBackgroundColor are ignored.
  26301. *
  26302. * @method Phaser.Stage#setBackgroundColor
  26303. * @param {number|string} color - The color of the background.
  26304. */
  26305. Phaser.Stage.prototype.setBackgroundColor = function (color) {
  26306. if (this.game.transparent) { return; }
  26307. Phaser.Color.valueToColor(color, this._bgColor);
  26308. Phaser.Color.updateColor(this._bgColor);
  26309. // For gl.clearColor (canvas uses _bgColor.rgba)
  26310. this._bgColor.r /= 255;
  26311. this._bgColor.g /= 255;
  26312. this._bgColor.b /= 255;
  26313. this._bgColor.a = 1;
  26314. };
  26315. /**
  26316. * Destroys the Stage and removes event listeners.
  26317. *
  26318. * @method Phaser.Stage#destroy
  26319. */
  26320. Phaser.Stage.prototype.destroy = function () {
  26321. if (this._hiddenVar)
  26322. {
  26323. document.removeEventListener(this._hiddenVar, this._onChange, false);
  26324. }
  26325. window.onpagehide = null;
  26326. window.onpageshow = null;
  26327. window.onblur = null;
  26328. window.onfocus = null;
  26329. };
  26330. /**
  26331. * @name Phaser.Stage#backgroundColor
  26332. * @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'
  26333. */
  26334. Object.defineProperty(Phaser.Stage.prototype, "backgroundColor", {
  26335. get: function () {
  26336. return this._bgColor.color;
  26337. },
  26338. set: function (color) {
  26339. this.setBackgroundColor(color);
  26340. }
  26341. });
  26342. /**
  26343. * Enable or disable texture smoothing for all objects on this Stage. Only works for bitmap/image textures. Smoothing is enabled by default.
  26344. *
  26345. * @name Phaser.Stage#smoothed
  26346. * @property {boolean} smoothed - Set to true to smooth all sprites rendered on this Stage, or false to disable smoothing (great for pixel art)
  26347. */
  26348. Object.defineProperty(Phaser.Stage.prototype, "smoothed", {
  26349. get: function () {
  26350. return PIXI.scaleModes.DEFAULT === PIXI.scaleModes.LINEAR;
  26351. },
  26352. set: function (value) {
  26353. if (value)
  26354. {
  26355. PIXI.scaleModes.DEFAULT = PIXI.scaleModes.LINEAR;
  26356. }
  26357. else
  26358. {
  26359. PIXI.scaleModes.DEFAULT = PIXI.scaleModes.NEAREST;
  26360. }
  26361. }
  26362. });
  26363. /**
  26364. * @author Richard Davey <rich@photonstorm.com>
  26365. * @copyright 2016 Photon Storm Ltd.
  26366. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  26367. */
  26368. /**
  26369. * A Group is a container for {@link DisplayObject display objects} including {@link Phaser.Sprite Sprites} and {@link Phaser.Image Images}.
  26370. *
  26371. * Groups form the logical tree structure of the display/scene graph where local transformations are applied to children.
  26372. * For instance, all children are also moved/rotated/scaled when the group is moved/rotated/scaled.
  26373. *
  26374. * In addition, Groups provides support for fast pooling and object recycling.
  26375. *
  26376. * Groups are also display objects and can be nested as children within other Groups.
  26377. *
  26378. * @class Phaser.Group
  26379. * @extends PIXI.DisplayObjectContainer
  26380. * @param {Phaser.Game} game - A reference to the currently running game.
  26381. * @param {DisplayObject|null} [parent=(game world)] - The parent Group (or other {@link DisplayObject}) that this group will be added to.
  26382. * If undefined/unspecified the Group will be added to the {@link Phaser.Game#world Game World}; if null the Group will not be added to any parent.
  26383. * @param {string} [name='group'] - A name for this group. Not used internally but useful for debugging.
  26384. * @param {boolean} [addToStage=false] - If true this group will be added directly to the Game.Stage instead of Game.World.
  26385. * @param {boolean} [enableBody=false] - If true all Sprites created with {@link #create} or {@link #createMulitple} will have a physics body created on them. Change the body type with {@link #physicsBodyType}.
  26386. * @param {integer} [physicsBodyType=0] - The physics body type to use when physics bodies are automatically added. See {@link #physicsBodyType} for values.
  26387. */
  26388. Phaser.Group = function (game, parent, name, addToStage, enableBody, physicsBodyType) {
  26389. if (addToStage === undefined) { addToStage = false; }
  26390. if (enableBody === undefined) { enableBody = false; }
  26391. if (physicsBodyType === undefined) { physicsBodyType = Phaser.Physics.ARCADE; }
  26392. /**
  26393. * A reference to the currently running Game.
  26394. * @property {Phaser.Game} game
  26395. * @protected
  26396. */
  26397. this.game = game;
  26398. if (parent === undefined)
  26399. {
  26400. parent = game.world;
  26401. }
  26402. /**
  26403. * A name for this group. Not used internally but useful for debugging.
  26404. * @property {string} name
  26405. */
  26406. this.name = name || 'group';
  26407. /**
  26408. * The z-depth value of this object within its parent container/Group - the World is a Group as well.
  26409. * This value must be unique for each child in a Group.
  26410. * @property {integer} z
  26411. * @readOnly
  26412. */
  26413. this.z = 0;
  26414. PIXI.DisplayObjectContainer.call(this);
  26415. if (addToStage)
  26416. {
  26417. this.game.stage.addChild(this);
  26418. this.z = this.game.stage.children.length;
  26419. }
  26420. else
  26421. {
  26422. if (parent)
  26423. {
  26424. parent.addChild(this);
  26425. this.z = parent.children.length;
  26426. }
  26427. }
  26428. /**
  26429. * Internal Phaser Type value.
  26430. * @property {integer} type
  26431. * @protected
  26432. */
  26433. this.type = Phaser.GROUP;
  26434. /**
  26435. * @property {number} physicsType - The const physics body type of this object.
  26436. * @readonly
  26437. */
  26438. this.physicsType = Phaser.GROUP;
  26439. /**
  26440. * The alive property is useful for Groups that are children of other Groups and need to be included/excluded in checks like forEachAlive.
  26441. * @property {boolean} alive
  26442. * @default
  26443. */
  26444. this.alive = true;
  26445. /**
  26446. * If exists is true the group is updated, otherwise it is skipped.
  26447. * @property {boolean} exists
  26448. * @default
  26449. */
  26450. this.exists = true;
  26451. /**
  26452. * A group with `ignoreDestroy` set to `true` ignores all calls to its `destroy` method.
  26453. * @property {boolean} ignoreDestroy
  26454. * @default
  26455. */
  26456. this.ignoreDestroy = false;
  26457. /**
  26458. * A Group is that has `pendingDestroy` set to `true` is flagged to have its destroy method
  26459. * called on the next logic update.
  26460. * You can set it directly to flag the Group to be destroyed on its next update.
  26461. *
  26462. * This is extremely useful if you wish to destroy a Group from within one of its own callbacks
  26463. * or a callback of one of its children.
  26464. *
  26465. * @property {boolean} pendingDestroy
  26466. */
  26467. this.pendingDestroy = false;
  26468. /**
  26469. * The type of objects that will be created when using {@link #create} or {@link #createMultiple}.
  26470. *
  26471. * Any object may be used but it should extend either Sprite or Image and accept the same constructor arguments:
  26472. * when a new object is created it is passed the following parameters to its constructor: `(game, x, y, key, frame)`.
  26473. *
  26474. * @property {object} classType
  26475. * @default {@link Phaser.Sprite}
  26476. */
  26477. this.classType = Phaser.Sprite;
  26478. /**
  26479. * The current display object that the group cursor is pointing to, if any. (Can be set manually.)
  26480. *
  26481. * The cursor is a way to iterate through the children in a Group using {@link #next} and {@link #previous}.
  26482. * @property {?DisplayObject} cursor
  26483. */
  26484. this.cursor = null;
  26485. /**
  26486. * If true all Sprites created by, or added to this group, will have a physics body enabled on them.
  26487. *
  26488. * The default body type is controlled with {@link #physicsBodyType}.
  26489. * @property {boolean} enableBody
  26490. */
  26491. this.enableBody = enableBody;
  26492. /**
  26493. * If true when a physics body is created (via {@link #enableBody}) it will create a physics debug object as well.
  26494. *
  26495. * This only works for P2 bodies.
  26496. * @property {boolean} enableBodyDebug
  26497. * @default
  26498. */
  26499. this.enableBodyDebug = false;
  26500. /**
  26501. * If {@link #enableBody} is true this is the type of physics body that is created on new Sprites.
  26502. *
  26503. * The valid values are {@link Phaser.Physics.ARCADE}, {@link Phaser.Physics.P2JS}, {@link Phaser.Physics.NINJA}, etc.
  26504. * @property {integer} physicsBodyType
  26505. */
  26506. this.physicsBodyType = physicsBodyType;
  26507. /**
  26508. * If this Group contains Arcade Physics Sprites you can set a custom sort direction via this property.
  26509. *
  26510. * It should be set to one of the Phaser.Physics.Arcade sort direction constants:
  26511. *
  26512. * Phaser.Physics.Arcade.SORT_NONE
  26513. * Phaser.Physics.Arcade.LEFT_RIGHT
  26514. * Phaser.Physics.Arcade.RIGHT_LEFT
  26515. * Phaser.Physics.Arcade.TOP_BOTTOM
  26516. * Phaser.Physics.Arcade.BOTTOM_TOP
  26517. *
  26518. * If set to `null` the Group will use whatever Phaser.Physics.Arcade.sortDirection is set to. This is the default behavior.
  26519. *
  26520. * @property {integer} physicsSortDirection
  26521. * @default
  26522. */
  26523. this.physicsSortDirection = null;
  26524. /**
  26525. * This signal is dispatched when the group is destroyed.
  26526. * @property {Phaser.Signal} onDestroy
  26527. */
  26528. this.onDestroy = new Phaser.Signal();
  26529. /**
  26530. * @property {integer} cursorIndex - The current index of the Group cursor. Advance it with Group.next.
  26531. * @readOnly
  26532. */
  26533. this.cursorIndex = 0;
  26534. /**
  26535. * A Group that is fixed to the camera uses its x/y coordinates as offsets from the top left of the camera. These are stored in Group.cameraOffset.
  26536. *
  26537. * Note that the cameraOffset values are in addition to any parent in the display list.
  26538. * So if this Group was in a Group that has x: 200, then this will be added to the cameraOffset.x
  26539. *
  26540. * @property {boolean} fixedToCamera
  26541. */
  26542. this.fixedToCamera = false;
  26543. /**
  26544. * If this object is {@link #fixedToCamera} then this stores the x/y position offset relative to the top-left of the camera view.
  26545. * If the parent of this Group is also `fixedToCamera` then the offset here is in addition to that and should typically be disabled.
  26546. * @property {Phaser.Point} cameraOffset
  26547. */
  26548. this.cameraOffset = new Phaser.Point();
  26549. /**
  26550. * The hash array is an array belonging to this Group into which you can add any of its children via Group.addToHash and Group.removeFromHash.
  26551. *
  26552. * Only children of this Group can be added to and removed from the hash.
  26553. *
  26554. * This hash is used automatically by Phaser Arcade Physics in order to perform non z-index based destructive sorting.
  26555. * However if you don't use Arcade Physics, or this isn't a physics enabled Group, then you can use the hash to perform your own
  26556. * sorting and filtering of Group children without touching their z-index (and therefore display draw order)
  26557. *
  26558. * @property {array} hash
  26559. */
  26560. this.hash = [];
  26561. /**
  26562. * The property on which children are sorted.
  26563. * @property {string} _sortProperty
  26564. * @private
  26565. */
  26566. this._sortProperty = 'z';
  26567. };
  26568. Phaser.Group.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
  26569. Phaser.Group.prototype.constructor = Phaser.Group;
  26570. /**
  26571. * A returnType value, as specified in {@link #iterate} eg.
  26572. * @constant
  26573. * @type {integer}
  26574. */
  26575. Phaser.Group.RETURN_NONE = 0;
  26576. /**
  26577. * A returnType value, as specified in {@link #iterate} eg.
  26578. * @constant
  26579. * @type {integer}
  26580. */
  26581. Phaser.Group.RETURN_TOTAL = 1;
  26582. /**
  26583. * A returnType value, as specified in {@link #iterate} eg.
  26584. * @constant
  26585. * @type {integer}
  26586. */
  26587. Phaser.Group.RETURN_CHILD = 2;
  26588. /**
  26589. * A sort ordering value, as specified in {@link #sort} eg.
  26590. * @constant
  26591. * @type {integer}
  26592. */
  26593. Phaser.Group.SORT_ASCENDING = -1;
  26594. /**
  26595. * A sort ordering value, as specified in {@link #sort} eg.
  26596. * @constant
  26597. * @type {integer}
  26598. */
  26599. Phaser.Group.SORT_DESCENDING = 1;
  26600. /**
  26601. * Adds an existing object as the top child in this group.
  26602. *
  26603. * The child is automatically added to the top of the group and is displayed on top of every previous child.
  26604. *
  26605. * If Group.enableBody is set then a physics body will be created on the object, so long as one does not already exist.
  26606. *
  26607. * Use {@link #addAt} to control where a child is added. Use {@link #create} to create and add a new child.
  26608. *
  26609. * @method Phaser.Group#add
  26610. * @param {DisplayObject} child - The display object to add as a child.
  26611. * @param {boolean} [silent=false] - If true the child will not dispatch the `onAddedToGroup` event.
  26612. * @return {DisplayObject} The child that was added to the group.
  26613. */
  26614. Phaser.Group.prototype.add = function (child, silent) {
  26615. if (silent === undefined) { silent = false; }
  26616. if (child.parent !== this)
  26617. {
  26618. if (child.body && child.parent && child.parent.hash)
  26619. {
  26620. child.parent.removeFromHash(child);
  26621. }
  26622. child.z = this.children.length;
  26623. this.addChild(child);
  26624. if (this.enableBody && child.body === null)
  26625. {
  26626. this.game.physics.enable(child, this.physicsBodyType);
  26627. }
  26628. else if (child.body)
  26629. {
  26630. this.addToHash(child);
  26631. }
  26632. if (!silent && child.events)
  26633. {
  26634. child.events.onAddedToGroup$dispatch(child, this);
  26635. }
  26636. if (this.cursor === null)
  26637. {
  26638. this.cursor = child;
  26639. }
  26640. }
  26641. return child;
  26642. };
  26643. /**
  26644. * Adds a child of this Group into the hash array.
  26645. * This call will return false if the child is not a child of this Group, or is already in the hash.
  26646. *
  26647. * @method Phaser.Group#addToHash
  26648. * @param {DisplayObject} child - The display object to add to this Groups hash. Must be a member of this Group already and not present in the hash.
  26649. * @return {boolean} True if the child was successfully added to the hash, otherwise false.
  26650. */
  26651. Phaser.Group.prototype.addToHash = function (child) {
  26652. if (child.parent === this)
  26653. {
  26654. var index = this.hash.indexOf(child);
  26655. if (index === -1)
  26656. {
  26657. this.hash.push(child);
  26658. return true;
  26659. }
  26660. }
  26661. return false;
  26662. };
  26663. /**
  26664. * Removes a child of this Group from the hash array.
  26665. * This call will return false if the child is not in the hash.
  26666. *
  26667. * @method Phaser.Group#removeFromHash
  26668. * @param {DisplayObject} child - The display object to remove from this Groups hash. Must be a member of this Group and in the hash.
  26669. * @return {boolean} True if the child was successfully removed from the hash, otherwise false.
  26670. */
  26671. Phaser.Group.prototype.removeFromHash = function (child) {
  26672. if (child)
  26673. {
  26674. var index = this.hash.indexOf(child);
  26675. if (index !== -1)
  26676. {
  26677. this.hash.splice(index, 1);
  26678. return true;
  26679. }
  26680. }
  26681. return false;
  26682. };
  26683. /**
  26684. * Adds an array of existing Display Objects to this Group.
  26685. *
  26686. * The Display Objects are automatically added to the top of this Group, and will render on-top of everything already in this Group.
  26687. *
  26688. * As well as an array you can also pass another Group as the first argument. In this case all of the children from that
  26689. * Group will be removed from it and added into this Group.
  26690. *
  26691. * @method Phaser.Group#addMultiple
  26692. * @param {DisplayObject[]|Phaser.Group} children - An array of display objects or a Phaser.Group. If a Group is given then *all* children will be moved from it.
  26693. * @param {boolean} [silent=false] - If true the children will not dispatch the `onAddedToGroup` event.
  26694. * @return {DisplayObject[]|Phaser.Group} The array of children or Group of children that were added to this Group.
  26695. */
  26696. Phaser.Group.prototype.addMultiple = function (children, silent) {
  26697. if (children instanceof Phaser.Group)
  26698. {
  26699. children.moveAll(this, silent);
  26700. }
  26701. else if (Array.isArray(children))
  26702. {
  26703. for (var i = 0; i < children.length; i++)
  26704. {
  26705. this.add(children[i], silent);
  26706. }
  26707. }
  26708. return children;
  26709. };
  26710. /**
  26711. * Adds an existing object to this group.
  26712. *
  26713. * The child is added to the group at the location specified by the index value, this allows you to control child ordering.
  26714. *
  26715. * @method Phaser.Group#addAt
  26716. * @param {DisplayObject} child - The display object to add as a child.
  26717. * @param {integer} [index=0] - The index within the group to insert the child to.
  26718. * @param {boolean} [silent=false] - If true the child will not dispatch the `onAddedToGroup` event.
  26719. * @return {DisplayObject} The child that was added to the group.
  26720. */
  26721. Phaser.Group.prototype.addAt = function (child, index, silent) {
  26722. if (silent === undefined) { silent = false; }
  26723. if (child.parent !== this)
  26724. {
  26725. if (child.body && child.parent)
  26726. {
  26727. child.parent.removeFromHash(child);
  26728. }
  26729. this.addChildAt(child, index);
  26730. this.updateZ();
  26731. if (this.enableBody && child.body === null)
  26732. {
  26733. this.game.physics.enable(child, this.physicsBodyType);
  26734. }
  26735. else if (child.body)
  26736. {
  26737. this.addToHash(child);
  26738. }
  26739. if (!silent && child.events)
  26740. {
  26741. child.events.onAddedToGroup$dispatch(child, this);
  26742. }
  26743. if (this.cursor === null)
  26744. {
  26745. this.cursor = child;
  26746. }
  26747. }
  26748. return child;
  26749. };
  26750. /**
  26751. * Returns the child found at the given index within this group.
  26752. *
  26753. * @method Phaser.Group#getAt
  26754. * @param {integer} index - The index to return the child from.
  26755. * @return {DisplayObject|integer} The child that was found at the given index, or -1 for an invalid index.
  26756. */
  26757. Phaser.Group.prototype.getAt = function (index) {
  26758. if (index < 0 || index >= this.children.length)
  26759. {
  26760. return -1;
  26761. }
  26762. else
  26763. {
  26764. return this.getChildAt(index);
  26765. }
  26766. };
  26767. /**
  26768. * Creates a new Phaser.Sprite object and adds it to the top of this group.
  26769. *
  26770. * Use {@link #classType} to change the type of object created.
  26771. *
  26772. * @method Phaser.Group#create
  26773. * @param {number} x - The x coordinate to display the newly created Sprite at. The value is in relation to the group.x point.
  26774. * @param {number} y - The y coordinate to display the newly created Sprite at. The value is in relation to the group.y point.
  26775. * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|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 Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture.
  26776. * @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.
  26777. * @param {boolean} [exists=true] - The default exists state of the Sprite.
  26778. * @return {DisplayObject} The child that was created: will be a {@link Phaser.Sprite} unless {@link #classType} has been changed.
  26779. */
  26780. Phaser.Group.prototype.create = function (x, y, key, frame, exists) {
  26781. if (exists === undefined) { exists = true; }
  26782. var child = new this.classType(this.game, x, y, key, frame);
  26783. child.exists = exists;
  26784. child.visible = exists;
  26785. child.alive = exists;
  26786. child.z = this.children.length;
  26787. this.addChild(child);
  26788. if (this.enableBody)
  26789. {
  26790. this.game.physics.enable(child, this.physicsBodyType, this.enableBodyDebug);
  26791. }
  26792. if (child.events)
  26793. {
  26794. child.events.onAddedToGroup$dispatch(child, this);
  26795. }
  26796. if (this.cursor === null)
  26797. {
  26798. this.cursor = child;
  26799. }
  26800. return child;
  26801. };
  26802. /**
  26803. * Creates multiple Phaser.Sprite objects and adds them to the top of this group.
  26804. *
  26805. * Useful if you need to quickly generate a pool of identical sprites, such as bullets.
  26806. *
  26807. * By default the sprites will be set to not exist and will be positioned at 0, 0 (relative to the group.x/y).
  26808. * Use {@link #classType} to change the type of object created.
  26809. *
  26810. * @method Phaser.Group#createMultiple
  26811. * @param {integer} quantity - The number of Sprites to create.
  26812. * @param {string} key - The Game.cache key of the image that this Sprite will use.
  26813. * @param {integer|string} [frame] - If the Sprite image contains multiple frames you can specify which one to use here.
  26814. * @param {boolean} [exists=false] - The default exists state of the Sprite.
  26815. */
  26816. Phaser.Group.prototype.createMultiple = function (quantity, key, frame, exists) {
  26817. if (exists === undefined) { exists = false; }
  26818. for (var i = 0; i < quantity; i++)
  26819. {
  26820. this.create(0, 0, key, frame, exists);
  26821. }
  26822. };
  26823. /**
  26824. * Internal method that re-applies all of the children's Z values.
  26825. *
  26826. * This must be called whenever children ordering is altered so that their `z` indices are correctly updated.
  26827. *
  26828. * @method Phaser.Group#updateZ
  26829. * @protected
  26830. */
  26831. Phaser.Group.prototype.updateZ = function () {
  26832. var i = this.children.length;
  26833. while (i--)
  26834. {
  26835. this.children[i].z = i;
  26836. }
  26837. };
  26838. /**
  26839. * Sets the group cursor to the first child in the group.
  26840. *
  26841. * If the optional index parameter is given it sets the cursor to the object at that index instead.
  26842. *
  26843. * @method Phaser.Group#resetCursor
  26844. * @param {integer} [index=0] - Set the cursor to point to a specific index.
  26845. * @return {any} The child the cursor now points to.
  26846. */
  26847. Phaser.Group.prototype.resetCursor = function (index) {
  26848. if (index === undefined) { index = 0; }
  26849. if (index > this.children.length - 1)
  26850. {
  26851. index = 0;
  26852. }
  26853. if (this.cursor)
  26854. {
  26855. this.cursorIndex = index;
  26856. this.cursor = this.children[this.cursorIndex];
  26857. return this.cursor;
  26858. }
  26859. };
  26860. /**
  26861. * Advances the group cursor to the next (higher) object in the group.
  26862. *
  26863. * If the cursor is at the end of the group (top child) it is moved the start of the group (bottom child).
  26864. *
  26865. * @method Phaser.Group#next
  26866. * @return {any} The child the cursor now points to.
  26867. */
  26868. Phaser.Group.prototype.next = function () {
  26869. if (this.cursor)
  26870. {
  26871. // Wrap the cursor?
  26872. if (this.cursorIndex >= this.children.length - 1)
  26873. {
  26874. this.cursorIndex = 0;
  26875. }
  26876. else
  26877. {
  26878. this.cursorIndex++;
  26879. }
  26880. this.cursor = this.children[this.cursorIndex];
  26881. return this.cursor;
  26882. }
  26883. };
  26884. /**
  26885. * Moves the group cursor to the previous (lower) child in the group.
  26886. *
  26887. * If the cursor is at the start of the group (bottom child) it is moved to the end (top child).
  26888. *
  26889. * @method Phaser.Group#previous
  26890. * @return {any} The child the cursor now points to.
  26891. */
  26892. Phaser.Group.prototype.previous = function () {
  26893. if (this.cursor)
  26894. {
  26895. // Wrap the cursor?
  26896. if (this.cursorIndex === 0)
  26897. {
  26898. this.cursorIndex = this.children.length - 1;
  26899. }
  26900. else
  26901. {
  26902. this.cursorIndex--;
  26903. }
  26904. this.cursor = this.children[this.cursorIndex];
  26905. return this.cursor;
  26906. }
  26907. };
  26908. /**
  26909. * Swaps the position of two children in this group.
  26910. *
  26911. * Both children must be in this group, a child cannot be swapped with itself, and unparented children cannot be swapped.
  26912. *
  26913. * @method Phaser.Group#swap
  26914. * @param {any} child1 - The first child to swap.
  26915. * @param {any} child2 - The second child to swap.
  26916. */
  26917. Phaser.Group.prototype.swap = function (child1, child2) {
  26918. this.swapChildren(child1, child2);
  26919. this.updateZ();
  26920. };
  26921. /**
  26922. * Brings the given child to the top of this group so it renders above all other children.
  26923. *
  26924. * @method Phaser.Group#bringToTop
  26925. * @param {any} child - The child to bring to the top of this group.
  26926. * @return {any} The child that was moved.
  26927. */
  26928. Phaser.Group.prototype.bringToTop = function (child) {
  26929. if (child.parent === this && this.getIndex(child) < this.children.length)
  26930. {
  26931. this.remove(child, false, true);
  26932. this.add(child, true);
  26933. }
  26934. return child;
  26935. };
  26936. /**
  26937. * Sends the given child to the bottom of this group so it renders below all other children.
  26938. *
  26939. * @method Phaser.Group#sendToBack
  26940. * @param {any} child - The child to send to the bottom of this group.
  26941. * @return {any} The child that was moved.
  26942. */
  26943. Phaser.Group.prototype.sendToBack = function (child) {
  26944. if (child.parent === this && this.getIndex(child) > 0)
  26945. {
  26946. this.remove(child, false, true);
  26947. this.addAt(child, 0, true);
  26948. }
  26949. return child;
  26950. };
  26951. /**
  26952. * Moves the given child up one place in this group unless it's already at the top.
  26953. *
  26954. * @method Phaser.Group#moveUp
  26955. * @param {any} child - The child to move up in the group.
  26956. * @return {any} The child that was moved.
  26957. */
  26958. Phaser.Group.prototype.moveUp = function (child) {
  26959. if (child.parent === this && this.getIndex(child) < this.children.length - 1)
  26960. {
  26961. var a = this.getIndex(child);
  26962. var b = this.getAt(a + 1);
  26963. if (b)
  26964. {
  26965. this.swap(child, b);
  26966. }
  26967. }
  26968. return child;
  26969. };
  26970. /**
  26971. * Moves the given child down one place in this group unless it's already at the bottom.
  26972. *
  26973. * @method Phaser.Group#moveDown
  26974. * @param {any} child - The child to move down in the group.
  26975. * @return {any} The child that was moved.
  26976. */
  26977. Phaser.Group.prototype.moveDown = function (child) {
  26978. if (child.parent === this && this.getIndex(child) > 0)
  26979. {
  26980. var a = this.getIndex(child);
  26981. var b = this.getAt(a - 1);
  26982. if (b)
  26983. {
  26984. this.swap(child, b);
  26985. }
  26986. }
  26987. return child;
  26988. };
  26989. /**
  26990. * Positions the child found at the given index within this group to the given x and y coordinates.
  26991. *
  26992. * @method Phaser.Group#xy
  26993. * @param {integer} index - The index of the child in the group to set the position of.
  26994. * @param {number} x - The new x position of the child.
  26995. * @param {number} y - The new y position of the child.
  26996. */
  26997. Phaser.Group.prototype.xy = function (index, x, y) {
  26998. if (index < 0 || index > this.children.length)
  26999. {
  27000. return -1;
  27001. }
  27002. else
  27003. {
  27004. this.getChildAt(index).x = x;
  27005. this.getChildAt(index).y = y;
  27006. }
  27007. };
  27008. /**
  27009. * Reverses all children in this group.
  27010. *
  27011. * This operation applies only to immediate children and does not propagate to subgroups.
  27012. *
  27013. * @method Phaser.Group#reverse
  27014. */
  27015. Phaser.Group.prototype.reverse = function () {
  27016. this.children.reverse();
  27017. this.updateZ();
  27018. };
  27019. /**
  27020. * Get the index position of the given child in this group, which should match the child's `z` property.
  27021. *
  27022. * @method Phaser.Group#getIndex
  27023. * @param {any} child - The child to get the index for.
  27024. * @return {integer} The index of the child or -1 if it's not a member of this group.
  27025. */
  27026. Phaser.Group.prototype.getIndex = function (child) {
  27027. return this.children.indexOf(child);
  27028. };
  27029. /**
  27030. * Searches the Group for the first instance of a child with the `name`
  27031. * property matching the given argument. Should more than one child have
  27032. * the same name only the first instance is returned.
  27033. *
  27034. * @method Phaser.Group#getByName
  27035. * @param {string} name - The name to search for.
  27036. * @return {any} The first child with a matching name, or null if none were found.
  27037. */
  27038. Phaser.Group.prototype.getByName = function (name) {
  27039. for (var i = 0; i < this.children.length; i++)
  27040. {
  27041. if (this.children[i].name === name)
  27042. {
  27043. return this.children[i];
  27044. }
  27045. }
  27046. return null;
  27047. };
  27048. /**
  27049. * Replaces a child of this group with the given newChild. The newChild cannot be a member of this group.
  27050. *
  27051. * @method Phaser.Group#replace
  27052. * @param {any} oldChild - The child in this group that will be replaced.
  27053. * @param {any} newChild - The child to be inserted into this group.
  27054. * @return {any} Returns the oldChild that was replaced within this group.
  27055. */
  27056. Phaser.Group.prototype.replace = function (oldChild, newChild) {
  27057. var index = this.getIndex(oldChild);
  27058. if (index !== -1)
  27059. {
  27060. if (newChild.parent)
  27061. {
  27062. if (newChild.parent instanceof Phaser.Group)
  27063. {
  27064. newChild.parent.remove(newChild);
  27065. }
  27066. else
  27067. {
  27068. newChild.parent.removeChild(newChild);
  27069. }
  27070. }
  27071. this.remove(oldChild);
  27072. this.addAt(newChild, index);
  27073. return oldChild;
  27074. }
  27075. };
  27076. /**
  27077. * Checks if the child has the given property.
  27078. *
  27079. * Will scan up to 4 levels deep only.
  27080. *
  27081. * @method Phaser.Group#hasProperty
  27082. * @param {any} child - The child to check for the existance of the property on.
  27083. * @param {string[]} key - An array of strings that make up the property.
  27084. * @return {boolean} True if the child has the property, otherwise false.
  27085. */
  27086. Phaser.Group.prototype.hasProperty = function (child, key) {
  27087. var len = key.length;
  27088. if (len === 1 && key[0] in child)
  27089. {
  27090. return true;
  27091. }
  27092. else if (len === 2 && key[0] in child && key[1] in child[key[0]])
  27093. {
  27094. return true;
  27095. }
  27096. else if (len === 3 && key[0] in child && key[1] in child[key[0]] && key[2] in child[key[0]][key[1]])
  27097. {
  27098. return true;
  27099. }
  27100. else if (len === 4 && key[0] in child && key[1] in child[key[0]] && key[2] in child[key[0]][key[1]] && key[3] in child[key[0]][key[1]][key[2]])
  27101. {
  27102. return true;
  27103. }
  27104. return false;
  27105. };
  27106. /**
  27107. * Sets a property to the given value on the child. The operation parameter controls how the value is set.
  27108. *
  27109. * The operations are:
  27110. * - 0: set the existing value to the given value; if force is `true` a new property will be created if needed
  27111. * - 1: will add the given value to the value already present.
  27112. * - 2: will subtract the given value from the value already present.
  27113. * - 3: will multiply the value already present by the given value.
  27114. * - 4: will divide the value already present by the given value.
  27115. *
  27116. * @method Phaser.Group#setProperty
  27117. * @param {any} child - The child to set the property value on.
  27118. * @param {array} key - An array of strings that make up the property that will be set.
  27119. * @param {any} value - The value that will be set.
  27120. * @param {integer} [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.
  27121. * @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set.
  27122. * @return {boolean} True if the property was set, false if not.
  27123. */
  27124. Phaser.Group.prototype.setProperty = function (child, key, value, operation, force) {
  27125. if (force === undefined) { force = false; }
  27126. operation = operation || 0;
  27127. // As ugly as this approach looks, and although it's limited to a depth of only 4, it's much faster than a for loop or object iteration.
  27128. // 0 = Equals
  27129. // 1 = Add
  27130. // 2 = Subtract
  27131. // 3 = Multiply
  27132. // 4 = Divide
  27133. // We can't force a property in and the child doesn't have it, so abort.
  27134. // Equally we can't add, subtract, multiply or divide a property value if it doesn't exist, so abort in those cases too.
  27135. if (!this.hasProperty(child, key) && (!force || operation > 0))
  27136. {
  27137. return false;
  27138. }
  27139. var len = key.length;
  27140. if (len === 1)
  27141. {
  27142. if (operation === 0) { child[key[0]] = value; }
  27143. else if (operation == 1) { child[key[0]] += value; }
  27144. else if (operation == 2) { child[key[0]] -= value; }
  27145. else if (operation == 3) { child[key[0]] *= value; }
  27146. else if (operation == 4) { child[key[0]] /= value; }
  27147. }
  27148. else if (len === 2)
  27149. {
  27150. if (operation === 0) { child[key[0]][key[1]] = value; }
  27151. else if (operation == 1) { child[key[0]][key[1]] += value; }
  27152. else if (operation == 2) { child[key[0]][key[1]] -= value; }
  27153. else if (operation == 3) { child[key[0]][key[1]] *= value; }
  27154. else if (operation == 4) { child[key[0]][key[1]] /= value; }
  27155. }
  27156. else if (len === 3)
  27157. {
  27158. if (operation === 0) { child[key[0]][key[1]][key[2]] = value; }
  27159. else if (operation == 1) { child[key[0]][key[1]][key[2]] += value; }
  27160. else if (operation == 2) { child[key[0]][key[1]][key[2]] -= value; }
  27161. else if (operation == 3) { child[key[0]][key[1]][key[2]] *= value; }
  27162. else if (operation == 4) { child[key[0]][key[1]][key[2]] /= value; }
  27163. }
  27164. else if (len === 4)
  27165. {
  27166. if (operation === 0) { child[key[0]][key[1]][key[2]][key[3]] = value; }
  27167. else if (operation == 1) { child[key[0]][key[1]][key[2]][key[3]] += value; }
  27168. else if (operation == 2) { child[key[0]][key[1]][key[2]][key[3]] -= value; }
  27169. else if (operation == 3) { child[key[0]][key[1]][key[2]][key[3]] *= value; }
  27170. else if (operation == 4) { child[key[0]][key[1]][key[2]][key[3]] /= value; }
  27171. }
  27172. return true;
  27173. };
  27174. /**
  27175. * Checks a property for the given value on the child.
  27176. *
  27177. * @method Phaser.Group#checkProperty
  27178. * @param {any} child - The child to check the property value on.
  27179. * @param {array} key - An array of strings that make up the property that will be set.
  27180. * @param {any} value - The value that will be checked.
  27181. * @param {boolean} [force=false] - If `force` is true then the property will be checked on the child regardless if it already exists or not. If true and the property doesn't exist, false will be returned.
  27182. * @return {boolean} True if the property was was equal to value, false if not.
  27183. */
  27184. Phaser.Group.prototype.checkProperty = function (child, key, value, force) {
  27185. if (force === undefined) { force = false; }
  27186. // We can't force a property in and the child doesn't have it, so abort.
  27187. if (!Phaser.Utils.getProperty(child, key) && force)
  27188. {
  27189. return false;
  27190. }
  27191. if (Phaser.Utils.getProperty(child, key) !== value)
  27192. {
  27193. return false;
  27194. }
  27195. return true;
  27196. };
  27197. /**
  27198. * Quickly set a property on a single child of this group to a new value.
  27199. *
  27200. * The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication.
  27201. *
  27202. * @method Phaser.Group#set
  27203. * @param {Phaser.Sprite} child - The child to set the property on.
  27204. * @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x'
  27205. * @param {any} value - The value that will be set.
  27206. * @param {boolean} [checkAlive=false] - If set then the child will only be updated if alive=true.
  27207. * @param {boolean} [checkVisible=false] - If set then the child will only be updated if visible=true.
  27208. * @param {integer} [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.
  27209. * @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set.
  27210. * @return {boolean} True if the property was set, false if not.
  27211. */
  27212. Phaser.Group.prototype.set = function (child, key, value, checkAlive, checkVisible, operation, force) {
  27213. if (force === undefined) { force = false; }
  27214. key = key.split('.');
  27215. if (checkAlive === undefined) { checkAlive = false; }
  27216. if (checkVisible === undefined) { checkVisible = false; }
  27217. if ((checkAlive === false || (checkAlive && child.alive)) && (checkVisible === false || (checkVisible && child.visible)))
  27218. {
  27219. return this.setProperty(child, key, value, operation, force);
  27220. }
  27221. };
  27222. /**
  27223. * Quickly set the same property across all children of this group to a new value.
  27224. *
  27225. * This call doesn't descend down children, so if you have a Group inside of this group, the property will be set on the group but not its children.
  27226. * If you need that ability please see `Group.setAllChildren`.
  27227. *
  27228. * The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication.
  27229. *
  27230. * @method Phaser.Group#setAll
  27231. * @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x'
  27232. * @param {any} value - The value that will be set.
  27233. * @param {boolean} [checkAlive=false] - If set then only children with alive=true will be updated. This includes any Groups that are children.
  27234. * @param {boolean} [checkVisible=false] - If set then only children with visible=true will be updated. This includes any Groups that are children.
  27235. * @param {integer} [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.
  27236. * @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set.
  27237. */
  27238. Phaser.Group.prototype.setAll = function (key, value, checkAlive, checkVisible, operation, force) {
  27239. if (checkAlive === undefined) { checkAlive = false; }
  27240. if (checkVisible === undefined) { checkVisible = false; }
  27241. if (force === undefined) { force = false; }
  27242. key = key.split('.');
  27243. operation = operation || 0;
  27244. for (var i = 0; i < this.children.length; i++)
  27245. {
  27246. if ((!checkAlive || (checkAlive && this.children[i].alive)) && (!checkVisible || (checkVisible && this.children[i].visible)))
  27247. {
  27248. this.setProperty(this.children[i], key, value, operation, force);
  27249. }
  27250. }
  27251. };
  27252. /**
  27253. * Quickly set the same property across all children of this group, and any child Groups, to a new value.
  27254. *
  27255. * If this group contains other Groups then the same property is set across their children as well, iterating down until it reaches the bottom.
  27256. * Unlike with `setAll` the property is NOT set on child Groups itself.
  27257. *
  27258. * The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication.
  27259. *
  27260. * @method Phaser.Group#setAllChildren
  27261. * @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x'
  27262. * @param {any} value - The value that will be set.
  27263. * @param {boolean} [checkAlive=false] - If set then only children with alive=true will be updated. This includes any Groups that are children.
  27264. * @param {boolean} [checkVisible=false] - If set then only children with visible=true will be updated. This includes any Groups that are children.
  27265. * @param {integer} [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.
  27266. * @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set.
  27267. */
  27268. Phaser.Group.prototype.setAllChildren = function (key, value, checkAlive, checkVisible, operation, force) {
  27269. if (checkAlive === undefined) { checkAlive = false; }
  27270. if (checkVisible === undefined) { checkVisible = false; }
  27271. if (force === undefined) { force = false; }
  27272. operation = operation || 0;
  27273. for (var i = 0; i < this.children.length; i++)
  27274. {
  27275. if ((!checkAlive || (checkAlive && this.children[i].alive)) && (!checkVisible || (checkVisible && this.children[i].visible)))
  27276. {
  27277. if (this.children[i] instanceof Phaser.Group)
  27278. {
  27279. this.children[i].setAllChildren(key, value, checkAlive, checkVisible, operation, force);
  27280. }
  27281. else
  27282. {
  27283. this.setProperty(this.children[i], key.split('.'), value, operation, force);
  27284. }
  27285. }
  27286. }
  27287. };
  27288. /**
  27289. * Quickly check that the same property across all children of this group is equal to the given value.
  27290. *
  27291. * This call doesn't descend down children, so if you have a Group inside of this group, the property will be checked on the group but not its children.
  27292. *
  27293. * @method Phaser.Group#checkAll
  27294. * @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x'
  27295. * @param {any} value - The value that will be checked.
  27296. * @param {boolean} [checkAlive=false] - If set then only children with alive=true will be checked. This includes any Groups that are children.
  27297. * @param {boolean} [checkVisible=false] - If set then only children with visible=true will be checked. This includes any Groups that are children.
  27298. * @param {boolean} [force=false] - If `force` is true then the property will be checked on the child regardless if it already exists or not. If true and the property doesn't exist, false will be returned.
  27299. */
  27300. Phaser.Group.prototype.checkAll = function (key, value, checkAlive, checkVisible, force) {
  27301. if (checkAlive === undefined) { checkAlive = false; }
  27302. if (checkVisible === undefined) { checkVisible = false; }
  27303. if (force === undefined) { force = false; }
  27304. for (var i = 0; i < this.children.length; i++)
  27305. {
  27306. if ((!checkAlive || (checkAlive && this.children[i].alive)) && (!checkVisible || (checkVisible && this.children[i].visible)))
  27307. {
  27308. if (!this.checkProperty(this.children[i], key, value, force))
  27309. {
  27310. return false;
  27311. }
  27312. }
  27313. }
  27314. return true;
  27315. };
  27316. /**
  27317. * Adds the amount to the given property on all children in this group.
  27318. *
  27319. * `Group.addAll('x', 10)` will add 10 to the child.x value for each child.
  27320. *
  27321. * @method Phaser.Group#addAll
  27322. * @param {string} property - The property to increment, for example 'body.velocity.x' or 'angle'.
  27323. * @param {number} amount - The amount to increment the property by. If child.x = 10 then addAll('x', 40) would make child.x = 50.
  27324. * @param {boolean} checkAlive - If true the property will only be changed if the child is alive.
  27325. * @param {boolean} checkVisible - If true the property will only be changed if the child is visible.
  27326. */
  27327. Phaser.Group.prototype.addAll = function (property, amount, checkAlive, checkVisible) {
  27328. this.setAll(property, amount, checkAlive, checkVisible, 1);
  27329. };
  27330. /**
  27331. * Subtracts the amount from the given property on all children in this group.
  27332. *
  27333. * `Group.subAll('x', 10)` will minus 10 from the child.x value for each child.
  27334. *
  27335. * @method Phaser.Group#subAll
  27336. * @param {string} property - The property to decrement, for example 'body.velocity.x' or 'angle'.
  27337. * @param {number} amount - The amount to subtract from the property. If child.x = 50 then subAll('x', 40) would make child.x = 10.
  27338. * @param {boolean} checkAlive - If true the property will only be changed if the child is alive.
  27339. * @param {boolean} checkVisible - If true the property will only be changed if the child is visible.
  27340. */
  27341. Phaser.Group.prototype.subAll = function (property, amount, checkAlive, checkVisible) {
  27342. this.setAll(property, amount, checkAlive, checkVisible, 2);
  27343. };
  27344. /**
  27345. * Multiplies the given property by the amount on all children in this group.
  27346. *
  27347. * `Group.multiplyAll('x', 2)` will x2 the child.x value for each child.
  27348. *
  27349. * @method Phaser.Group#multiplyAll
  27350. * @param {string} property - The property to multiply, for example 'body.velocity.x' or 'angle'.
  27351. * @param {number} amount - The amount to multiply the property by. If child.x = 10 then multiplyAll('x', 2) would make child.x = 20.
  27352. * @param {boolean} checkAlive - If true the property will only be changed if the child is alive.
  27353. * @param {boolean} checkVisible - If true the property will only be changed if the child is visible.
  27354. */
  27355. Phaser.Group.prototype.multiplyAll = function (property, amount, checkAlive, checkVisible) {
  27356. this.setAll(property, amount, checkAlive, checkVisible, 3);
  27357. };
  27358. /**
  27359. * Divides the given property by the amount on all children in this group.
  27360. *
  27361. * `Group.divideAll('x', 2)` will half the child.x value for each child.
  27362. *
  27363. * @method Phaser.Group#divideAll
  27364. * @param {string} property - The property to divide, for example 'body.velocity.x' or 'angle'.
  27365. * @param {number} amount - The amount to divide the property by. If child.x = 100 then divideAll('x', 2) would make child.x = 50.
  27366. * @param {boolean} checkAlive - If true the property will only be changed if the child is alive.
  27367. * @param {boolean} checkVisible - If true the property will only be changed if the child is visible.
  27368. */
  27369. Phaser.Group.prototype.divideAll = function (property, amount, checkAlive, checkVisible) {
  27370. this.setAll(property, amount, checkAlive, checkVisible, 4);
  27371. };
  27372. /**
  27373. * Calls a function, specified by name, on all children in the group who exist (or do not exist).
  27374. *
  27375. * After the existsValue parameter you can add as many parameters as you like, which will all be passed to the child callback.
  27376. *
  27377. * @method Phaser.Group#callAllExists
  27378. * @param {string} callback - Name of the function on the children to call.
  27379. * @param {boolean} existsValue - Only children with exists=existsValue will be called.
  27380. * @param {...any} parameter - Additional parameters that will be passed to the callback.
  27381. */
  27382. Phaser.Group.prototype.callAllExists = function (callback, existsValue) {
  27383. var args;
  27384. if (arguments.length > 2)
  27385. {
  27386. args = [];
  27387. for (var i = 2; i < arguments.length; i++)
  27388. {
  27389. args.push(arguments[i]);
  27390. }
  27391. }
  27392. for (var i = 0; i < this.children.length; i++)
  27393. {
  27394. if (this.children[i].exists === existsValue && this.children[i][callback])
  27395. {
  27396. this.children[i][callback].apply(this.children[i], args);
  27397. }
  27398. }
  27399. };
  27400. /**
  27401. * Returns a reference to a function that exists on a child of the group based on the given callback array.
  27402. *
  27403. * @method Phaser.Group#callbackFromArray
  27404. * @param {object} child - The object to inspect.
  27405. * @param {array} callback - The array of function names.
  27406. * @param {integer} length - The size of the array (pre-calculated in callAll).
  27407. * @protected
  27408. */
  27409. Phaser.Group.prototype.callbackFromArray = function (child, callback, length) {
  27410. // Kinda looks like a Christmas tree
  27411. if (length == 1)
  27412. {
  27413. if (child[callback[0]])
  27414. {
  27415. return child[callback[0]];
  27416. }
  27417. }
  27418. else if (length == 2)
  27419. {
  27420. if (child[callback[0]][callback[1]])
  27421. {
  27422. return child[callback[0]][callback[1]];
  27423. }
  27424. }
  27425. else if (length == 3)
  27426. {
  27427. if (child[callback[0]][callback[1]][callback[2]])
  27428. {
  27429. return child[callback[0]][callback[1]][callback[2]];
  27430. }
  27431. }
  27432. else if (length == 4)
  27433. {
  27434. if (child[callback[0]][callback[1]][callback[2]][callback[3]])
  27435. {
  27436. return child[callback[0]][callback[1]][callback[2]][callback[3]];
  27437. }
  27438. }
  27439. else
  27440. {
  27441. if (child[callback])
  27442. {
  27443. return child[callback];
  27444. }
  27445. }
  27446. return false;
  27447. };
  27448. /**
  27449. * Calls a function, specified by name, on all on children.
  27450. *
  27451. * The function is called for all children regardless if they are dead or alive (see callAllExists for different options).
  27452. * After the method parameter and context you can add as many extra parameters as you like, which will all be passed to the child.
  27453. *
  27454. * @method Phaser.Group#callAll
  27455. * @param {string} method - Name of the function on the child to call. Deep property lookup is supported.
  27456. * @param {string} [context=null] - A string containing the context under which the method will be executed. Set to null to default to the child.
  27457. * @param {...any} args - Additional parameters that will be passed to the method.
  27458. */
  27459. Phaser.Group.prototype.callAll = function (method, context) {
  27460. if (method === undefined)
  27461. {
  27462. return;
  27463. }
  27464. // Extract the method into an array
  27465. method = method.split('.');
  27466. var methodLength = method.length;
  27467. if (context === undefined || context === null || context === '')
  27468. {
  27469. context = null;
  27470. }
  27471. else
  27472. {
  27473. // Extract the context into an array
  27474. if (typeof context === 'string')
  27475. {
  27476. context = context.split('.');
  27477. var contextLength = context.length;
  27478. }
  27479. }
  27480. var args;
  27481. if (arguments.length > 2)
  27482. {
  27483. args = [];
  27484. for (var i = 2; i < arguments.length; i++)
  27485. {
  27486. args.push(arguments[i]);
  27487. }
  27488. }
  27489. var callback = null;
  27490. var callbackContext = null;
  27491. for (var i = 0; i < this.children.length; i++)
  27492. {
  27493. callback = this.callbackFromArray(this.children[i], method, methodLength);
  27494. if (context && callback)
  27495. {
  27496. callbackContext = this.callbackFromArray(this.children[i], context, contextLength);
  27497. if (callback)
  27498. {
  27499. callback.apply(callbackContext, args);
  27500. }
  27501. }
  27502. else if (callback)
  27503. {
  27504. callback.apply(this.children[i], args);
  27505. }
  27506. }
  27507. };
  27508. /**
  27509. * The core preUpdate - as called by World.
  27510. * @method Phaser.Group#preUpdate
  27511. * @protected
  27512. */
  27513. Phaser.Group.prototype.preUpdate = function () {
  27514. if (this.pendingDestroy)
  27515. {
  27516. this.destroy();
  27517. return false;
  27518. }
  27519. if (!this.exists || !this.parent.exists)
  27520. {
  27521. this.renderOrderID = -1;
  27522. return false;
  27523. }
  27524. var i = this.children.length;
  27525. while (i--)
  27526. {
  27527. this.children[i].preUpdate();
  27528. }
  27529. return true;
  27530. };
  27531. /**
  27532. * The core update - as called by World.
  27533. * @method Phaser.Group#update
  27534. * @protected
  27535. */
  27536. Phaser.Group.prototype.update = function () {
  27537. var i = this.children.length;
  27538. while (i--)
  27539. {
  27540. this.children[i].update();
  27541. }
  27542. };
  27543. /**
  27544. * The core postUpdate - as called by World.
  27545. * @method Phaser.Group#postUpdate
  27546. * @protected
  27547. */
  27548. Phaser.Group.prototype.postUpdate = function () {
  27549. // Fixed to Camera?
  27550. if (this.fixedToCamera)
  27551. {
  27552. this.x = this.game.camera.view.x + this.cameraOffset.x;
  27553. this.y = this.game.camera.view.y + this.cameraOffset.y;
  27554. }
  27555. var i = this.children.length;
  27556. while (i--)
  27557. {
  27558. this.children[i].postUpdate();
  27559. }
  27560. };
  27561. /**
  27562. * Find children matching a certain predicate.
  27563. *
  27564. * For example:
  27565. *
  27566. * var healthyList = Group.filter(function(child, index, children) {
  27567. * return child.health > 10 ? true : false;
  27568. * }, true);
  27569. * healthyList.callAll('attack');
  27570. *
  27571. * Note: Currently this will skip any children which are Groups themselves.
  27572. *
  27573. * @method Phaser.Group#filter
  27574. * @param {function} predicate - The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, the index as the second, and the entire child array as the third
  27575. * @param {boolean} [checkExists=false] - If true, only existing can be selected; otherwise all children can be selected and will be passed to the predicate.
  27576. * @return {Phaser.ArraySet} Returns an array list containing all the children that the predicate returned true for
  27577. */
  27578. Phaser.Group.prototype.filter = function (predicate, checkExists) {
  27579. var index = -1;
  27580. var length = this.children.length;
  27581. var results = [];
  27582. while (++index < length)
  27583. {
  27584. var child = this.children[index];
  27585. if (!checkExists || (checkExists && child.exists))
  27586. {
  27587. if (predicate(child, index, this.children))
  27588. {
  27589. results.push(child);
  27590. }
  27591. }
  27592. }
  27593. return new Phaser.ArraySet(results);
  27594. };
  27595. /**
  27596. * Call a function on each child in this group.
  27597. *
  27598. * Additional arguments for the callback can be specified after the `checkExists` parameter. For example,
  27599. *
  27600. * Group.forEach(awardBonusGold, this, true, 100, 500)
  27601. *
  27602. * would invoke `awardBonusGold` function with the parameters `(child, 100, 500)`.
  27603. *
  27604. * Note: This check will skip any children which are Groups themselves.
  27605. *
  27606. * @method Phaser.Group#forEach
  27607. * @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument.
  27608. * @param {object} callbackContext - The context in which the function should be called (usually 'this').
  27609. * @param {boolean} [checkExists=false] - If set only children matching for which `exists` is true will be passed to the callback, otherwise all children will be passed.
  27610. * @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item.
  27611. */
  27612. Phaser.Group.prototype.forEach = function (callback, callbackContext, checkExists) {
  27613. if (checkExists === undefined) { checkExists = false; }
  27614. if (arguments.length <= 3)
  27615. {
  27616. for (var i = 0; i < this.children.length; i++)
  27617. {
  27618. if (!checkExists || (checkExists && this.children[i].exists))
  27619. {
  27620. callback.call(callbackContext, this.children[i]);
  27621. }
  27622. }
  27623. }
  27624. else
  27625. {
  27626. // Assigning to arguments properties causes Extreme Deoptimization in Chrome, FF, and IE.
  27627. // Using an array and pushing each element (not a slice!) is _significantly_ faster.
  27628. var args = [null];
  27629. for (var i = 3; i < arguments.length; i++)
  27630. {
  27631. args.push(arguments[i]);
  27632. }
  27633. for (var i = 0; i < this.children.length; i++)
  27634. {
  27635. if (!checkExists || (checkExists && this.children[i].exists))
  27636. {
  27637. args[0] = this.children[i];
  27638. callback.apply(callbackContext, args);
  27639. }
  27640. }
  27641. }
  27642. };
  27643. /**
  27644. * Call a function on each existing child in this group.
  27645. *
  27646. * See {@link Phaser.Group#forEach forEach} for details.
  27647. *
  27648. * @method Phaser.Group#forEachExists
  27649. * @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument.
  27650. * @param {object} callbackContext - The context in which the function should be called (usually 'this').
  27651. * @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item.
  27652. */
  27653. Phaser.Group.prototype.forEachExists = function (callback, callbackContext) {
  27654. var args;
  27655. if (arguments.length > 2)
  27656. {
  27657. args = [null];
  27658. for (var i = 2; i < arguments.length; i++)
  27659. {
  27660. args.push(arguments[i]);
  27661. }
  27662. }
  27663. this.iterate('exists', true, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args);
  27664. };
  27665. /**
  27666. * Call a function on each alive child in this group.
  27667. *
  27668. * See {@link Phaser.Group#forEach forEach} for details.
  27669. *
  27670. * @method Phaser.Group#forEachAlive
  27671. * @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument.
  27672. * @param {object} callbackContext - The context in which the function should be called (usually 'this').
  27673. * @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item.
  27674. */
  27675. Phaser.Group.prototype.forEachAlive = function (callback, callbackContext) {
  27676. var args;
  27677. if (arguments.length > 2)
  27678. {
  27679. args = [null];
  27680. for (var i = 2; i < arguments.length; i++)
  27681. {
  27682. args.push(arguments[i]);
  27683. }
  27684. }
  27685. this.iterate('alive', true, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args);
  27686. };
  27687. /**
  27688. * Call a function on each dead child in this group.
  27689. *
  27690. * See {@link Phaser.Group#forEach forEach} for details.
  27691. *
  27692. * @method Phaser.Group#forEachDead
  27693. * @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument.
  27694. * @param {object} callbackContext - The context in which the function should be called (usually 'this').
  27695. * @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item.
  27696. */
  27697. Phaser.Group.prototype.forEachDead = function (callback, callbackContext) {
  27698. var args;
  27699. if (arguments.length > 2)
  27700. {
  27701. args = [null];
  27702. for (var i = 2; i < arguments.length; i++)
  27703. {
  27704. args.push(arguments[i]);
  27705. }
  27706. }
  27707. this.iterate('alive', false, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args);
  27708. };
  27709. /**
  27710. * Sort the children in the group according to a particular key and ordering.
  27711. *
  27712. * Call this function to sort the group according to a particular key value and order.
  27713. *
  27714. * 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()`.
  27715. *
  27716. * Internally this uses a standard JavaScript Array sort, so everything that applies there also applies here, including
  27717. * alphabetical sorting, mixing strings and numbers, and Unicode sorting. See MDN for more details.
  27718. *
  27719. * @method Phaser.Group#sort
  27720. * @param {string} [key='z'] - The name of the property to sort on. Defaults to the objects z-depth value.
  27721. * @param {integer} [order=Phaser.Group.SORT_ASCENDING] - Order ascending ({@link Phaser.Group.SORT_ASCENDING SORT_ASCENDING}) or descending ({@link Phaser.Group.SORT_DESCENDING SORT_DESCENDING}).
  27722. */
  27723. Phaser.Group.prototype.sort = function (key, order) {
  27724. if (this.children.length < 2)
  27725. {
  27726. // Nothing to swap
  27727. return;
  27728. }
  27729. if (key === undefined) { key = 'z'; }
  27730. if (order === undefined) { order = Phaser.Group.SORT_ASCENDING; }
  27731. this._sortProperty = key;
  27732. if (order === Phaser.Group.SORT_ASCENDING)
  27733. {
  27734. this.children.sort(this.ascendingSortHandler.bind(this));
  27735. }
  27736. else
  27737. {
  27738. this.children.sort(this.descendingSortHandler.bind(this));
  27739. }
  27740. this.updateZ();
  27741. };
  27742. /**
  27743. * Sort the children in the group according to custom sort function.
  27744. *
  27745. * The `sortHandler` is provided the two parameters: the two children involved in the comparison (a and b).
  27746. * It should return -1 if `a > b`, 1 if `a < b` or 0 if `a === b`.
  27747. *
  27748. * @method Phaser.Group#customSort
  27749. * @param {function} sortHandler - The custom sort function.
  27750. * @param {object} [context=undefined] - The context in which the sortHandler is called.
  27751. */
  27752. Phaser.Group.prototype.customSort = function (sortHandler, context) {
  27753. if (this.children.length < 2)
  27754. {
  27755. // Nothing to swap
  27756. return;
  27757. }
  27758. this.children.sort(sortHandler.bind(context));
  27759. this.updateZ();
  27760. };
  27761. /**
  27762. * An internal helper function for the sort process.
  27763. *
  27764. * @method Phaser.Group#ascendingSortHandler
  27765. * @protected
  27766. * @param {object} a - The first object being sorted.
  27767. * @param {object} b - The second object being sorted.
  27768. */
  27769. Phaser.Group.prototype.ascendingSortHandler = function (a, b) {
  27770. if (a[this._sortProperty] < b[this._sortProperty])
  27771. {
  27772. return -1;
  27773. }
  27774. else if (a[this._sortProperty] > b[this._sortProperty])
  27775. {
  27776. return 1;
  27777. }
  27778. else
  27779. {
  27780. if (a.z < b.z)
  27781. {
  27782. return -1;
  27783. }
  27784. else
  27785. {
  27786. return 1;
  27787. }
  27788. }
  27789. };
  27790. /**
  27791. * An internal helper function for the sort process.
  27792. *
  27793. * @method Phaser.Group#descendingSortHandler
  27794. * @protected
  27795. * @param {object} a - The first object being sorted.
  27796. * @param {object} b - The second object being sorted.
  27797. */
  27798. Phaser.Group.prototype.descendingSortHandler = function (a, b) {
  27799. if (a[this._sortProperty] < b[this._sortProperty])
  27800. {
  27801. return 1;
  27802. }
  27803. else if (a[this._sortProperty] > b[this._sortProperty])
  27804. {
  27805. return -1;
  27806. }
  27807. else
  27808. {
  27809. return 0;
  27810. }
  27811. };
  27812. /**
  27813. * Iterates over the children of the group performing one of several actions for matched children.
  27814. *
  27815. * A child is considered a match when it has a property, named `key`, whose value is equal to `value`
  27816. * according to a strict equality comparison.
  27817. *
  27818. * The result depends on the `returnType`:
  27819. *
  27820. * - {@link Phaser.Group.RETURN_TOTAL RETURN_TOTAL}:
  27821. * The callback, if any, is applied to all matching children. The number of matched children is returned.
  27822. * - {@link Phaser.Group.RETURN_NONE RETURN_NONE}:
  27823. * The callback, if any, is applied to all matching children. No value is returned.
  27824. * - {@link Phaser.Group.RETURN_CHILD RETURN_CHILD}:
  27825. * The callback, if any, is applied to the *first* matching child and the *first* matched child is returned.
  27826. * If there is no matching child then null is returned.
  27827. *
  27828. * If `args` is specified it must be an array. The matched child will be assigned to the first
  27829. * element and the entire array will be applied to the callback function.
  27830. *
  27831. * @method Phaser.Group#iterate
  27832. * @param {string} key - The child property to check, i.e. 'exists', 'alive', 'health'
  27833. * @param {any} value - A child matches if `child[key] === value` is true.
  27834. * @param {integer} returnType - How to iterate the children and what to return.
  27835. * @param {function} [callback=null] - Optional function that will be called on each matching child. The matched child is supplied as the first argument.
  27836. * @param {object} [callbackContext] - The context in which the function should be called (usually 'this').
  27837. * @param {any[]} [args=(none)] - The arguments supplied to to the callback; the first array index (argument) will be replaced with the matched child.
  27838. * @return {any} Returns either an integer (for RETURN_TOTAL), the first matched child (for RETURN_CHILD), or null.
  27839. */
  27840. Phaser.Group.prototype.iterate = function (key, value, returnType, callback, callbackContext, args) {
  27841. if (returnType === Phaser.Group.RETURN_TOTAL && this.children.length === 0)
  27842. {
  27843. return 0;
  27844. }
  27845. var total = 0;
  27846. for (var i = 0; i < this.children.length; i++)
  27847. {
  27848. if (this.children[i][key] === value)
  27849. {
  27850. total++;
  27851. if (callback)
  27852. {
  27853. if (args)
  27854. {
  27855. args[0] = this.children[i];
  27856. callback.apply(callbackContext, args);
  27857. }
  27858. else
  27859. {
  27860. callback.call(callbackContext, this.children[i]);
  27861. }
  27862. }
  27863. if (returnType === Phaser.Group.RETURN_CHILD)
  27864. {
  27865. return this.children[i];
  27866. }
  27867. }
  27868. }
  27869. if (returnType === Phaser.Group.RETURN_TOTAL)
  27870. {
  27871. return total;
  27872. }
  27873. // RETURN_CHILD or RETURN_NONE
  27874. return null;
  27875. };
  27876. /**
  27877. * Get the first display object that exists, or doesn't exist.
  27878. *
  27879. * You can use the optional argument `createIfNull` to create a new Game Object if none matching your exists argument were found in this Group.
  27880. *
  27881. * It works by calling `Group.create` passing it the parameters given to this method, and returning the new child.
  27882. *
  27883. * If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child
  27884. * will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`.
  27885. *
  27886. * @method Phaser.Group#getFirstExists
  27887. * @param {boolean} [exists=true] - If true, find the first existing child; otherwise find the first non-existing child.
  27888. * @param {boolean} [createIfNull=false] - If `true` and no alive children are found a new one is created.
  27889. * @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point.
  27890. * @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point.
  27891. * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|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 Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture.
  27892. * @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.
  27893. * @return {DisplayObject} The first child, or `null` if none found and `createIfNull` was false.
  27894. */
  27895. Phaser.Group.prototype.getFirstExists = function (exists, createIfNull, x, y, key, frame) {
  27896. if (createIfNull === undefined) { createIfNull = false; }
  27897. if (typeof exists !== 'boolean')
  27898. {
  27899. exists = true;
  27900. }
  27901. var child = this.iterate('exists', exists, Phaser.Group.RETURN_CHILD);
  27902. return (child === null && createIfNull) ? this.create(x, y, key, frame) : this.resetChild(child, x, y, key, frame);
  27903. };
  27904. /**
  27905. * Get the first child that is alive (`child.alive === true`).
  27906. *
  27907. * This is handy for choosing a squad leader, etc.
  27908. *
  27909. * You can use the optional argument `createIfNull` to create a new Game Object if no alive ones were found in this Group.
  27910. *
  27911. * It works by calling `Group.create` passing it the parameters given to this method, and returning the new child.
  27912. *
  27913. * If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child
  27914. * will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`.
  27915. *
  27916. * @method Phaser.Group#getFirstAlive
  27917. * @param {boolean} [createIfNull=false] - If `true` and no alive children are found a new one is created.
  27918. * @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point.
  27919. * @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point.
  27920. * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|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 Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture.
  27921. * @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.
  27922. * @return {DisplayObject} The alive dead child, or `null` if none found and `createIfNull` was false.
  27923. */
  27924. Phaser.Group.prototype.getFirstAlive = function (createIfNull, x, y, key, frame) {
  27925. if (createIfNull === undefined) { createIfNull = false; }
  27926. var child = this.iterate('alive', true, Phaser.Group.RETURN_CHILD);
  27927. return (child === null && createIfNull) ? this.create(x, y, key, frame) : this.resetChild(child, x, y, key, frame);
  27928. };
  27929. /**
  27930. * Get the first child that is dead (`child.alive === false`).
  27931. *
  27932. * This is handy for checking if everything has been wiped out and adding to the pool as needed.
  27933. *
  27934. * You can use the optional argument `createIfNull` to create a new Game Object if no dead ones were found in this Group.
  27935. *
  27936. * It works by calling `Group.create` passing it the parameters given to this method, and returning the new child.
  27937. *
  27938. * If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child
  27939. * will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`.
  27940. *
  27941. * @method Phaser.Group#getFirstDead
  27942. * @param {boolean} [createIfNull=false] - If `true` and no dead children are found a new one is created.
  27943. * @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point.
  27944. * @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point.
  27945. * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|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 Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture.
  27946. * @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.
  27947. * @return {DisplayObject} The first dead child, or `null` if none found and `createIfNull` was false.
  27948. */
  27949. Phaser.Group.prototype.getFirstDead = function (createIfNull, x, y, key, frame) {
  27950. if (createIfNull === undefined) { createIfNull = false; }
  27951. var child = this.iterate('alive', false, Phaser.Group.RETURN_CHILD);
  27952. return (child === null && createIfNull) ? this.create(x, y, key, frame) : this.resetChild(child, x, y, key, frame);
  27953. };
  27954. /**
  27955. * Takes a child and if the `x` and `y` arguments are given it calls `child.reset(x, y)` on it.
  27956. *
  27957. * If the `key` and optionally the `frame` arguments are given, it calls `child.loadTexture(key, frame)` on it.
  27958. *
  27959. * The two operations are separate. For example if you just wish to load a new texture then pass `null` as the x and y values.
  27960. *
  27961. * @method Phaser.Group#resetChild
  27962. * @param {DisplayObject} child - The child to reset and/or load the texture on.
  27963. * @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point.
  27964. * @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point.
  27965. * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|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 Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture.
  27966. * @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.
  27967. * @return {DisplayObject} The child that was reset: usually a {@link Phaser.Sprite}.
  27968. */
  27969. Phaser.Group.prototype.resetChild = function (child, x, y, key, frame) {
  27970. if (child === null)
  27971. {
  27972. return null;
  27973. }
  27974. if (x === undefined) { x = null; }
  27975. if (y === undefined) { y = null; }
  27976. if (x !== null && y !== null)
  27977. {
  27978. child.reset(x, y);
  27979. }
  27980. if (key !== undefined)
  27981. {
  27982. child.loadTexture(key, frame);
  27983. }
  27984. return child;
  27985. };
  27986. /**
  27987. * Return the child at the top of this group.
  27988. *
  27989. * The top child is the child displayed (rendered) above every other child.
  27990. *
  27991. * @method Phaser.Group#getTop
  27992. * @return {any} The child at the top of the Group.
  27993. */
  27994. Phaser.Group.prototype.getTop = function () {
  27995. if (this.children.length > 0)
  27996. {
  27997. return this.children[this.children.length - 1];
  27998. }
  27999. };
  28000. /**
  28001. * Returns the child at the bottom of this group.
  28002. *
  28003. * The bottom child the child being displayed (rendered) below every other child.
  28004. *
  28005. * @method Phaser.Group#getBottom
  28006. * @return {any} The child at the bottom of the Group.
  28007. */
  28008. Phaser.Group.prototype.getBottom = function () {
  28009. if (this.children.length > 0)
  28010. {
  28011. return this.children[0];
  28012. }
  28013. };
  28014. /**
  28015. * Get the number of living children in this group.
  28016. *
  28017. * @method Phaser.Group#countLiving
  28018. * @return {integer} The number of children flagged as alive.
  28019. */
  28020. Phaser.Group.prototype.countLiving = function () {
  28021. return this.iterate('alive', true, Phaser.Group.RETURN_TOTAL);
  28022. };
  28023. /**
  28024. * Get the number of dead children in this group.
  28025. *
  28026. * @method Phaser.Group#countDead
  28027. * @return {integer} The number of children flagged as dead.
  28028. */
  28029. Phaser.Group.prototype.countDead = function () {
  28030. return this.iterate('alive', false, Phaser.Group.RETURN_TOTAL);
  28031. };
  28032. /**
  28033. * Returns a random child from the group.
  28034. *
  28035. * @method Phaser.Group#getRandom
  28036. * @param {integer} [startIndex=0] - Offset from the front of the front of the group (lowest child).
  28037. * @param {integer} [length=(to top)] - Restriction on the number of values you want to randomly select from.
  28038. * @return {any} A random child of this Group.
  28039. */
  28040. Phaser.Group.prototype.getRandom = function (startIndex, length) {
  28041. if (this.children.length === 0)
  28042. {
  28043. return null;
  28044. }
  28045. startIndex = startIndex || 0;
  28046. length = length || this.children.length;
  28047. return Phaser.ArrayUtils.getRandomItem(this.children, startIndex, length);
  28048. };
  28049. /**
  28050. * Removes the given child from this group.
  28051. *
  28052. * This will dispatch an `onRemovedFromGroup` event from the child (if it has one), and optionally destroy the child.
  28053. *
  28054. * If the group cursor was referring to the removed child it is updated to refer to the next child.
  28055. *
  28056. * @method Phaser.Group#remove
  28057. * @param {any} child - The child to remove.
  28058. * @param {boolean} [destroy=false] - If true `destroy` will be invoked on the removed child.
  28059. * @param {boolean} [silent=false] - If true the the child will not dispatch the `onRemovedFromGroup` event.
  28060. * @return {boolean} true if the child was removed from this group, otherwise false.
  28061. */
  28062. Phaser.Group.prototype.remove = function (child, destroy, silent) {
  28063. if (destroy === undefined) { destroy = false; }
  28064. if (silent === undefined) { silent = false; }
  28065. if (this.children.length === 0 || this.children.indexOf(child) === -1)
  28066. {
  28067. return false;
  28068. }
  28069. if (!silent && child.events && !child.destroyPhase)
  28070. {
  28071. child.events.onRemovedFromGroup$dispatch(child, this);
  28072. }
  28073. var removed = this.removeChild(child);
  28074. this.removeFromHash(child);
  28075. this.updateZ();
  28076. if (this.cursor === child)
  28077. {
  28078. this.next();
  28079. }
  28080. if (destroy && removed)
  28081. {
  28082. removed.destroy(true);
  28083. }
  28084. return true;
  28085. };
  28086. /**
  28087. * Moves all children from this Group to the Group given.
  28088. *
  28089. * @method Phaser.Group#moveAll
  28090. * @param {Phaser.Group} group - The new Group to which the children will be moved to.
  28091. * @param {boolean} [silent=false] - If true the children will not dispatch the `onAddedToGroup` event for the new Group.
  28092. * @return {Phaser.Group} The Group to which all the children were moved.
  28093. */
  28094. Phaser.Group.prototype.moveAll = function (group, silent) {
  28095. if (silent === undefined) { silent = false; }
  28096. if (this.children.length > 0 && group instanceof Phaser.Group)
  28097. {
  28098. do
  28099. {
  28100. group.add(this.children[0], silent);
  28101. }
  28102. while (this.children.length > 0);
  28103. this.hash = [];
  28104. this.cursor = null;
  28105. }
  28106. return group;
  28107. };
  28108. /**
  28109. * Removes all children from this group, but does not remove the group from its parent.
  28110. *
  28111. * @method Phaser.Group#removeAll
  28112. * @param {boolean} [destroy=false] - If true `destroy` will be invoked on each removed child.
  28113. * @param {boolean} [silent=false] - If true the children will not dispatch their `onRemovedFromGroup` events.
  28114. */
  28115. Phaser.Group.prototype.removeAll = function (destroy, silent) {
  28116. if (destroy === undefined) { destroy = false; }
  28117. if (silent === undefined) { silent = false; }
  28118. if (this.children.length === 0)
  28119. {
  28120. return;
  28121. }
  28122. do
  28123. {
  28124. if (!silent && this.children[0].events)
  28125. {
  28126. this.children[0].events.onRemovedFromGroup$dispatch(this.children[0], this);
  28127. }
  28128. var removed = this.removeChild(this.children[0]);
  28129. this.removeFromHash(removed);
  28130. if (destroy && removed)
  28131. {
  28132. removed.destroy(true);
  28133. }
  28134. }
  28135. while (this.children.length > 0);
  28136. this.hash = [];
  28137. this.cursor = null;
  28138. };
  28139. /**
  28140. * Removes all children from this group whose index falls beteen the given startIndex and endIndex values.
  28141. *
  28142. * @method Phaser.Group#removeBetween
  28143. * @param {integer} startIndex - The index to start removing children from.
  28144. * @param {integer} [endIndex] - The index to stop removing children at. Must be higher than startIndex. If undefined this method will remove all children between startIndex and the end of the group.
  28145. * @param {boolean} [destroy=false] - If true `destroy` will be invoked on each removed child.
  28146. * @param {boolean} [silent=false] - If true the children will not dispatch their `onRemovedFromGroup` events.
  28147. */
  28148. Phaser.Group.prototype.removeBetween = function (startIndex, endIndex, destroy, silent) {
  28149. if (endIndex === undefined) { endIndex = this.children.length - 1; }
  28150. if (destroy === undefined) { destroy = false; }
  28151. if (silent === undefined) { silent = false; }
  28152. if (this.children.length === 0)
  28153. {
  28154. return;
  28155. }
  28156. if (startIndex > endIndex || startIndex < 0 || endIndex > this.children.length)
  28157. {
  28158. return false;
  28159. }
  28160. var i = endIndex;
  28161. while (i >= startIndex)
  28162. {
  28163. if (!silent && this.children[i].events)
  28164. {
  28165. this.children[i].events.onRemovedFromGroup$dispatch(this.children[i], this);
  28166. }
  28167. var removed = this.removeChild(this.children[i]);
  28168. this.removeFromHash(removed);
  28169. if (destroy && removed)
  28170. {
  28171. removed.destroy(true);
  28172. }
  28173. if (this.cursor === this.children[i])
  28174. {
  28175. this.cursor = null;
  28176. }
  28177. i--;
  28178. }
  28179. this.updateZ();
  28180. };
  28181. /**
  28182. * Destroys this group.
  28183. *
  28184. * Removes all children, then removes this group from its parent and nulls references.
  28185. *
  28186. * @method Phaser.Group#destroy
  28187. * @param {boolean} [destroyChildren=true] - If true `destroy` will be invoked on each removed child.
  28188. * @param {boolean} [soft=false] - A 'soft destroy' (set to true) doesn't remove this group from its parent or null the game reference. Set to false and it does.
  28189. */
  28190. Phaser.Group.prototype.destroy = function (destroyChildren, soft) {
  28191. if (this.game === null || this.ignoreDestroy) { return; }
  28192. if (destroyChildren === undefined) { destroyChildren = true; }
  28193. if (soft === undefined) { soft = false; }
  28194. this.onDestroy.dispatch(this, destroyChildren, soft);
  28195. this.removeAll(destroyChildren);
  28196. this.cursor = null;
  28197. this.filters = null;
  28198. this.pendingDestroy = false;
  28199. if (!soft)
  28200. {
  28201. if (this.parent)
  28202. {
  28203. this.parent.removeChild(this);
  28204. }
  28205. this.game = null;
  28206. this.exists = false;
  28207. }
  28208. };
  28209. /**
  28210. * Total number of existing children in the group.
  28211. *
  28212. * @name Phaser.Group#total
  28213. * @property {integer} total
  28214. * @readonly
  28215. */
  28216. Object.defineProperty(Phaser.Group.prototype, "total", {
  28217. get: function () {
  28218. return this.iterate('exists', true, Phaser.Group.RETURN_TOTAL);
  28219. }
  28220. });
  28221. /**
  28222. * Total number of children in this group, regardless of exists/alive status.
  28223. *
  28224. * @name Phaser.Group#length
  28225. * @property {integer} length
  28226. * @readonly
  28227. */
  28228. Object.defineProperty(Phaser.Group.prototype, "length", {
  28229. get: function () {
  28230. return this.children.length;
  28231. }
  28232. });
  28233. /**
  28234. * The angle of rotation of the group container, in degrees.
  28235. *
  28236. * This adjusts the group itself by modifying its local rotation transform.
  28237. *
  28238. * This has no impact on the rotation/angle properties of the children, but it will update their worldTransform
  28239. * and on-screen orientation and position.
  28240. *
  28241. * @name Phaser.Group#angle
  28242. * @property {number} angle
  28243. */
  28244. Object.defineProperty(Phaser.Group.prototype, "angle", {
  28245. get: function() {
  28246. return Phaser.Math.radToDeg(this.rotation);
  28247. },
  28248. set: function(value) {
  28249. this.rotation = Phaser.Math.degToRad(value);
  28250. }
  28251. });
  28252. /**
  28253. * A display object is any object that can be rendered in the Phaser/pixi.js scene graph.
  28254. *
  28255. * This includes {@link Phaser.Group} (groups are display objects!),
  28256. * {@link Phaser.Sprite}, {@link Phaser.Button}, {@link Phaser.Text}
  28257. * as well as {@link PIXI.DisplayObject} and all derived types.
  28258. *
  28259. * @typedef {object} DisplayObject
  28260. */
  28261. // Documentation stub for linking.
  28262. /**
  28263. * The x coordinate of the group container.
  28264. *
  28265. * You can adjust the group container itself by modifying its coordinates.
  28266. * This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position.
  28267. * @name Phaser.Group#x
  28268. * @property {number} x
  28269. */
  28270. /**
  28271. * The y coordinate of the group container.
  28272. *
  28273. * You can adjust the group container itself by modifying its coordinates.
  28274. * This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position.
  28275. * @name Phaser.Group#y
  28276. * @property {number} y
  28277. */
  28278. /**
  28279. * The angle of rotation of the group container, in radians.
  28280. *
  28281. * This will adjust the group container itself by modifying its rotation.
  28282. * This will have no impact on the rotation value of its children, but it will update their worldTransform and on-screen position.
  28283. * @name Phaser.Group#rotation
  28284. * @property {number} rotation
  28285. */
  28286. /**
  28287. * The visible state of the group. Non-visible Groups and all of their children are not rendered.
  28288. *
  28289. * @name Phaser.Group#visible
  28290. * @property {boolean} visible
  28291. */
  28292. /**
  28293. * The alpha value of the group container.
  28294. *
  28295. * @name Phaser.Group#alpha
  28296. * @property {number} alpha
  28297. */
  28298. /**
  28299. * @author Richard Davey <rich@photonstorm.com>
  28300. * @copyright 2016 Photon Storm Ltd.
  28301. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  28302. */
  28303. /**
  28304. * "This world is but a canvas to our imagination." - Henry David Thoreau
  28305. *
  28306. * A game has only one world. The world is an abstract place in which all game objects live. It is not bound
  28307. * by stage limits and can be any size. You look into the world via cameras. All game objects live within
  28308. * the world at world-based coordinates. By default a world is created the same size as your Stage.
  28309. *
  28310. * @class Phaser.World
  28311. * @extends Phaser.Group
  28312. * @constructor
  28313. * @param {Phaser.Game} game - Reference to the current game instance.
  28314. */
  28315. Phaser.World = function (game) {
  28316. Phaser.Group.call(this, game, null, '__world', false);
  28317. /**
  28318. * 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.
  28319. * 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.
  28320. * 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.
  28321. * 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.
  28322. * @property {Phaser.Rectangle} bounds - Bound of this world that objects can not escape from.
  28323. */
  28324. this.bounds = new Phaser.Rectangle(0, 0, game.width, game.height);
  28325. /**
  28326. * @property {Phaser.Camera} camera - Camera instance.
  28327. */
  28328. this.camera = null;
  28329. /**
  28330. * @property {boolean} _definedSize - True if the World has been given a specifically defined size (i.e. from a Tilemap or direct in code) or false if it's just matched to the Game dimensions.
  28331. * @readonly
  28332. */
  28333. this._definedSize = false;
  28334. /**
  28335. * @property {number} width - The defined width of the World. Sometimes the bounds needs to grow larger than this (if you resize the game) but this retains the original requested dimension.
  28336. */
  28337. this._width = game.width;
  28338. /**
  28339. * @property {number} height - The defined height of the World. Sometimes the bounds needs to grow larger than this (if you resize the game) but this retains the original requested dimension.
  28340. */
  28341. this._height = game.height;
  28342. this.game.state.onStateChange.add(this.stateChange, this);
  28343. };
  28344. Phaser.World.prototype = Object.create(Phaser.Group.prototype);
  28345. Phaser.World.prototype.constructor = Phaser.World;
  28346. /**
  28347. * Initialises the game world.
  28348. *
  28349. * @method Phaser.World#boot
  28350. * @protected
  28351. */
  28352. Phaser.World.prototype.boot = function () {
  28353. this.camera = new Phaser.Camera(this.game, 0, 0, 0, this.game.width, this.game.height);
  28354. this.game.stage.addChild(this);
  28355. this.camera.boot();
  28356. };
  28357. /**
  28358. * Called whenever the State changes or resets.
  28359. *
  28360. * It resets the world.x and world.y coordinates back to zero,
  28361. * then resets the Camera.
  28362. *
  28363. * @method Phaser.World#stateChange
  28364. * @protected
  28365. */
  28366. Phaser.World.prototype.stateChange = function () {
  28367. this.x = 0;
  28368. this.y = 0;
  28369. this.camera.reset();
  28370. };
  28371. /**
  28372. * Updates the size of this world and sets World.x/y to the given values
  28373. * The Camera bounds and Physics bounds (if set) are also updated to match the new World bounds.
  28374. *
  28375. * @method Phaser.World#setBounds
  28376. * @param {number} x - Top left most corner of the world.
  28377. * @param {number} y - Top left most corner of the world.
  28378. * @param {number} width - New width of the game world in pixels.
  28379. * @param {number} height - New height of the game world in pixels.
  28380. */
  28381. Phaser.World.prototype.setBounds = function (x, y, width, height) {
  28382. this._definedSize = true;
  28383. this._width = width;
  28384. this._height = height;
  28385. this.bounds.setTo(x, y, width, height);
  28386. this.x = x;
  28387. this.y = y;
  28388. if (this.camera.bounds)
  28389. {
  28390. // The Camera can never be smaller than the game size
  28391. this.camera.bounds.setTo(x, y, Math.max(width, this.game.width), Math.max(height, this.game.height));
  28392. }
  28393. this.game.physics.setBoundsToWorld();
  28394. };
  28395. /**
  28396. * Updates the size of this world. Note that this doesn't modify the world x/y coordinates, just the width and height.
  28397. *
  28398. * @method Phaser.World#resize
  28399. * @param {number} width - New width of the game world in pixels.
  28400. * @param {number} height - New height of the game world in pixels.
  28401. */
  28402. Phaser.World.prototype.resize = function (width, height) {
  28403. // Don't ever scale the World bounds lower than the original requested dimensions if it's a defined world size
  28404. if (this._definedSize)
  28405. {
  28406. if (width < this._width)
  28407. {
  28408. width = this._width;
  28409. }
  28410. if (height < this._height)
  28411. {
  28412. height = this._height;
  28413. }
  28414. }
  28415. this.bounds.width = width;
  28416. this.bounds.height = height;
  28417. this.game.camera.setBoundsToWorld();
  28418. this.game.physics.setBoundsToWorld();
  28419. };
  28420. /**
  28421. * Destroyer of worlds.
  28422. *
  28423. * @method Phaser.World#shutdown
  28424. */
  28425. Phaser.World.prototype.shutdown = function () {
  28426. // World is a Group, so run a soft destruction on this and all children.
  28427. this.destroy(true, true);
  28428. };
  28429. /**
  28430. * This will take the given game object and check if its x/y coordinates fall outside of the world bounds.
  28431. * If they do it will reposition the object to the opposite side of the world, creating a wrap-around effect.
  28432. * If sprite has a P2 body then the body (sprite.body) should be passed as first parameter to the function.
  28433. *
  28434. * Please understand there are limitations to this method. For example if you have scaled the World
  28435. * then objects won't always be re-positioned correctly, and you'll need to employ your own wrapping function.
  28436. *
  28437. * @method Phaser.World#wrap
  28438. * @param {Phaser.Sprite|Phaser.Image|Phaser.TileSprite|Phaser.Text} sprite - The object you wish to wrap around the world bounds.
  28439. * @param {number} [padding=0] - Extra padding added equally to the sprite.x and y coordinates before checking if within the world bounds. Ignored if useBounds is true.
  28440. * @param {boolean} [useBounds=false] - If useBounds is false wrap checks the object.x/y coordinates. If true it does a more accurate bounds check, which is more expensive.
  28441. * @param {boolean} [horizontal=true] - If horizontal is false, wrap will not wrap the object.x coordinates horizontally.
  28442. * @param {boolean} [vertical=true] - If vertical is false, wrap will not wrap the object.y coordinates vertically.
  28443. */
  28444. Phaser.World.prototype.wrap = function (sprite, padding, useBounds, horizontal, vertical) {
  28445. if (padding === undefined) { padding = 0; }
  28446. if (useBounds === undefined) { useBounds = false; }
  28447. if (horizontal === undefined) { horizontal = true; }
  28448. if (vertical === undefined) { vertical = true; }
  28449. if (!useBounds)
  28450. {
  28451. if (horizontal && sprite.x + padding < this.bounds.x)
  28452. {
  28453. sprite.x = this.bounds.right + padding;
  28454. }
  28455. else if (horizontal && sprite.x - padding > this.bounds.right)
  28456. {
  28457. sprite.x = this.bounds.left - padding;
  28458. }
  28459. if (vertical && sprite.y + padding < this.bounds.top)
  28460. {
  28461. sprite.y = this.bounds.bottom + padding;
  28462. }
  28463. else if (vertical && sprite.y - padding > this.bounds.bottom)
  28464. {
  28465. sprite.y = this.bounds.top - padding;
  28466. }
  28467. }
  28468. else
  28469. {
  28470. sprite.getBounds();
  28471. if (horizontal)
  28472. {
  28473. if ((sprite.x + sprite._currentBounds.width) < this.bounds.x)
  28474. {
  28475. sprite.x = this.bounds.right;
  28476. }
  28477. else if (sprite.x > this.bounds.right)
  28478. {
  28479. sprite.x = this.bounds.left;
  28480. }
  28481. }
  28482. if (vertical)
  28483. {
  28484. if ((sprite.y + sprite._currentBounds.height) < this.bounds.top)
  28485. {
  28486. sprite.y = this.bounds.bottom;
  28487. }
  28488. else if (sprite.y > this.bounds.bottom)
  28489. {
  28490. sprite.y = this.bounds.top;
  28491. }
  28492. }
  28493. }
  28494. };
  28495. /**
  28496. * @name Phaser.World#width
  28497. * @property {number} width - Gets or sets the current width of the game world. The world can never be smaller than the game (canvas) dimensions.
  28498. */
  28499. Object.defineProperty(Phaser.World.prototype, "width", {
  28500. get: function () {
  28501. return this.bounds.width;
  28502. },
  28503. set: function (value) {
  28504. if (value < this.game.width)
  28505. {
  28506. value = this.game.width;
  28507. }
  28508. this.bounds.width = value;
  28509. this._width = value;
  28510. this._definedSize = true;
  28511. }
  28512. });
  28513. /**
  28514. * @name Phaser.World#height
  28515. * @property {number} height - Gets or sets the current height of the game world. The world can never be smaller than the game (canvas) dimensions.
  28516. */
  28517. Object.defineProperty(Phaser.World.prototype, "height", {
  28518. get: function () {
  28519. return this.bounds.height;
  28520. },
  28521. set: function (value) {
  28522. if (value < this.game.height)
  28523. {
  28524. value = this.game.height;
  28525. }
  28526. this.bounds.height = value;
  28527. this._height = value;
  28528. this._definedSize = true;
  28529. }
  28530. });
  28531. /**
  28532. * @name Phaser.World#centerX
  28533. * @property {number} centerX - Gets the X position corresponding to the center point of the world.
  28534. * @readonly
  28535. */
  28536. Object.defineProperty(Phaser.World.prototype, "centerX", {
  28537. get: function () {
  28538. return this.bounds.halfWidth + this.bounds.x;
  28539. }
  28540. });
  28541. /**
  28542. * @name Phaser.World#centerY
  28543. * @property {number} centerY - Gets the Y position corresponding to the center point of the world.
  28544. * @readonly
  28545. */
  28546. Object.defineProperty(Phaser.World.prototype, "centerY", {
  28547. get: function () {
  28548. return this.bounds.halfHeight + this.bounds.y;
  28549. }
  28550. });
  28551. /**
  28552. * @name Phaser.World#randomX
  28553. * @property {number} randomX - Gets a random integer which is lesser than or equal to the current width of the game world.
  28554. * @readonly
  28555. */
  28556. Object.defineProperty(Phaser.World.prototype, "randomX", {
  28557. get: function () {
  28558. if (this.bounds.x < 0)
  28559. {
  28560. return this.game.rnd.between(this.bounds.x, (this.bounds.width - Math.abs(this.bounds.x)));
  28561. }
  28562. else
  28563. {
  28564. return this.game.rnd.between(this.bounds.x, this.bounds.width);
  28565. }
  28566. }
  28567. });
  28568. /**
  28569. * @name Phaser.World#randomY
  28570. * @property {number} randomY - Gets a random integer which is lesser than or equal to the current height of the game world.
  28571. * @readonly
  28572. */
  28573. Object.defineProperty(Phaser.World.prototype, "randomY", {
  28574. get: function () {
  28575. if (this.bounds.y < 0)
  28576. {
  28577. return this.game.rnd.between(this.bounds.y, (this.bounds.height - Math.abs(this.bounds.y)));
  28578. }
  28579. else
  28580. {
  28581. return this.game.rnd.between(this.bounds.y, this.bounds.height);
  28582. }
  28583. }
  28584. });
  28585. /**
  28586. * @author Richard Davey <rich@photonstorm.com>
  28587. * @copyright 2016 Photon Storm Ltd.
  28588. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  28589. */
  28590. /**
  28591. * This is where the magic happens. The Game object is the heart of your game,
  28592. * providing quick access to common functions and handling the boot process.
  28593. *
  28594. * "Hell, there are no rules here - we're trying to accomplish something."
  28595. * Thomas A. Edison
  28596. *
  28597. * @class Phaser.Game
  28598. * @constructor
  28599. * @param {number|string} [width=800] - The width of your game in game pixels. If given as a string the value must be between 0 and 100 and will be used as the percentage width of the parent container, or the browser window if no parent is given.
  28600. * @param {number|string} [height=600] - The height of your game in game pixels. If given as a string the value must be between 0 and 100 and will be used as the percentage height of the parent container, or the browser window if no parent is given.
  28601. * @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).
  28602. * @param {string|HTMLElement} [parent=''] - The DOM element into which this games canvas will be injected. Either a DOM ID (string) or the element itself.
  28603. * @param {object} [state=null] - The default state object. A object consisting of Phaser.State functions (preload, create, update, render) or null.
  28604. * @param {boolean} [transparent=false] - Use a transparent canvas background or not.
  28605. * @param {boolean} [antialias=true] - Draw all image textures anti-aliased or not. The default is for smooth textures, but disable if your game features pixel art.
  28606. * @param {object} [physicsConfig=null] - A physics configuration object to pass to the Physics world on creation.
  28607. */
  28608. Phaser.Game = function (width, height, renderer, parent, state, transparent, antialias, physicsConfig) {
  28609. /**
  28610. * @property {number} id - Phaser Game ID (for when Pixi supports multiple instances).
  28611. * @readonly
  28612. */
  28613. this.id = Phaser.GAMES.push(this) - 1;
  28614. /**
  28615. * @property {object} config - The Phaser.Game configuration object.
  28616. */
  28617. this.config = null;
  28618. /**
  28619. * @property {object} physicsConfig - The Phaser.Physics.World configuration object.
  28620. */
  28621. this.physicsConfig = physicsConfig;
  28622. /**
  28623. * @property {string|HTMLElement} parent - The Games DOM parent.
  28624. * @default
  28625. */
  28626. this.parent = '';
  28627. /**
  28628. * The current Game Width in pixels.
  28629. *
  28630. * _Do not modify this property directly:_ use {@link Phaser.ScaleManager#setGameSize} - eg. `game.scale.setGameSize(width, height)` - instead.
  28631. *
  28632. * @property {integer} width
  28633. * @readonly
  28634. * @default
  28635. */
  28636. this.width = 800;
  28637. /**
  28638. * The current Game Height in pixels.
  28639. *
  28640. * _Do not modify this property directly:_ use {@link Phaser.ScaleManager#setGameSize} - eg. `game.scale.setGameSize(width, height)` - instead.
  28641. *
  28642. * @property {integer} height
  28643. * @readonly
  28644. * @default
  28645. */
  28646. this.height = 600;
  28647. /**
  28648. * The resolution of your game. This value is read only, but can be changed at start time it via a game configuration object.
  28649. *
  28650. * @property {integer} resolution
  28651. * @readonly
  28652. * @default
  28653. */
  28654. this.resolution = 1;
  28655. /**
  28656. * @property {integer} _width - Private internal var.
  28657. * @private
  28658. */
  28659. this._width = 800;
  28660. /**
  28661. * @property {integer} _height - Private internal var.
  28662. * @private
  28663. */
  28664. this._height = 600;
  28665. /**
  28666. * @property {boolean} transparent - Use a transparent canvas background or not.
  28667. * @default
  28668. */
  28669. this.transparent = false;
  28670. /**
  28671. * @property {boolean} antialias - Anti-alias graphics. By default scaled images are smoothed in Canvas and WebGL, set anti-alias to false to disable this globally.
  28672. * @default
  28673. */
  28674. this.antialias = true;
  28675. /**
  28676. * @property {boolean} preserveDrawingBuffer - The value of the preserveDrawingBuffer flag affects whether or not the contents of the stencil buffer is retained after rendering.
  28677. * @default
  28678. */
  28679. this.preserveDrawingBuffer = false;
  28680. /**
  28681. * Clear the Canvas each frame before rendering the display list.
  28682. * You can set this to `false` to gain some performance if your game always contains a background that completely fills the display.
  28683. * @property {boolean} clearBeforeRender
  28684. * @default
  28685. */
  28686. this.clearBeforeRender = true;
  28687. /**
  28688. * @property {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - The Pixi Renderer.
  28689. * @protected
  28690. */
  28691. this.renderer = null;
  28692. /**
  28693. * @property {number} renderType - The Renderer this game will use. Either Phaser.AUTO, Phaser.CANVAS or Phaser.WEBGL.
  28694. * @readonly
  28695. */
  28696. this.renderType = Phaser.AUTO;
  28697. /**
  28698. * @property {Phaser.StateManager} state - The StateManager.
  28699. */
  28700. this.state = null;
  28701. /**
  28702. * @property {boolean} isBooted - Whether the game engine is booted, aka available.
  28703. * @readonly
  28704. */
  28705. this.isBooted = false;
  28706. /**
  28707. * @property {boolean} isRunning - Is game running or paused?
  28708. * @readonly
  28709. */
  28710. this.isRunning = false;
  28711. /**
  28712. * @property {Phaser.RequestAnimationFrame} raf - Automatically handles the core game loop via requestAnimationFrame or setTimeout
  28713. * @protected
  28714. */
  28715. this.raf = null;
  28716. /**
  28717. * @property {Phaser.GameObjectFactory} add - Reference to the Phaser.GameObjectFactory.
  28718. */
  28719. this.add = null;
  28720. /**
  28721. * @property {Phaser.GameObjectCreator} make - Reference to the GameObject Creator.
  28722. */
  28723. this.make = null;
  28724. /**
  28725. * @property {Phaser.Cache} cache - Reference to the assets cache.
  28726. */
  28727. this.cache = null;
  28728. /**
  28729. * @property {Phaser.Input} input - Reference to the input manager
  28730. */
  28731. this.input = null;
  28732. /**
  28733. * @property {Phaser.Loader} load - Reference to the assets loader.
  28734. */
  28735. this.load = null;
  28736. /**
  28737. * @property {Phaser.Math} math - Reference to the math helper.
  28738. */
  28739. this.math = null;
  28740. /**
  28741. * @property {Phaser.Net} net - Reference to the network class.
  28742. */
  28743. this.net = null;
  28744. /**
  28745. * @property {Phaser.ScaleManager} scale - The game scale manager.
  28746. */
  28747. this.scale = null;
  28748. /**
  28749. * @property {Phaser.SoundManager} sound - Reference to the sound manager.
  28750. */
  28751. this.sound = null;
  28752. /**
  28753. * @property {Phaser.Stage} stage - Reference to the stage.
  28754. */
  28755. this.stage = null;
  28756. /**
  28757. * @property {Phaser.Time} time - Reference to the core game clock.
  28758. */
  28759. this.time = null;
  28760. /**
  28761. * @property {Phaser.TweenManager} tweens - Reference to the tween manager.
  28762. */
  28763. this.tweens = null;
  28764. /**
  28765. * @property {Phaser.World} world - Reference to the world.
  28766. */
  28767. this.world = null;
  28768. /**
  28769. * @property {Phaser.Physics} physics - Reference to the physics manager.
  28770. */
  28771. this.physics = null;
  28772. /**
  28773. * @property {Phaser.PluginManager} plugins - Reference to the plugin manager.
  28774. */
  28775. this.plugins = null;
  28776. /**
  28777. * @property {Phaser.RandomDataGenerator} rnd - Instance of repeatable random data generator helper.
  28778. */
  28779. this.rnd = null;
  28780. /**
  28781. * @property {Phaser.Device} device - Contains device information and capabilities.
  28782. */
  28783. this.device = Phaser.Device;
  28784. /**
  28785. * @property {Phaser.Camera} camera - A handy reference to world.camera.
  28786. */
  28787. this.camera = null;
  28788. /**
  28789. * @property {HTMLCanvasElement} canvas - A handy reference to renderer.view, the canvas that the game is being rendered in to.
  28790. */
  28791. this.canvas = null;
  28792. /**
  28793. * @property {CanvasRenderingContext2D} context - A handy reference to renderer.context (only set for CANVAS games, not WebGL)
  28794. */
  28795. this.context = null;
  28796. /**
  28797. * @property {Phaser.Utils.Debug} debug - A set of useful debug utilities.
  28798. */
  28799. this.debug = null;
  28800. /**
  28801. * @property {Phaser.Particles} particles - The Particle Manager.
  28802. */
  28803. this.particles = null;
  28804. /**
  28805. * @property {Phaser.Create} create - The Asset Generator.
  28806. */
  28807. this.create = null;
  28808. /**
  28809. * If `false` Phaser will automatically render the display list every update. If `true` the render loop will be skipped.
  28810. * You can toggle this value at run-time to gain exact control over when Phaser renders. This can be useful in certain types of game or application.
  28811. * Please note that if you don't render the display list then none of the game object transforms will be updated, so use this value carefully.
  28812. * @property {boolean} lockRender
  28813. * @default
  28814. */
  28815. this.lockRender = false;
  28816. /**
  28817. * @property {boolean} stepping - Enable core loop stepping with Game.enableStep().
  28818. * @default
  28819. * @readonly
  28820. */
  28821. this.stepping = false;
  28822. /**
  28823. * @property {boolean} pendingStep - An internal property used by enableStep, but also useful to query from your own game objects.
  28824. * @default
  28825. * @readonly
  28826. */
  28827. this.pendingStep = false;
  28828. /**
  28829. * @property {number} stepCount - When stepping is enabled this contains the current step cycle.
  28830. * @default
  28831. * @readonly
  28832. */
  28833. this.stepCount = 0;
  28834. /**
  28835. * @property {Phaser.Signal} onPause - This event is fired when the game pauses.
  28836. */
  28837. this.onPause = null;
  28838. /**
  28839. * @property {Phaser.Signal} onResume - This event is fired when the game resumes from a paused state.
  28840. */
  28841. this.onResume = null;
  28842. /**
  28843. * @property {Phaser.Signal} onBlur - This event is fired when the game no longer has focus (typically on page hide).
  28844. */
  28845. this.onBlur = null;
  28846. /**
  28847. * @property {Phaser.Signal} onFocus - This event is fired when the game has focus (typically on page show).
  28848. */
  28849. this.onFocus = null;
  28850. /**
  28851. * @property {boolean} _paused - Is game paused?
  28852. * @private
  28853. */
  28854. this._paused = false;
  28855. /**
  28856. * @property {boolean} _codePaused - Was the game paused via code or a visibility change?
  28857. * @private
  28858. */
  28859. this._codePaused = false;
  28860. /**
  28861. * The ID of the current/last logic update applied this render frame, starting from 0.
  28862. * The first update is `currentUpdateID === 0` and the last update is `currentUpdateID === updatesThisFrame.`
  28863. * @property {integer} currentUpdateID
  28864. * @protected
  28865. */
  28866. this.currentUpdateID = 0;
  28867. /**
  28868. * Number of logic updates expected to occur this render frame; will be 1 unless there are catch-ups required (and allowed).
  28869. * @property {integer} updatesThisFrame
  28870. * @protected
  28871. */
  28872. this.updatesThisFrame = 1;
  28873. /**
  28874. * @property {number} _deltaTime - Accumulate elapsed time until a logic update is due.
  28875. * @private
  28876. */
  28877. this._deltaTime = 0;
  28878. /**
  28879. * @property {number} _lastCount - Remember how many 'catch-up' iterations were used on the logicUpdate last frame.
  28880. * @private
  28881. */
  28882. this._lastCount = 0;
  28883. /**
  28884. * @property {number} _spiraling - If the 'catch-up' iterations are spiraling out of control, this counter is incremented.
  28885. * @private
  28886. */
  28887. this._spiraling = 0;
  28888. /**
  28889. * @property {boolean} _kickstart - Force a logic update + render by default (always set on Boot and State swap)
  28890. * @private
  28891. */
  28892. this._kickstart = true;
  28893. /**
  28894. * If the game is struggling to maintain the desired FPS, this signal will be dispatched.
  28895. * The desired/chosen FPS should probably be closer to the {@link Phaser.Time#suggestedFps} value.
  28896. * @property {Phaser.Signal} fpsProblemNotifier
  28897. * @public
  28898. */
  28899. this.fpsProblemNotifier = new Phaser.Signal();
  28900. /**
  28901. * @property {boolean} forceSingleUpdate - Should the game loop force a logic update, regardless of the delta timer? Set to true if you know you need this. You can toggle it on the fly.
  28902. */
  28903. this.forceSingleUpdate = true;
  28904. /**
  28905. * @property {number} _nextNotification - The soonest game.time.time value that the next fpsProblemNotifier can be dispatched.
  28906. * @private
  28907. */
  28908. this._nextFpsNotification = 0;
  28909. // Parse the configuration object (if any)
  28910. if (arguments.length === 1 && typeof arguments[0] === 'object')
  28911. {
  28912. this.parseConfig(arguments[0]);
  28913. }
  28914. else
  28915. {
  28916. this.config = { enableDebug: true };
  28917. if (typeof width !== 'undefined')
  28918. {
  28919. this._width = width;
  28920. }
  28921. if (typeof height !== 'undefined')
  28922. {
  28923. this._height = height;
  28924. }
  28925. if (typeof renderer !== 'undefined')
  28926. {
  28927. this.renderType = renderer;
  28928. }
  28929. if (typeof parent !== 'undefined')
  28930. {
  28931. this.parent = parent;
  28932. }
  28933. if (typeof transparent !== 'undefined')
  28934. {
  28935. this.transparent = transparent;
  28936. }
  28937. if (typeof antialias !== 'undefined')
  28938. {
  28939. this.antialias = antialias;
  28940. }
  28941. this.rnd = new Phaser.RandomDataGenerator([(Date.now() * Math.random()).toString()]);
  28942. this.state = new Phaser.StateManager(this, state);
  28943. }
  28944. this.device.whenReady(this.boot, this);
  28945. return this;
  28946. };
  28947. Phaser.Game.prototype = {
  28948. /**
  28949. * Parses a Game configuration object.
  28950. *
  28951. * @method Phaser.Game#parseConfig
  28952. * @protected
  28953. */
  28954. parseConfig: function (config) {
  28955. this.config = config;
  28956. if (config['enableDebug'] === undefined)
  28957. {
  28958. this.config.enableDebug = true;
  28959. }
  28960. if (config['width'])
  28961. {
  28962. this._width = config['width'];
  28963. }
  28964. if (config['height'])
  28965. {
  28966. this._height = config['height'];
  28967. }
  28968. if (config['renderer'])
  28969. {
  28970. this.renderType = config['renderer'];
  28971. }
  28972. if (config['parent'])
  28973. {
  28974. this.parent = config['parent'];
  28975. }
  28976. if (config['transparent'] !== undefined)
  28977. {
  28978. this.transparent = config['transparent'];
  28979. }
  28980. if (config['antialias'] !== undefined)
  28981. {
  28982. this.antialias = config['antialias'];
  28983. }
  28984. if (config['resolution'])
  28985. {
  28986. this.resolution = config['resolution'];
  28987. }
  28988. if (config['preserveDrawingBuffer'] !== undefined)
  28989. {
  28990. this.preserveDrawingBuffer = config['preserveDrawingBuffer'];
  28991. }
  28992. if (config['physicsConfig'])
  28993. {
  28994. this.physicsConfig = config['physicsConfig'];
  28995. }
  28996. var seed = [(Date.now() * Math.random()).toString()];
  28997. if (config['seed'])
  28998. {
  28999. seed = config['seed'];
  29000. }
  29001. this.rnd = new Phaser.RandomDataGenerator(seed);
  29002. var state = null;
  29003. if (config['state'])
  29004. {
  29005. state = config['state'];
  29006. }
  29007. this.state = new Phaser.StateManager(this, state);
  29008. },
  29009. /**
  29010. * Initialize engine sub modules and start the game.
  29011. *
  29012. * @method Phaser.Game#boot
  29013. * @protected
  29014. */
  29015. boot: function () {
  29016. if (this.isBooted)
  29017. {
  29018. return;
  29019. }
  29020. this.onPause = new Phaser.Signal();
  29021. this.onResume = new Phaser.Signal();
  29022. this.onBlur = new Phaser.Signal();
  29023. this.onFocus = new Phaser.Signal();
  29024. this.isBooted = true;
  29025. PIXI.game = this;
  29026. this.math = Phaser.Math;
  29027. this.scale = new Phaser.ScaleManager(this, this._width, this._height);
  29028. this.stage = new Phaser.Stage(this);
  29029. this.setUpRenderer();
  29030. this.world = new Phaser.World(this);
  29031. this.add = new Phaser.GameObjectFactory(this);
  29032. this.make = new Phaser.GameObjectCreator(this);
  29033. this.cache = new Phaser.Cache(this);
  29034. this.load = new Phaser.Loader(this);
  29035. this.time = new Phaser.Time(this);
  29036. this.tweens = new Phaser.TweenManager(this);
  29037. this.input = new Phaser.Input(this);
  29038. this.sound = new Phaser.SoundManager(this);
  29039. this.physics = new Phaser.Physics(this, this.physicsConfig);
  29040. this.particles = new Phaser.Particles(this);
  29041. this.create = new Phaser.Create(this);
  29042. this.plugins = new Phaser.PluginManager(this);
  29043. this.net = new Phaser.Net(this);
  29044. this.time.boot();
  29045. this.stage.boot();
  29046. this.world.boot();
  29047. this.scale.boot();
  29048. this.input.boot();
  29049. this.sound.boot();
  29050. this.state.boot();
  29051. if (this.config['enableDebug'])
  29052. {
  29053. this.debug = new Phaser.Utils.Debug(this);
  29054. this.debug.boot();
  29055. }
  29056. else
  29057. {
  29058. this.debug = { preUpdate: function () {}, update: function () {}, reset: function () {} };
  29059. }
  29060. this.showDebugHeader();
  29061. this.isRunning = true;
  29062. if (this.config && this.config['forceSetTimeOut'])
  29063. {
  29064. this.raf = new Phaser.RequestAnimationFrame(this, this.config['forceSetTimeOut']);
  29065. }
  29066. else
  29067. {
  29068. this.raf = new Phaser.RequestAnimationFrame(this, false);
  29069. }
  29070. this._kickstart = true;
  29071. if (window['focus'])
  29072. {
  29073. if (!window['PhaserGlobal'] || (window['PhaserGlobal'] && !window['PhaserGlobal'].stopFocus))
  29074. {
  29075. window.focus();
  29076. }
  29077. }
  29078. this.raf.start();
  29079. },
  29080. /**
  29081. * Displays a Phaser version debug header in the console.
  29082. *
  29083. * @method Phaser.Game#showDebugHeader
  29084. * @protected
  29085. */
  29086. showDebugHeader: function () {
  29087. if (window['PhaserGlobal'] && window['PhaserGlobal'].hideBanner)
  29088. {
  29089. return;
  29090. }
  29091. var v = Phaser.VERSION;
  29092. var r = 'Canvas';
  29093. var a = 'HTML Audio';
  29094. var c = 1;
  29095. if (this.renderType === Phaser.WEBGL)
  29096. {
  29097. r = 'WebGL';
  29098. c++;
  29099. }
  29100. else if (this.renderType == Phaser.HEADLESS)
  29101. {
  29102. r = 'Headless';
  29103. }
  29104. if (this.device.webAudio)
  29105. {
  29106. a = 'WebAudio';
  29107. c++;
  29108. }
  29109. if (this.device.chrome)
  29110. {
  29111. var args = [
  29112. '%c %c %c Phaser v' + v + ' | Pixi.js ' + PIXI.VERSION + ' | ' + r + ' | ' + a + ' %c %c ' + '%c http://phaser.io %c\u2665%c\u2665%c\u2665',
  29113. 'background: #9854d8',
  29114. 'background: #6c2ca7',
  29115. 'color: #ffffff; background: #450f78;',
  29116. 'background: #6c2ca7',
  29117. 'background: #9854d8',
  29118. 'background: #ffffff'
  29119. ];
  29120. for (var i = 0; i < 3; i++)
  29121. {
  29122. if (i < c)
  29123. {
  29124. args.push('color: #ff2424; background: #fff');
  29125. }
  29126. else
  29127. {
  29128. args.push('color: #959595; background: #fff');
  29129. }
  29130. }
  29131. console.log.apply(console, args);
  29132. }
  29133. else if (window['console'])
  29134. {
  29135. console.log('Phaser v' + v + ' | Pixi.js ' + PIXI.VERSION + ' | ' + r + ' | ' + a + ' | http://phaser.io');
  29136. }
  29137. },
  29138. /**
  29139. * Checks if the device is capable of using the requested renderer and sets it up or an alternative if not.
  29140. *
  29141. * @method Phaser.Game#setUpRenderer
  29142. * @protected
  29143. */
  29144. setUpRenderer: function () {
  29145. if (this.config['canvas'])
  29146. {
  29147. this.canvas = this.config['canvas'];
  29148. }
  29149. else
  29150. {
  29151. this.canvas = Phaser.Canvas.create(this, this.width, this.height, this.config['canvasID'], true);
  29152. }
  29153. if (this.config['canvasStyle'])
  29154. {
  29155. this.canvas.style = this.config['canvasStyle'];
  29156. }
  29157. else
  29158. {
  29159. this.canvas.style['-webkit-full-screen'] = 'width: 100%; height: 100%';
  29160. }
  29161. if (this.renderType === Phaser.HEADLESS || this.renderType === Phaser.CANVAS || (this.renderType === Phaser.AUTO && !this.device.webGL))
  29162. {
  29163. if (this.device.canvas)
  29164. {
  29165. // They requested Canvas and their browser supports it
  29166. this.renderType = Phaser.CANVAS;
  29167. this.renderer = new PIXI.CanvasRenderer(this);
  29168. this.context = this.renderer.context;
  29169. }
  29170. else
  29171. {
  29172. throw new Error('Phaser.Game - Cannot create Canvas or WebGL context, aborting.');
  29173. }
  29174. }
  29175. else
  29176. {
  29177. // They requested WebGL and their browser supports it
  29178. this.renderType = Phaser.WEBGL;
  29179. this.renderer = new PIXI.WebGLRenderer(this);
  29180. this.context = null;
  29181. this.canvas.addEventListener('webglcontextlost', this.contextLost.bind(this), false);
  29182. this.canvas.addEventListener('webglcontextrestored', this.contextRestored.bind(this), false);
  29183. }
  29184. if (this.device.cocoonJS)
  29185. {
  29186. this.canvas.screencanvas = (this.renderType === Phaser.CANVAS) ? true : false;
  29187. }
  29188. if (this.renderType !== Phaser.HEADLESS)
  29189. {
  29190. this.stage.smoothed = this.antialias;
  29191. Phaser.Canvas.addToDOM(this.canvas, this.parent, false);
  29192. Phaser.Canvas.setTouchAction(this.canvas);
  29193. }
  29194. },
  29195. /**
  29196. * Handles WebGL context loss.
  29197. *
  29198. * @method Phaser.Game#contextLost
  29199. * @private
  29200. * @param {Event} event - The webglcontextlost event.
  29201. */
  29202. contextLost: function (event) {
  29203. event.preventDefault();
  29204. this.renderer.contextLost = true;
  29205. },
  29206. /**
  29207. * Handles WebGL context restoration.
  29208. *
  29209. * @method Phaser.Game#contextRestored
  29210. * @private
  29211. */
  29212. contextRestored: function () {
  29213. this.renderer.initContext();
  29214. this.cache.clearGLTextures();
  29215. this.renderer.contextLost = false;
  29216. },
  29217. /**
  29218. * The core game loop.
  29219. *
  29220. * @method Phaser.Game#update
  29221. * @protected
  29222. * @param {number} time - The current time as provided by RequestAnimationFrame.
  29223. */
  29224. update: function (time) {
  29225. this.time.update(time);
  29226. if (this._kickstart)
  29227. {
  29228. this.updateLogic(this.time.desiredFpsMult);
  29229. // Sync the scene graph after _every_ logic update to account for moved game objects
  29230. this.stage.updateTransform();
  29231. // call the game render update exactly once every frame
  29232. this.updateRender(this.time.slowMotion * this.time.desiredFps);
  29233. this._kickstart = false;
  29234. return;
  29235. }
  29236. // if the logic time is spiraling upwards, skip a frame entirely
  29237. if (this._spiraling > 1 && !this.forceSingleUpdate)
  29238. {
  29239. // cause an event to warn the program that this CPU can't keep up with the current desiredFps rate
  29240. if (this.time.time > this._nextFpsNotification)
  29241. {
  29242. // only permit one fps notification per 10 seconds
  29243. this._nextFpsNotification = this.time.time + 10000;
  29244. // dispatch the notification signal
  29245. this.fpsProblemNotifier.dispatch();
  29246. }
  29247. // reset the _deltaTime accumulator which will cause all pending dropped frames to be permanently skipped
  29248. this._deltaTime = 0;
  29249. this._spiraling = 0;
  29250. // call the game render update exactly once every frame
  29251. this.updateRender(this.time.slowMotion * this.time.desiredFps);
  29252. }
  29253. else
  29254. {
  29255. // step size taking into account the slow motion speed
  29256. var slowStep = this.time.slowMotion * 1000.0 / this.time.desiredFps;
  29257. // accumulate time until the slowStep threshold is met or exceeded... up to a limit of 3 catch-up frames at slowStep intervals
  29258. this._deltaTime += Math.max(Math.min(slowStep * 3, this.time.elapsed), 0);
  29259. // call the game update logic multiple times if necessary to "catch up" with dropped frames
  29260. // unless forceSingleUpdate is true
  29261. var count = 0;
  29262. this.updatesThisFrame = Math.floor(this._deltaTime / slowStep);
  29263. if (this.forceSingleUpdate)
  29264. {
  29265. this.updatesThisFrame = Math.min(1, this.updatesThisFrame);
  29266. }
  29267. while (this._deltaTime >= slowStep)
  29268. {
  29269. this._deltaTime -= slowStep;
  29270. this.currentUpdateID = count;
  29271. this.updateLogic(this.time.desiredFpsMult);
  29272. // Sync the scene graph after _every_ logic update to account for moved game objects
  29273. this.stage.updateTransform();
  29274. count++;
  29275. if (this.forceSingleUpdate && count === 1)
  29276. {
  29277. break;
  29278. }
  29279. else
  29280. {
  29281. this.time.refresh();
  29282. }
  29283. }
  29284. // detect spiraling (if the catch-up loop isn't fast enough, the number of iterations will increase constantly)
  29285. if (count > this._lastCount)
  29286. {
  29287. this._spiraling++;
  29288. }
  29289. else if (count < this._lastCount)
  29290. {
  29291. // looks like it caught up successfully, reset the spiral alert counter
  29292. this._spiraling = 0;
  29293. }
  29294. this._lastCount = count;
  29295. // call the game render update exactly once every frame unless we're playing catch-up from a spiral condition
  29296. this.updateRender(this._deltaTime / slowStep);
  29297. }
  29298. },
  29299. /**
  29300. * Updates all logic subsystems in Phaser. Called automatically by Game.update.
  29301. *
  29302. * @method Phaser.Game#updateLogic
  29303. * @protected
  29304. * @param {number} timeStep - The current timeStep value as determined by Game.update.
  29305. */
  29306. updateLogic: function (timeStep) {
  29307. if (!this._paused && !this.pendingStep)
  29308. {
  29309. if (this.stepping)
  29310. {
  29311. this.pendingStep = true;
  29312. }
  29313. this.scale.preUpdate();
  29314. this.debug.preUpdate();
  29315. this.world.camera.preUpdate();
  29316. this.physics.preUpdate();
  29317. this.state.preUpdate(timeStep);
  29318. this.plugins.preUpdate(timeStep);
  29319. this.stage.preUpdate();
  29320. this.state.update();
  29321. this.stage.update();
  29322. this.tweens.update();
  29323. this.sound.update();
  29324. this.input.update();
  29325. this.physics.update();
  29326. this.particles.update();
  29327. this.plugins.update();
  29328. this.stage.postUpdate();
  29329. this.plugins.postUpdate();
  29330. }
  29331. else
  29332. {
  29333. // Scaling and device orientation changes are still reflected when paused.
  29334. this.scale.pauseUpdate();
  29335. this.state.pauseUpdate();
  29336. this.debug.preUpdate();
  29337. }
  29338. },
  29339. /**
  29340. * Runs the Render cycle.
  29341. * It starts by calling State.preRender. In here you can do any last minute adjustments of display objects as required.
  29342. * It then calls the renderer, which renders the entire display list, starting from the Stage object and working down.
  29343. * It then calls plugin.render on any loaded plugins, in the order in which they were enabled.
  29344. * After this State.render is called. Any rendering that happens here will take place on-top of the display list.
  29345. * Finally plugin.postRender is called on any loaded plugins, in the order in which they were enabled.
  29346. * This method is called automatically by Game.update, you don't need to call it directly.
  29347. * Should you wish to have fine-grained control over when Phaser renders then use the `Game.lockRender` boolean.
  29348. * Phaser will only render when this boolean is `false`.
  29349. *
  29350. * @method Phaser.Game#updateRender
  29351. * @protected
  29352. * @param {number} elapsedTime - The time elapsed since the last update.
  29353. */
  29354. updateRender: function (elapsedTime) {
  29355. if (this.lockRender)
  29356. {
  29357. return;
  29358. }
  29359. this.state.preRender(elapsedTime);
  29360. this.renderer.render(this.stage);
  29361. this.plugins.render(elapsedTime);
  29362. this.state.render(elapsedTime);
  29363. this.plugins.postRender(elapsedTime);
  29364. },
  29365. /**
  29366. * Enable core game loop stepping. When enabled you must call game.step() directly (perhaps via a DOM button?)
  29367. * Calling step will advance the game loop by one frame. This is extremely useful for hard to track down errors!
  29368. *
  29369. * @method Phaser.Game#enableStep
  29370. */
  29371. enableStep: function () {
  29372. this.stepping = true;
  29373. this.pendingStep = false;
  29374. this.stepCount = 0;
  29375. },
  29376. /**
  29377. * Disables core game loop stepping.
  29378. *
  29379. * @method Phaser.Game#disableStep
  29380. */
  29381. disableStep: function () {
  29382. this.stepping = false;
  29383. this.pendingStep = false;
  29384. },
  29385. /**
  29386. * When stepping is enabled you must call this function directly (perhaps via a DOM button?) to advance the game loop by one frame.
  29387. * This is extremely useful to hard to track down errors! Use the internal stepCount property to monitor progress.
  29388. *
  29389. * @method Phaser.Game#step
  29390. */
  29391. step: function () {
  29392. this.pendingStep = false;
  29393. this.stepCount++;
  29394. },
  29395. /**
  29396. * Nukes the entire game from orbit.
  29397. *
  29398. * @method Phaser.Game#destroy
  29399. */
  29400. destroy: function () {
  29401. this.raf.stop();
  29402. this.state.destroy();
  29403. this.sound.destroy();
  29404. this.scale.destroy();
  29405. this.stage.destroy();
  29406. this.input.destroy();
  29407. this.physics.destroy();
  29408. this.plugins.destroy();
  29409. this.state = null;
  29410. this.sound = null;
  29411. this.scale = null;
  29412. this.stage = null;
  29413. this.input = null;
  29414. this.physics = null;
  29415. this.plugins = null;
  29416. this.cache = null;
  29417. this.load = null;
  29418. this.time = null;
  29419. this.world = null;
  29420. this.isBooted = false;
  29421. this.renderer.destroy(false);
  29422. Phaser.Canvas.removeFromDOM(this.canvas);
  29423. Phaser.GAMES[this.id] = null;
  29424. },
  29425. /**
  29426. * Called by the Stage visibility handler.
  29427. *
  29428. * @method Phaser.Game#gamePaused
  29429. * @param {object} event - The DOM event that caused the game to pause, if any.
  29430. * @protected
  29431. */
  29432. gamePaused: function (event) {
  29433. // If the game is already paused it was done via game code, so don't re-pause it
  29434. if (!this._paused)
  29435. {
  29436. this._paused = true;
  29437. this.time.gamePaused();
  29438. if (this.sound.muteOnPause)
  29439. {
  29440. this.sound.setMute();
  29441. }
  29442. this.onPause.dispatch(event);
  29443. // Avoids Cordova iOS crash event: https://github.com/photonstorm/phaser/issues/1800
  29444. if (this.device.cordova && this.device.iOS)
  29445. {
  29446. this.lockRender = true;
  29447. }
  29448. }
  29449. },
  29450. /**
  29451. * Called by the Stage visibility handler.
  29452. *
  29453. * @method Phaser.Game#gameResumed
  29454. * @param {object} event - The DOM event that caused the game to pause, if any.
  29455. * @protected
  29456. */
  29457. gameResumed: function (event) {
  29458. // Game is paused, but wasn't paused via code, so resume it
  29459. if (this._paused && !this._codePaused)
  29460. {
  29461. this._paused = false;
  29462. this.time.gameResumed();
  29463. this.input.reset();
  29464. if (this.sound.muteOnPause)
  29465. {
  29466. this.sound.unsetMute();
  29467. }
  29468. this.onResume.dispatch(event);
  29469. // Avoids Cordova iOS crash event: https://github.com/photonstorm/phaser/issues/1800
  29470. if (this.device.cordova && this.device.iOS)
  29471. {
  29472. this.lockRender = false;
  29473. }
  29474. }
  29475. },
  29476. /**
  29477. * Called by the Stage visibility handler.
  29478. *
  29479. * @method Phaser.Game#focusLoss
  29480. * @param {object} event - The DOM event that caused the game to pause, if any.
  29481. * @protected
  29482. */
  29483. focusLoss: function (event) {
  29484. this.onBlur.dispatch(event);
  29485. if (!this.stage.disableVisibilityChange)
  29486. {
  29487. this.gamePaused(event);
  29488. }
  29489. },
  29490. /**
  29491. * Called by the Stage visibility handler.
  29492. *
  29493. * @method Phaser.Game#focusGain
  29494. * @param {object} event - The DOM event that caused the game to pause, if any.
  29495. * @protected
  29496. */
  29497. focusGain: function (event) {
  29498. this.onFocus.dispatch(event);
  29499. if (!this.stage.disableVisibilityChange)
  29500. {
  29501. this.gameResumed(event);
  29502. }
  29503. }
  29504. };
  29505. Phaser.Game.prototype.constructor = Phaser.Game;
  29506. /**
  29507. * The paused state of the Game. A paused game doesn't update any of its subsystems.
  29508. * When a game is paused the onPause event is dispatched. When it is resumed the onResume event is dispatched.
  29509. * @name Phaser.Game#paused
  29510. * @property {boolean} paused - Gets and sets the paused state of the Game.
  29511. */
  29512. Object.defineProperty(Phaser.Game.prototype, "paused", {
  29513. get: function () {
  29514. return this._paused;
  29515. },
  29516. set: function (value) {
  29517. if (value === true)
  29518. {
  29519. if (this._paused === false)
  29520. {
  29521. this._paused = true;
  29522. this.sound.setMute();
  29523. this.time.gamePaused();
  29524. this.onPause.dispatch(this);
  29525. }
  29526. this._codePaused = true;
  29527. }
  29528. else
  29529. {
  29530. if (this._paused)
  29531. {
  29532. this._paused = false;
  29533. this.input.reset();
  29534. this.sound.unsetMute();
  29535. this.time.gameResumed();
  29536. this.onResume.dispatch(this);
  29537. }
  29538. this._codePaused = false;
  29539. }
  29540. }
  29541. });
  29542. /**
  29543. *
  29544. * "Deleted code is debugged code." - Jeff Sickel
  29545. *
  29546. * ヽ(〃^▽^〃)ノ
  29547. *
  29548. */
  29549. /**
  29550. * @author Richard Davey <rich@photonstorm.com>
  29551. * @copyright 2016 Photon Storm Ltd.
  29552. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  29553. */
  29554. /**
  29555. * Phaser.Input is the Input Manager for all types of Input across Phaser, including mouse, keyboard, touch and MSPointer.
  29556. * The Input manager is updated automatically by the core game loop.
  29557. *
  29558. * @class Phaser.Input
  29559. * @constructor
  29560. * @param {Phaser.Game} game - Current game instance.
  29561. */
  29562. Phaser.Input = function (game) {
  29563. /**
  29564. * @property {Phaser.Game} game - A reference to the currently running game.
  29565. */
  29566. this.game = game;
  29567. /**
  29568. * @property {HTMLCanvasElement} hitCanvas - The canvas to which single pixels are drawn in order to perform pixel-perfect hit detection.
  29569. * @default
  29570. */
  29571. this.hitCanvas = null;
  29572. /**
  29573. * @property {CanvasRenderingContext2D} hitContext - The context of the pixel perfect hit canvas.
  29574. * @default
  29575. */
  29576. this.hitContext = null;
  29577. /**
  29578. * An array of callbacks that will be fired every time the activePointer receives a move event from the DOM.
  29579. * To add a callback to this array please use `Input.addMoveCallback`.
  29580. * @property {array} moveCallbacks
  29581. * @protected
  29582. */
  29583. this.moveCallbacks = [];
  29584. /**
  29585. * @property {number} pollRate - How often should the input pointers be checked for updates? A value of 0 means every single frame (60fps); a value of 1 means every other frame (30fps) and so on.
  29586. * @default
  29587. */
  29588. this.pollRate = 0;
  29589. /**
  29590. * When enabled, input (eg. Keyboard, Mouse, Touch) will be processed - as long as the individual sources are enabled themselves.
  29591. *
  29592. * When not enabled, _all_ input sources are ignored. To disable just one type of input; for example, the Mouse, use `input.mouse.enabled = false`.
  29593. * @property {boolean} enabled
  29594. * @default
  29595. */
  29596. this.enabled = true;
  29597. /**
  29598. * @property {number} multiInputOverride - Controls the expected behavior when using a mouse and touch together on a multi-input device.
  29599. * @default
  29600. */
  29601. this.multiInputOverride = Phaser.Input.MOUSE_TOUCH_COMBINE;
  29602. /**
  29603. * @property {Phaser.Point} position - A point object representing the current position of the Pointer.
  29604. * @default
  29605. */
  29606. this.position = null;
  29607. /**
  29608. * @property {Phaser.Point} speed - A point object representing the speed of the Pointer. Only really useful in single Pointer games; otherwise see the Pointer objects directly.
  29609. */
  29610. this.speed = null;
  29611. /**
  29612. * A Circle object centered on the x/y screen coordinates of the Input.
  29613. * Default size of 44px (Apples recommended "finger tip" size) but can be changed to anything.
  29614. * @property {Phaser.Circle} circle
  29615. */
  29616. this.circle = null;
  29617. /**
  29618. * @property {Phaser.Point} scale - The scale by which all input coordinates are multiplied; calculated by the ScaleManager. In an un-scaled game the values will be x = 1 and y = 1.
  29619. */
  29620. this.scale = null;
  29621. /**
  29622. * @property {integer} maxPointers - The maximum number of Pointers allowed to be active at any one time. A value of -1 is only limited by the total number of pointers. For lots of games it's useful to set this to 1.
  29623. * @default -1 (Limited by total pointers.)
  29624. */
  29625. this.maxPointers = -1;
  29626. /**
  29627. * @property {number} tapRate - The number of milliseconds that the Pointer has to be pressed down and then released to be considered a tap or click.
  29628. * @default
  29629. */
  29630. this.tapRate = 200;
  29631. /**
  29632. * @property {number} doubleTapRate - The number of milliseconds between taps of the same Pointer for it to be considered a double tap / click.
  29633. * @default
  29634. */
  29635. this.doubleTapRate = 300;
  29636. /**
  29637. * @property {number} holdRate - The number of milliseconds that the Pointer has to be pressed down for it to fire a onHold event.
  29638. * @default
  29639. */
  29640. this.holdRate = 2000;
  29641. /**
  29642. * @property {number} justPressedRate - The number of milliseconds below which the Pointer is considered justPressed.
  29643. * @default
  29644. */
  29645. this.justPressedRate = 200;
  29646. /**
  29647. * @property {number} justReleasedRate - The number of milliseconds below which the Pointer is considered justReleased .
  29648. * @default
  29649. */
  29650. this.justReleasedRate = 200;
  29651. /**
  29652. * Sets if the Pointer objects should record a history of x/y coordinates they have passed through.
  29653. * The history is cleared each time the Pointer is pressed down.
  29654. * The history is updated at the rate specified in Input.pollRate
  29655. * @property {boolean} recordPointerHistory
  29656. * @default
  29657. */
  29658. this.recordPointerHistory = false;
  29659. /**
  29660. * @property {number} recordRate - The rate in milliseconds at which the Pointer objects should update their tracking history.
  29661. * @default
  29662. */
  29663. this.recordRate = 100;
  29664. /**
  29665. * The total number of entries that can be recorded into the Pointer objects tracking history.
  29666. * If the Pointer is tracking one event every 100ms; then a trackLimit of 100 would store the last 10 seconds worth of history.
  29667. * @property {number} recordLimit
  29668. * @default
  29669. */
  29670. this.recordLimit = 100;
  29671. /**
  29672. * @property {Phaser.Pointer} pointer1 - A Pointer object.
  29673. */
  29674. this.pointer1 = null;
  29675. /**
  29676. * @property {Phaser.Pointer} pointer2 - A Pointer object.
  29677. */
  29678. this.pointer2 = null;
  29679. /**
  29680. * @property {Phaser.Pointer} pointer3 - A Pointer object.
  29681. */
  29682. this.pointer3 = null;
  29683. /**
  29684. * @property {Phaser.Pointer} pointer4 - A Pointer object.
  29685. */
  29686. this.pointer4 = null;
  29687. /**
  29688. * @property {Phaser.Pointer} pointer5 - A Pointer object.
  29689. */
  29690. this.pointer5 = null;
  29691. /**
  29692. * @property {Phaser.Pointer} pointer6 - A Pointer object.
  29693. */
  29694. this.pointer6 = null;
  29695. /**
  29696. * @property {Phaser.Pointer} pointer7 - A Pointer object.
  29697. */
  29698. this.pointer7 = null;
  29699. /**
  29700. * @property {Phaser.Pointer} pointer8 - A Pointer object.
  29701. */
  29702. this.pointer8 = null;
  29703. /**
  29704. * @property {Phaser.Pointer} pointer9 - A Pointer object.
  29705. */
  29706. this.pointer9 = null;
  29707. /**
  29708. * @property {Phaser.Pointer} pointer10 - A Pointer object.
  29709. */
  29710. this.pointer10 = null;
  29711. /**
  29712. * An array of non-mouse pointers that have been added to the game.
  29713. * The properties `pointer1..N` are aliases for `pointers[0..N-1]`.
  29714. * @property {Phaser.Pointer[]} pointers
  29715. * @public
  29716. * @readonly
  29717. */
  29718. this.pointers = [];
  29719. /**
  29720. * The most recently active Pointer object.
  29721. *
  29722. * When you've limited max pointers to 1 this will accurately be either the first finger touched or mouse.
  29723. *
  29724. * @property {Phaser.Pointer} activePointer
  29725. */
  29726. this.activePointer = null;
  29727. /**
  29728. * The mouse has its own unique Phaser.Pointer object which you can use if making a desktop specific game.
  29729. *
  29730. * @property {Pointer} mousePointer
  29731. */
  29732. this.mousePointer = null;
  29733. /**
  29734. * The Mouse Input manager.
  29735. *
  29736. * You should not usually access this manager directly, but instead use Input.mousePointer or Input.activePointer
  29737. * which normalizes all the input values for you, regardless of browser.
  29738. *
  29739. * @property {Phaser.Mouse} mouse
  29740. */
  29741. this.mouse = null;
  29742. /**
  29743. * The Keyboard Input manager.
  29744. *
  29745. * @property {Phaser.Keyboard} keyboard
  29746. */
  29747. this.keyboard = null;
  29748. /**
  29749. * The Touch Input manager.
  29750. *
  29751. * You should not usually access this manager directly, but instead use Input.activePointer
  29752. * which normalizes all the input values for you, regardless of browser.
  29753. *
  29754. * @property {Phaser.Touch} touch
  29755. */
  29756. this.touch = null;
  29757. /**
  29758. * The MSPointer Input manager.
  29759. *
  29760. * You should not usually access this manager directly, but instead use Input.activePointer
  29761. * which normalizes all the input values for you, regardless of browser.
  29762. *
  29763. * @property {Phaser.MSPointer} mspointer
  29764. */
  29765. this.mspointer = null;
  29766. /**
  29767. * The Gamepad Input manager.
  29768. *
  29769. * @property {Phaser.Gamepad} gamepad
  29770. */
  29771. this.gamepad = null;
  29772. /**
  29773. * If the Input Manager has been reset locked then all calls made to InputManager.reset,
  29774. * such as from a State change, are ignored.
  29775. * @property {boolean} resetLocked
  29776. * @default
  29777. */
  29778. this.resetLocked = false;
  29779. /**
  29780. * A Signal that is dispatched each time a pointer is pressed down.
  29781. * @property {Phaser.Signal} onDown
  29782. */
  29783. this.onDown = null;
  29784. /**
  29785. * A Signal that is dispatched each time a pointer is released.
  29786. * @property {Phaser.Signal} onUp
  29787. */
  29788. this.onUp = null;
  29789. /**
  29790. * A Signal that is dispatched each time a pointer is tapped.
  29791. * @property {Phaser.Signal} onTap
  29792. */
  29793. this.onTap = null;
  29794. /**
  29795. * A Signal that is dispatched each time a pointer is held down.
  29796. * @property {Phaser.Signal} onHold
  29797. */
  29798. this.onHold = null;
  29799. /**
  29800. * You can tell all Pointers to ignore any Game Object with a `priorityID` lower than this value.
  29801. * This is useful when stacking UI layers. Set to zero to disable.
  29802. * @property {number} minPriorityID
  29803. * @default
  29804. */
  29805. this.minPriorityID = 0;
  29806. /**
  29807. * A list of interactive objects. The InputHandler components add and remove themselves from this list.
  29808. * @property {Phaser.ArraySet} interactiveItems
  29809. */
  29810. this.interactiveItems = new Phaser.ArraySet();
  29811. /**
  29812. * @property {Phaser.Point} _localPoint - Internal cache var.
  29813. * @private
  29814. */
  29815. this._localPoint = new Phaser.Point();
  29816. /**
  29817. * @property {number} _pollCounter - Internal var holding the current poll counter.
  29818. * @private
  29819. */
  29820. this._pollCounter = 0;
  29821. /**
  29822. * @property {Phaser.Point} _oldPosition - A point object representing the previous position of the Pointer.
  29823. * @private
  29824. */
  29825. this._oldPosition = null;
  29826. /**
  29827. * @property {number} _x - x coordinate of the most recent Pointer event
  29828. * @private
  29829. */
  29830. this._x = 0;
  29831. /**
  29832. * @property {number} _y - Y coordinate of the most recent Pointer event
  29833. * @private
  29834. */
  29835. this._y = 0;
  29836. };
  29837. /**
  29838. * @constant
  29839. * @type {number}
  29840. */
  29841. Phaser.Input.MOUSE_OVERRIDES_TOUCH = 0;
  29842. /**
  29843. * @constant
  29844. * @type {number}
  29845. */
  29846. Phaser.Input.TOUCH_OVERRIDES_MOUSE = 1;
  29847. /**
  29848. * @constant
  29849. * @type {number}
  29850. */
  29851. Phaser.Input.MOUSE_TOUCH_COMBINE = 2;
  29852. /**
  29853. * The maximum number of pointers that can be added. This excludes the mouse pointer.
  29854. * @constant
  29855. * @type {integer}
  29856. */
  29857. Phaser.Input.MAX_POINTERS = 10;
  29858. Phaser.Input.prototype = {
  29859. /**
  29860. * Starts the Input Manager running.
  29861. *
  29862. * @method Phaser.Input#boot
  29863. * @protected
  29864. */
  29865. boot: function () {
  29866. this.mousePointer = new Phaser.Pointer(this.game, 0, Phaser.PointerMode.CURSOR);
  29867. this.addPointer();
  29868. this.addPointer();
  29869. this.mouse = new Phaser.Mouse(this.game);
  29870. this.touch = new Phaser.Touch(this.game);
  29871. this.mspointer = new Phaser.MSPointer(this.game);
  29872. if (Phaser.Keyboard)
  29873. {
  29874. this.keyboard = new Phaser.Keyboard(this.game);
  29875. }
  29876. if (Phaser.Gamepad)
  29877. {
  29878. this.gamepad = new Phaser.Gamepad(this.game);
  29879. }
  29880. this.onDown = new Phaser.Signal();
  29881. this.onUp = new Phaser.Signal();
  29882. this.onTap = new Phaser.Signal();
  29883. this.onHold = new Phaser.Signal();
  29884. this.scale = new Phaser.Point(1, 1);
  29885. this.speed = new Phaser.Point();
  29886. this.position = new Phaser.Point();
  29887. this._oldPosition = new Phaser.Point();
  29888. this.circle = new Phaser.Circle(0, 0, 44);
  29889. this.activePointer = this.mousePointer;
  29890. this.hitCanvas = PIXI.CanvasPool.create(this, 1, 1);
  29891. this.hitContext = this.hitCanvas.getContext('2d');
  29892. this.mouse.start();
  29893. this.touch.start();
  29894. this.mspointer.start();
  29895. this.mousePointer.active = true;
  29896. if (this.keyboard)
  29897. {
  29898. this.keyboard.start();
  29899. }
  29900. var _this = this;
  29901. this._onClickTrampoline = function (event) {
  29902. _this.onClickTrampoline(event);
  29903. };
  29904. this.game.canvas.addEventListener('click', this._onClickTrampoline, false);
  29905. },
  29906. /**
  29907. * Stops all of the Input Managers from running.
  29908. *
  29909. * @method Phaser.Input#destroy
  29910. */
  29911. destroy: function () {
  29912. this.mouse.stop();
  29913. this.touch.stop();
  29914. this.mspointer.stop();
  29915. if (this.keyboard)
  29916. {
  29917. this.keyboard.stop();
  29918. }
  29919. if (this.gamepad)
  29920. {
  29921. this.gamepad.stop();
  29922. }
  29923. this.moveCallbacks = [];
  29924. PIXI.CanvasPool.remove(this);
  29925. this.game.canvas.removeEventListener('click', this._onClickTrampoline);
  29926. },
  29927. /**
  29928. * Adds a callback that is fired every time the activePointer receives a DOM move event such as a mousemove or touchmove.
  29929. *
  29930. * The callback will be sent 4 parameters: The Pointer that moved, the x position of the pointer, the y position and the down state.
  29931. *
  29932. * It will be called every time the activePointer moves, which in a multi-touch game can be a lot of times, so this is best
  29933. * to only use if you've limited input to a single pointer (i.e. mouse or touch).
  29934. *
  29935. * The callback is added to the Phaser.Input.moveCallbacks array and should be removed with Phaser.Input.deleteMoveCallback.
  29936. *
  29937. * @method Phaser.Input#addMoveCallback
  29938. * @param {function} callback - The callback that will be called each time the activePointer receives a DOM move event.
  29939. * @param {object} context - The context in which the callback will be called.
  29940. */
  29941. addMoveCallback: function (callback, context) {
  29942. this.moveCallbacks.push({ callback: callback, context: context });
  29943. },
  29944. /**
  29945. * Removes the callback from the Phaser.Input.moveCallbacks array.
  29946. *
  29947. * @method Phaser.Input#deleteMoveCallback
  29948. * @param {function} callback - The callback to be removed.
  29949. * @param {object} context - The context in which the callback exists.
  29950. */
  29951. deleteMoveCallback: function (callback, context) {
  29952. var i = this.moveCallbacks.length;
  29953. while (i--)
  29954. {
  29955. if (this.moveCallbacks[i].callback === callback && this.moveCallbacks[i].context === context)
  29956. {
  29957. this.moveCallbacks.splice(i, 1);
  29958. return;
  29959. }
  29960. }
  29961. },
  29962. /**
  29963. * Add a new Pointer object to the Input Manager.
  29964. * By default Input creates 3 pointer objects: `mousePointer` (not include in part of general pointer pool), `pointer1` and `pointer2`.
  29965. * This method adds an additional pointer, up to a maximum of Phaser.Input.MAX_POINTERS (default of 10).
  29966. *
  29967. * @method Phaser.Input#addPointer
  29968. * @return {Phaser.Pointer|null} The new Pointer object that was created; null if a new pointer could not be added.
  29969. */
  29970. addPointer: function () {
  29971. if (this.pointers.length >= Phaser.Input.MAX_POINTERS)
  29972. {
  29973. console.warn("Phaser.Input.addPointer: Maximum limit of " + Phaser.Input.MAX_POINTERS + " pointers reached.");
  29974. return null;
  29975. }
  29976. var id = this.pointers.length + 1;
  29977. var pointer = new Phaser.Pointer(this.game, id, Phaser.PointerMode.TOUCH);
  29978. this.pointers.push(pointer);
  29979. this['pointer' + id] = pointer;
  29980. return pointer;
  29981. },
  29982. /**
  29983. * Updates the Input Manager. Called by the core Game loop.
  29984. *
  29985. * @method Phaser.Input#update
  29986. * @protected
  29987. */
  29988. update: function () {
  29989. if (this.keyboard)
  29990. {
  29991. this.keyboard.update();
  29992. }
  29993. if (this.pollRate > 0 && this._pollCounter < this.pollRate)
  29994. {
  29995. this._pollCounter++;
  29996. return;
  29997. }
  29998. this.speed.x = this.position.x - this._oldPosition.x;
  29999. this.speed.y = this.position.y - this._oldPosition.y;
  30000. this._oldPosition.copyFrom(this.position);
  30001. this.mousePointer.update();
  30002. if (this.gamepad && this.gamepad.active)
  30003. {
  30004. this.gamepad.update();
  30005. }
  30006. for (var i = 0; i < this.pointers.length; i++)
  30007. {
  30008. this.pointers[i].update();
  30009. }
  30010. this._pollCounter = 0;
  30011. },
  30012. /**
  30013. * Reset all of the Pointers and Input states.
  30014. *
  30015. * The optional `hard` parameter will reset any events or callbacks that may be bound.
  30016. * Input.reset is called automatically during a State change or if a game loses focus / visibility.
  30017. * To control control the reset manually set {@link Phaser.InputManager.resetLocked} to `true`.
  30018. *
  30019. * @method Phaser.Input#reset
  30020. * @public
  30021. * @param {boolean} [hard=false] - A soft reset won't reset any events or callbacks that are bound. A hard reset will.
  30022. */
  30023. reset: function (hard) {
  30024. if (!this.game.isBooted || this.resetLocked)
  30025. {
  30026. return;
  30027. }
  30028. if (hard === undefined) { hard = false; }
  30029. this.mousePointer.reset();
  30030. if (this.keyboard)
  30031. {
  30032. this.keyboard.reset(hard);
  30033. }
  30034. if (this.gamepad)
  30035. {
  30036. this.gamepad.reset();
  30037. }
  30038. for (var i = 0; i < this.pointers.length; i++)
  30039. {
  30040. this.pointers[i].reset();
  30041. }
  30042. if (this.game.canvas.style.cursor !== 'none')
  30043. {
  30044. this.game.canvas.style.cursor = 'inherit';
  30045. }
  30046. if (hard)
  30047. {
  30048. this.onDown.dispose();
  30049. this.onUp.dispose();
  30050. this.onTap.dispose();
  30051. this.onHold.dispose();
  30052. this.onDown = new Phaser.Signal();
  30053. this.onUp = new Phaser.Signal();
  30054. this.onTap = new Phaser.Signal();
  30055. this.onHold = new Phaser.Signal();
  30056. this.moveCallbacks = [];
  30057. }
  30058. this._pollCounter = 0;
  30059. },
  30060. /**
  30061. * Resets the speed and old position properties.
  30062. *
  30063. * @method Phaser.Input#resetSpeed
  30064. * @param {number} x - Sets the oldPosition.x value.
  30065. * @param {number} y - Sets the oldPosition.y value.
  30066. */
  30067. resetSpeed: function (x, y) {
  30068. this._oldPosition.setTo(x, y);
  30069. this.speed.setTo(0, 0);
  30070. },
  30071. /**
  30072. * Find the first free Pointer object and start it, passing in the event data.
  30073. * This is called automatically by Phaser.Touch and Phaser.MSPointer.
  30074. *
  30075. * @method Phaser.Input#startPointer
  30076. * @protected
  30077. * @param {any} event - The event data from the Touch event.
  30078. * @return {Phaser.Pointer} The Pointer object that was started or null if no Pointer object is available.
  30079. */
  30080. startPointer: function (event) {
  30081. if (this.maxPointers >= 0 && this.countActivePointers(this.maxPointers) >= this.maxPointers)
  30082. {
  30083. return null;
  30084. }
  30085. if (!this.pointer1.active)
  30086. {
  30087. return this.pointer1.start(event);
  30088. }
  30089. if (!this.pointer2.active)
  30090. {
  30091. return this.pointer2.start(event);
  30092. }
  30093. for (var i = 2; i < this.pointers.length; i++)
  30094. {
  30095. var pointer = this.pointers[i];
  30096. if (!pointer.active)
  30097. {
  30098. return pointer.start(event);
  30099. }
  30100. }
  30101. return null;
  30102. },
  30103. /**
  30104. * Updates the matching Pointer object, passing in the event data.
  30105. * This is called automatically and should not normally need to be invoked.
  30106. *
  30107. * @method Phaser.Input#updatePointer
  30108. * @protected
  30109. * @param {any} event - The event data from the Touch event.
  30110. * @return {Phaser.Pointer} The Pointer object that was updated; null if no pointer was updated.
  30111. */
  30112. updatePointer: function (event) {
  30113. if (this.pointer1.active && this.pointer1.identifier === event.identifier)
  30114. {
  30115. return this.pointer1.move(event);
  30116. }
  30117. if (this.pointer2.active && this.pointer2.identifier === event.identifier)
  30118. {
  30119. return this.pointer2.move(event);
  30120. }
  30121. for (var i = 2; i < this.pointers.length; i++)
  30122. {
  30123. var pointer = this.pointers[i];
  30124. if (pointer.active && pointer.identifier === event.identifier)
  30125. {
  30126. return pointer.move(event);
  30127. }
  30128. }
  30129. return null;
  30130. },
  30131. /**
  30132. * Stops the matching Pointer object, passing in the event data.
  30133. *
  30134. * @method Phaser.Input#stopPointer
  30135. * @protected
  30136. * @param {any} event - The event data from the Touch event.
  30137. * @return {Phaser.Pointer} The Pointer object that was stopped or null if no Pointer object is available.
  30138. */
  30139. stopPointer: function (event) {
  30140. if (this.pointer1.active && this.pointer1.identifier === event.identifier)
  30141. {
  30142. return this.pointer1.stop(event);
  30143. }
  30144. if (this.pointer2.active && this.pointer2.identifier === event.identifier)
  30145. {
  30146. return this.pointer2.stop(event);
  30147. }
  30148. for (var i = 2; i < this.pointers.length; i++)
  30149. {
  30150. var pointer = this.pointers[i];
  30151. if (pointer.active && pointer.identifier === event.identifier)
  30152. {
  30153. return pointer.stop(event);
  30154. }
  30155. }
  30156. return null;
  30157. },
  30158. /**
  30159. * Returns the total number of active pointers, not exceeding the specified limit
  30160. *
  30161. * @name Phaser.Input#countActivePointers
  30162. * @private
  30163. * @property {integer} [limit=(max pointers)] - Stop counting after this.
  30164. * @return {integer} The number of active pointers, or limit - whichever is less.
  30165. */
  30166. countActivePointers: function (limit) {
  30167. if (limit === undefined) { limit = this.pointers.length; }
  30168. var count = limit;
  30169. for (var i = 0; i < this.pointers.length && count > 0; i++)
  30170. {
  30171. var pointer = this.pointers[i];
  30172. if (pointer.active)
  30173. {
  30174. count--;
  30175. }
  30176. }
  30177. return (limit - count);
  30178. },
  30179. /**
  30180. * Get the first Pointer with the given active state.
  30181. *
  30182. * @method Phaser.Input#getPointer
  30183. * @param {boolean} [isActive=false] - The state the Pointer should be in - active or inactive?
  30184. * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested state.
  30185. */
  30186. getPointer: function (isActive) {
  30187. if (isActive === undefined) { isActive = false; }
  30188. for (var i = 0; i < this.pointers.length; i++)
  30189. {
  30190. var pointer = this.pointers[i];
  30191. if (pointer.active === isActive)
  30192. {
  30193. return pointer;
  30194. }
  30195. }
  30196. return null;
  30197. },
  30198. /**
  30199. * Get the Pointer object whos `identifier` property matches the given identifier value.
  30200. *
  30201. * The identifier property is not set until the Pointer has been used at least once, as its populated by the DOM event.
  30202. * Also it can change every time you press the pointer down, and is not fixed once set.
  30203. * Note: Not all browsers set the identifier property and it's not part of the W3C spec, so you may need getPointerFromId instead.
  30204. *
  30205. * @method Phaser.Input#getPointerFromIdentifier
  30206. * @param {number} identifier - The Pointer.identifier value to search for.
  30207. * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested identifier.
  30208. */
  30209. getPointerFromIdentifier: function (identifier) {
  30210. for (var i = 0; i < this.pointers.length; i++)
  30211. {
  30212. var pointer = this.pointers[i];
  30213. if (pointer.identifier === identifier)
  30214. {
  30215. return pointer;
  30216. }
  30217. }
  30218. return null;
  30219. },
  30220. /**
  30221. * Get the Pointer object whos `pointerId` property matches the given value.
  30222. *
  30223. * The pointerId property is not set until the Pointer has been used at least once, as its populated by the DOM event.
  30224. * Also it can change every time you press the pointer down if the browser recycles it.
  30225. *
  30226. * @method Phaser.Input#getPointerFromId
  30227. * @param {number} pointerId - The `pointerId` (not 'id') value to search for.
  30228. * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested identifier.
  30229. */
  30230. getPointerFromId: function (pointerId) {
  30231. for (var i = 0; i < this.pointers.length; i++)
  30232. {
  30233. var pointer = this.pointers[i];
  30234. if (pointer.pointerId === pointerId)
  30235. {
  30236. return pointer;
  30237. }
  30238. }
  30239. return null;
  30240. },
  30241. /**
  30242. * This will return the local coordinates of the specified displayObject based on the given Pointer.
  30243. *
  30244. * @method Phaser.Input#getLocalPosition
  30245. * @param {Phaser.Sprite|Phaser.Image} displayObject - The DisplayObject to get the local coordinates for.
  30246. * @param {Phaser.Pointer} pointer - The Pointer to use in the check against the displayObject.
  30247. * @return {Phaser.Point} A point containing the coordinates of the Pointer position relative to the DisplayObject.
  30248. */
  30249. getLocalPosition: function (displayObject, pointer, output) {
  30250. if (output === undefined) { output = new Phaser.Point(); }
  30251. var wt = displayObject.worldTransform;
  30252. var id = 1 / (wt.a * wt.d + wt.c * -wt.b);
  30253. return output.setTo(
  30254. wt.d * id * pointer.x + -wt.c * id * pointer.y + (wt.ty * wt.c - wt.tx * wt.d) * id,
  30255. wt.a * id * pointer.y + -wt.b * id * pointer.x + (-wt.ty * wt.a + wt.tx * wt.b) * id
  30256. );
  30257. },
  30258. /**
  30259. * Tests if the pointer hits the given object.
  30260. *
  30261. * @method Phaser.Input#hitTest
  30262. * @param {DisplayObject} displayObject - The displayObject to test for a hit.
  30263. * @param {Phaser.Pointer} pointer - The pointer to use for the test.
  30264. * @param {Phaser.Point} localPoint - The local translated point.
  30265. */
  30266. hitTest: function (displayObject, pointer, localPoint) {
  30267. if (!displayObject.worldVisible)
  30268. {
  30269. return false;
  30270. }
  30271. this.getLocalPosition(displayObject, pointer, this._localPoint);
  30272. localPoint.copyFrom(this._localPoint);
  30273. if (displayObject.hitArea && displayObject.hitArea.contains)
  30274. {
  30275. return (displayObject.hitArea.contains(this._localPoint.x, this._localPoint.y));
  30276. }
  30277. else if (displayObject instanceof Phaser.TileSprite)
  30278. {
  30279. var width = displayObject.width;
  30280. var height = displayObject.height;
  30281. var x1 = -width * displayObject.anchor.x;
  30282. if (this._localPoint.x >= x1 && this._localPoint.x < x1 + width)
  30283. {
  30284. var y1 = -height * displayObject.anchor.y;
  30285. if (this._localPoint.y >= y1 && this._localPoint.y < y1 + height)
  30286. {
  30287. return true;
  30288. }
  30289. }
  30290. }
  30291. else if (displayObject instanceof PIXI.Sprite)
  30292. {
  30293. var width = displayObject.texture.frame.width;
  30294. var height = displayObject.texture.frame.height;
  30295. var x1 = -width * displayObject.anchor.x;
  30296. if (this._localPoint.x >= x1 && this._localPoint.x < x1 + width)
  30297. {
  30298. var y1 = -height * displayObject.anchor.y;
  30299. if (this._localPoint.y >= y1 && this._localPoint.y < y1 + height)
  30300. {
  30301. return true;
  30302. }
  30303. }
  30304. }
  30305. else if (displayObject instanceof Phaser.Graphics)
  30306. {
  30307. for (var i = 0; i < displayObject.graphicsData.length; i++)
  30308. {
  30309. var data = displayObject.graphicsData[i];
  30310. if (!data.fill)
  30311. {
  30312. continue;
  30313. }
  30314. // Only deal with fills..
  30315. if (data.shape && data.shape.contains(this._localPoint.x, this._localPoint.y))
  30316. {
  30317. return true;
  30318. }
  30319. }
  30320. }
  30321. // Didn't hit the parent, does it have any children?
  30322. for (var i = 0, len = displayObject.children.length; i < len; i++)
  30323. {
  30324. if (this.hitTest(displayObject.children[i], pointer, localPoint))
  30325. {
  30326. return true;
  30327. }
  30328. }
  30329. return false;
  30330. },
  30331. /**
  30332. * Used for click trampolines. See {@link Phaser.Pointer.addClickTrampoline}.
  30333. *
  30334. * @method Phaser.Input#onClickTrampoline
  30335. * @private
  30336. */
  30337. onClickTrampoline: function () {
  30338. // It might not always be the active pointer, but this does work on
  30339. // Desktop browsers (read: IE) with Mouse or MSPointer input.
  30340. this.activePointer.processClickTrampolines();
  30341. }
  30342. };
  30343. Phaser.Input.prototype.constructor = Phaser.Input;
  30344. /**
  30345. * The X coordinate of the most recently active pointer.
  30346. * This value takes game scaling into account automatically. See Pointer.screenX/clientX for source values.
  30347. * @name Phaser.Input#x
  30348. * @property {number} x
  30349. */
  30350. Object.defineProperty(Phaser.Input.prototype, "x", {
  30351. get: function () {
  30352. return this._x;
  30353. },
  30354. set: function (value) {
  30355. this._x = Math.floor(value);
  30356. }
  30357. });
  30358. /**
  30359. * The Y coordinate of the most recently active pointer.
  30360. * This value takes game scaling into account automatically. See Pointer.screenY/clientY for source values.
  30361. * @name Phaser.Input#y
  30362. * @property {number} y
  30363. */
  30364. Object.defineProperty(Phaser.Input.prototype, "y", {
  30365. get: function () {
  30366. return this._y;
  30367. },
  30368. set: function (value) {
  30369. this._y = Math.floor(value);
  30370. }
  30371. });
  30372. /**
  30373. * True if the Input is currently poll rate locked.
  30374. * @name Phaser.Input#pollLocked
  30375. * @property {boolean} pollLocked
  30376. * @readonly
  30377. */
  30378. Object.defineProperty(Phaser.Input.prototype, "pollLocked", {
  30379. get: function () {
  30380. return (this.pollRate > 0 && this._pollCounter < this.pollRate);
  30381. }
  30382. });
  30383. /**
  30384. * The total number of inactive Pointers.
  30385. * @name Phaser.Input#totalInactivePointers
  30386. * @property {number} totalInactivePointers
  30387. * @readonly
  30388. */
  30389. Object.defineProperty(Phaser.Input.prototype, "totalInactivePointers", {
  30390. get: function () {
  30391. return this.pointers.length - this.countActivePointers();
  30392. }
  30393. });
  30394. /**
  30395. * The total number of active Pointers, not counting the mouse pointer.
  30396. * @name Phaser.Input#totalActivePointers
  30397. * @property {integers} totalActivePointers
  30398. * @readonly
  30399. */
  30400. Object.defineProperty(Phaser.Input.prototype, "totalActivePointers", {
  30401. get: function () {
  30402. return this.countActivePointers();
  30403. }
  30404. });
  30405. /**
  30406. * The world X coordinate of the most recently active pointer.
  30407. * @name Phaser.Input#worldX
  30408. * @property {number} worldX - The world X coordinate of the most recently active pointer.
  30409. * @readonly
  30410. */
  30411. Object.defineProperty(Phaser.Input.prototype, "worldX", {
  30412. get: function () {
  30413. return this.game.camera.view.x + this.x;
  30414. }
  30415. });
  30416. /**
  30417. * The world Y coordinate of the most recently active pointer.
  30418. * @name Phaser.Input#worldY
  30419. * @property {number} worldY - The world Y coordinate of the most recently active pointer.
  30420. * @readonly
  30421. */
  30422. Object.defineProperty(Phaser.Input.prototype, "worldY", {
  30423. get: function () {
  30424. return this.game.camera.view.y + this.y;
  30425. }
  30426. });
  30427. /**
  30428. * @author Richard Davey <rich@photonstorm.com>
  30429. * @copyright 2016 Photon Storm Ltd.
  30430. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  30431. */
  30432. /**
  30433. * The Mouse class is responsible for handling all aspects of mouse interaction with the browser.
  30434. *
  30435. * It captures and processes mouse events that happen on the game canvas object.
  30436. * It also adds a single `mouseup` listener to `window` which is used to capture the mouse being released
  30437. * when not over the game.
  30438. *
  30439. * You should not normally access this class directly, but instead use a Phaser.Pointer object
  30440. * which normalises all game input for you, including accurate button handling.
  30441. *
  30442. * @class Phaser.Mouse
  30443. * @constructor
  30444. * @param {Phaser.Game} game - A reference to the currently running game.
  30445. */
  30446. Phaser.Mouse = function (game) {
  30447. /**
  30448. * @property {Phaser.Game} game - A reference to the currently running game.
  30449. */
  30450. this.game = game;
  30451. /**
  30452. * @property {Phaser.Input} input - A reference to the Phaser Input Manager.
  30453. * @protected
  30454. */
  30455. this.input = game.input;
  30456. /**
  30457. * @property {object} callbackContext - The context under which callbacks are called.
  30458. */
  30459. this.callbackContext = this.game;
  30460. /**
  30461. * @property {function} mouseDownCallback - A callback that can be fired when the mouse is pressed down.
  30462. */
  30463. this.mouseDownCallback = null;
  30464. /**
  30465. * @property {function} mouseUpCallback - A callback that can be fired when the mouse is released from a pressed down state.
  30466. */
  30467. this.mouseUpCallback = null;
  30468. /**
  30469. * @property {function} mouseOutCallback - A callback that can be fired when the mouse is no longer over the game canvas.
  30470. */
  30471. this.mouseOutCallback = null;
  30472. /**
  30473. * @property {function} mouseOverCallback - A callback that can be fired when the mouse enters the game canvas (usually after a mouseout).
  30474. */
  30475. this.mouseOverCallback = null;
  30476. /**
  30477. * @property {function} mouseWheelCallback - A callback that can be fired when the mousewheel is used.
  30478. */
  30479. this.mouseWheelCallback = null;
  30480. /**
  30481. * @property {boolean} capture - If true the DOM mouse events will have event.preventDefault applied to them, if false they will propagate fully.
  30482. */
  30483. this.capture = false;
  30484. /**
  30485. * This property was removed in Phaser 2.4 and should no longer be used.
  30486. * Instead please see the Pointer button properties such as `Pointer.leftButton`, `Pointer.rightButton` and so on.
  30487. * Or Pointer.button holds the DOM event button value if you require that.
  30488. * @property {number} button
  30489. * @default
  30490. */
  30491. this.button = -1;
  30492. /**
  30493. * The direction of the _last_ mousewheel usage 1 for up -1 for down.
  30494. * @property {number} wheelDelta
  30495. */
  30496. this.wheelDelta = 0;
  30497. /**
  30498. * Mouse input will only be processed if enabled.
  30499. * @property {boolean} enabled
  30500. * @default
  30501. */
  30502. this.enabled = true;
  30503. /**
  30504. * @property {boolean} locked - If the mouse has been Pointer Locked successfully this will be set to true.
  30505. * @default
  30506. */
  30507. this.locked = false;
  30508. /**
  30509. * @property {boolean} stopOnGameOut - If true Pointer.stop will be called if the mouse leaves the game canvas.
  30510. * @default
  30511. */
  30512. this.stopOnGameOut = false;
  30513. /**
  30514. * @property {Phaser.Signal} pointerLock - This event is dispatched when the browser enters or leaves pointer lock state.
  30515. * @default
  30516. */
  30517. this.pointerLock = new Phaser.Signal();
  30518. /**
  30519. * The browser mouse DOM event. Will be null if no mouse event has ever been received.
  30520. * Access this property only inside a Mouse event handler and do not keep references to it.
  30521. * @property {MouseEvent|null} event
  30522. * @default
  30523. */
  30524. this.event = null;
  30525. /**
  30526. * @property {function} _onMouseDown - Internal event handler reference.
  30527. * @private
  30528. */
  30529. this._onMouseDown = null;
  30530. /**
  30531. * @property {function} _onMouseMove - Internal event handler reference.
  30532. * @private
  30533. */
  30534. this._onMouseMove = null;
  30535. /**
  30536. * @property {function} _onMouseUp - Internal event handler reference.
  30537. * @private
  30538. */
  30539. this._onMouseUp = null;
  30540. /**
  30541. * @property {function} _onMouseOut - Internal event handler reference.
  30542. * @private
  30543. */
  30544. this._onMouseOut = null;
  30545. /**
  30546. * @property {function} _onMouseOver - Internal event handler reference.
  30547. * @private
  30548. */
  30549. this._onMouseOver = null;
  30550. /**
  30551. * @property {function} _onMouseWheel - Internal event handler reference.
  30552. * @private
  30553. */
  30554. this._onMouseWheel = null;
  30555. /**
  30556. * Wheel proxy event object, if required. Shared for all wheel events for this mouse.
  30557. * @property {Phaser.Mouse~WheelEventProxy} _wheelEvent
  30558. * @private
  30559. */
  30560. this._wheelEvent = null;
  30561. };
  30562. /**
  30563. * @constant
  30564. * @type {number}
  30565. */
  30566. Phaser.Mouse.NO_BUTTON = -1;
  30567. /**
  30568. * @constant
  30569. * @type {number}
  30570. */
  30571. Phaser.Mouse.LEFT_BUTTON = 0;
  30572. /**
  30573. * @constant
  30574. * @type {number}
  30575. */
  30576. Phaser.Mouse.MIDDLE_BUTTON = 1;
  30577. /**
  30578. * @constant
  30579. * @type {number}
  30580. */
  30581. Phaser.Mouse.RIGHT_BUTTON = 2;
  30582. /**
  30583. * @constant
  30584. * @type {number}
  30585. */
  30586. Phaser.Mouse.BACK_BUTTON = 3;
  30587. /**
  30588. * @constant
  30589. * @type {number}
  30590. */
  30591. Phaser.Mouse.FORWARD_BUTTON = 4;
  30592. /**
  30593. * @constant
  30594. * @type {number}
  30595. */
  30596. Phaser.Mouse.WHEEL_UP = 1;
  30597. /**
  30598. * @constant
  30599. * @type {number}
  30600. */
  30601. Phaser.Mouse.WHEEL_DOWN = -1;
  30602. Phaser.Mouse.prototype = {
  30603. /**
  30604. * Starts the event listeners running.
  30605. * @method Phaser.Mouse#start
  30606. */
  30607. start: function () {
  30608. if (this.game.device.android && this.game.device.chrome === false)
  30609. {
  30610. // Android stock browser fires mouse events even if you preventDefault on the touchStart, so ...
  30611. return;
  30612. }
  30613. if (this._onMouseDown !== null)
  30614. {
  30615. // Avoid setting multiple listeners
  30616. return;
  30617. }
  30618. var _this = this;
  30619. this._onMouseDown = function (event) {
  30620. return _this.onMouseDown(event);
  30621. };
  30622. this._onMouseMove = function (event) {
  30623. return _this.onMouseMove(event);
  30624. };
  30625. this._onMouseUp = function (event) {
  30626. return _this.onMouseUp(event);
  30627. };
  30628. this._onMouseUpGlobal = function (event) {
  30629. return _this.onMouseUpGlobal(event);
  30630. };
  30631. this._onMouseOutGlobal = function (event) {
  30632. return _this.onMouseOutGlobal(event);
  30633. };
  30634. this._onMouseOut = function (event) {
  30635. return _this.onMouseOut(event);
  30636. };
  30637. this._onMouseOver = function (event) {
  30638. return _this.onMouseOver(event);
  30639. };
  30640. this._onMouseWheel = function (event) {
  30641. return _this.onMouseWheel(event);
  30642. };
  30643. var canvas = this.game.canvas;
  30644. canvas.addEventListener('mousedown', this._onMouseDown, true);
  30645. canvas.addEventListener('mousemove', this._onMouseMove, true);
  30646. canvas.addEventListener('mouseup', this._onMouseUp, true);
  30647. if (!this.game.device.cocoonJS)
  30648. {
  30649. window.addEventListener('mouseup', this._onMouseUpGlobal, true);
  30650. window.addEventListener('mouseout', this._onMouseOutGlobal, true);
  30651. canvas.addEventListener('mouseover', this._onMouseOver, true);
  30652. canvas.addEventListener('mouseout', this._onMouseOut, true);
  30653. }
  30654. var wheelEvent = this.game.device.wheelEvent;
  30655. if (wheelEvent)
  30656. {
  30657. canvas.addEventListener(wheelEvent, this._onMouseWheel, true);
  30658. if (wheelEvent === 'mousewheel')
  30659. {
  30660. this._wheelEvent = new WheelEventProxy(-1/40, 1);
  30661. }
  30662. else if (wheelEvent === 'DOMMouseScroll')
  30663. {
  30664. this._wheelEvent = new WheelEventProxy(1, 1);
  30665. }
  30666. }
  30667. },
  30668. /**
  30669. * The internal method that handles the mouse down event from the browser.
  30670. * @method Phaser.Mouse#onMouseDown
  30671. * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event.
  30672. */
  30673. onMouseDown: function (event) {
  30674. this.event = event;
  30675. if (this.capture)
  30676. {
  30677. event.preventDefault();
  30678. }
  30679. if (this.mouseDownCallback)
  30680. {
  30681. this.mouseDownCallback.call(this.callbackContext, event);
  30682. }
  30683. if (!this.input.enabled || !this.enabled)
  30684. {
  30685. return;
  30686. }
  30687. event['identifier'] = 0;
  30688. this.input.mousePointer.start(event);
  30689. },
  30690. /**
  30691. * The internal method that handles the mouse move event from the browser.
  30692. * @method Phaser.Mouse#onMouseMove
  30693. * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event.
  30694. */
  30695. onMouseMove: function (event) {
  30696. this.event = event;
  30697. if (this.capture)
  30698. {
  30699. event.preventDefault();
  30700. }
  30701. if (this.mouseMoveCallback)
  30702. {
  30703. this.mouseMoveCallback.call(this.callbackContext, event);
  30704. }
  30705. if (!this.input.enabled || !this.enabled)
  30706. {
  30707. return;
  30708. }
  30709. event['identifier'] = 0;
  30710. this.input.mousePointer.move(event);
  30711. },
  30712. /**
  30713. * The internal method that handles the mouse up event from the browser.
  30714. * @method Phaser.Mouse#onMouseUp
  30715. * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event.
  30716. */
  30717. onMouseUp: function (event) {
  30718. this.event = event;
  30719. if (this.capture)
  30720. {
  30721. event.preventDefault();
  30722. }
  30723. if (this.mouseUpCallback)
  30724. {
  30725. this.mouseUpCallback.call(this.callbackContext, event);
  30726. }
  30727. if (!this.input.enabled || !this.enabled)
  30728. {
  30729. return;
  30730. }
  30731. event['identifier'] = 0;
  30732. this.input.mousePointer.stop(event);
  30733. },
  30734. /**
  30735. * The internal method that handles the mouse up event from the window.
  30736. *
  30737. * @method Phaser.Mouse#onMouseUpGlobal
  30738. * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event.
  30739. */
  30740. onMouseUpGlobal: function (event) {
  30741. if (!this.input.mousePointer.withinGame)
  30742. {
  30743. if (this.mouseUpCallback)
  30744. {
  30745. this.mouseUpCallback.call(this.callbackContext, event);
  30746. }
  30747. event['identifier'] = 0;
  30748. this.input.mousePointer.stop(event);
  30749. }
  30750. },
  30751. /**
  30752. * The internal method that handles the mouse out event from the window.
  30753. *
  30754. * @method Phaser.Mouse#onMouseOutGlobal
  30755. * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event.
  30756. */
  30757. onMouseOutGlobal: function (event) {
  30758. this.event = event;
  30759. if (this.capture)
  30760. {
  30761. event.preventDefault();
  30762. }
  30763. this.input.mousePointer.withinGame = false;
  30764. if (!this.input.enabled || !this.enabled)
  30765. {
  30766. return;
  30767. }
  30768. // If we get a mouseout event from the window then basically
  30769. // something serious has gone down, usually along the lines of
  30770. // the browser opening a context-menu or similar.
  30771. // On OS X Chrome especially this is bad news, as it blocks
  30772. // us then getting a mouseup event, so we need to force that through.
  30773. //
  30774. // No matter what, we must cancel the left and right buttons
  30775. this.input.mousePointer.stop(event);
  30776. this.input.mousePointer.leftButton.stop(event);
  30777. this.input.mousePointer.rightButton.stop(event);
  30778. },
  30779. /**
  30780. * The internal method that handles the mouse out event from the browser.
  30781. *
  30782. * @method Phaser.Mouse#onMouseOut
  30783. * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event.
  30784. */
  30785. onMouseOut: function (event) {
  30786. this.event = event;
  30787. if (this.capture)
  30788. {
  30789. event.preventDefault();
  30790. }
  30791. this.input.mousePointer.withinGame = false;
  30792. if (this.mouseOutCallback)
  30793. {
  30794. this.mouseOutCallback.call(this.callbackContext, event);
  30795. }
  30796. if (!this.input.enabled || !this.enabled)
  30797. {
  30798. return;
  30799. }
  30800. if (this.stopOnGameOut)
  30801. {
  30802. event['identifier'] = 0;
  30803. this.input.mousePointer.stop(event);
  30804. }
  30805. },
  30806. /**
  30807. * The internal method that handles the mouse over event from the browser.
  30808. *
  30809. * @method Phaser.Mouse#onMouseOver
  30810. * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event.
  30811. */
  30812. onMouseOver: function (event) {
  30813. this.event = event;
  30814. if (this.capture)
  30815. {
  30816. event.preventDefault();
  30817. }
  30818. this.input.mousePointer.withinGame = true;
  30819. if (this.mouseOverCallback)
  30820. {
  30821. this.mouseOverCallback.call(this.callbackContext, event);
  30822. }
  30823. },
  30824. /**
  30825. * The internal method that handles the mouse wheel event from the browser.
  30826. *
  30827. * @method Phaser.Mouse#onMouseWheel
  30828. * @param {MouseEvent} event - The native event from the browser.
  30829. */
  30830. onMouseWheel: function (event) {
  30831. if (this._wheelEvent) {
  30832. event = this._wheelEvent.bindEvent(event);
  30833. }
  30834. this.event = event;
  30835. if (this.capture)
  30836. {
  30837. event.preventDefault();
  30838. }
  30839. // reverse detail for firefox
  30840. this.wheelDelta = Phaser.Math.clamp(-event.deltaY, -1, 1);
  30841. if (this.mouseWheelCallback)
  30842. {
  30843. this.mouseWheelCallback.call(this.callbackContext, event);
  30844. }
  30845. },
  30846. /**
  30847. * If the browser supports it you can request that the pointer be locked to the browser window.
  30848. * This is classically known as 'FPS controls', where the pointer can't leave the browser until the user presses an exit key.
  30849. * If the browser successfully enters a locked state the event Phaser.Mouse.pointerLock will be dispatched and the first parameter will be 'true'.
  30850. * @method Phaser.Mouse#requestPointerLock
  30851. */
  30852. requestPointerLock: function () {
  30853. if (this.game.device.pointerLock)
  30854. {
  30855. var element = this.game.canvas;
  30856. element.requestPointerLock = element.requestPointerLock || element.mozRequestPointerLock || element.webkitRequestPointerLock;
  30857. element.requestPointerLock();
  30858. var _this = this;
  30859. this._pointerLockChange = function (event) {
  30860. return _this.pointerLockChange(event);
  30861. };
  30862. document.addEventListener('pointerlockchange', this._pointerLockChange, true);
  30863. document.addEventListener('mozpointerlockchange', this._pointerLockChange, true);
  30864. document.addEventListener('webkitpointerlockchange', this._pointerLockChange, true);
  30865. }
  30866. },
  30867. /**
  30868. * Internal pointerLockChange handler.
  30869. *
  30870. * @method Phaser.Mouse#pointerLockChange
  30871. * @param {Event} event - The native event from the browser. This gets stored in Mouse.event.
  30872. */
  30873. pointerLockChange: function (event) {
  30874. var element = this.game.canvas;
  30875. if (document.pointerLockElement === element || document.mozPointerLockElement === element || document.webkitPointerLockElement === element)
  30876. {
  30877. // Pointer was successfully locked
  30878. this.locked = true;
  30879. this.pointerLock.dispatch(true, event);
  30880. }
  30881. else
  30882. {
  30883. // Pointer was unlocked
  30884. this.locked = false;
  30885. this.pointerLock.dispatch(false, event);
  30886. }
  30887. },
  30888. /**
  30889. * Internal release pointer lock handler.
  30890. * @method Phaser.Mouse#releasePointerLock
  30891. */
  30892. releasePointerLock: function () {
  30893. document.exitPointerLock = document.exitPointerLock || document.mozExitPointerLock || document.webkitExitPointerLock;
  30894. document.exitPointerLock();
  30895. document.removeEventListener('pointerlockchange', this._pointerLockChange, true);
  30896. document.removeEventListener('mozpointerlockchange', this._pointerLockChange, true);
  30897. document.removeEventListener('webkitpointerlockchange', this._pointerLockChange, true);
  30898. },
  30899. /**
  30900. * Stop the event listeners.
  30901. * @method Phaser.Mouse#stop
  30902. */
  30903. stop: function () {
  30904. var canvas = this.game.canvas;
  30905. canvas.removeEventListener('mousedown', this._onMouseDown, true);
  30906. canvas.removeEventListener('mousemove', this._onMouseMove, true);
  30907. canvas.removeEventListener('mouseup', this._onMouseUp, true);
  30908. canvas.removeEventListener('mouseover', this._onMouseOver, true);
  30909. canvas.removeEventListener('mouseout', this._onMouseOut, true);
  30910. var wheelEvent = this.game.device.wheelEvent;
  30911. if (wheelEvent)
  30912. {
  30913. canvas.removeEventListener(wheelEvent, this._onMouseWheel, true);
  30914. }
  30915. window.removeEventListener('mouseup', this._onMouseUpGlobal, true);
  30916. window.removeEventListener('mouseout', this._onMouseOutGlobal, true);
  30917. document.removeEventListener('pointerlockchange', this._pointerLockChange, true);
  30918. document.removeEventListener('mozpointerlockchange', this._pointerLockChange, true);
  30919. document.removeEventListener('webkitpointerlockchange', this._pointerLockChange, true);
  30920. }
  30921. };
  30922. Phaser.Mouse.prototype.constructor = Phaser.Mouse;
  30923. /* jshint latedef:nofunc */
  30924. /**
  30925. * A purely internal event support class to proxy 'wheelscroll' and 'DOMMouseWheel'
  30926. * events to 'wheel'-like events.
  30927. *
  30928. * See https://developer.mozilla.org/en-US/docs/Web/Events/mousewheel for choosing a scale and delta mode.
  30929. *
  30930. * @method Phaser.Mouse#WheelEventProxy
  30931. * @private
  30932. * @param {number} scaleFactor - Scale factor as applied to wheelDelta/wheelDeltaX or details.
  30933. * @param {integer} deltaMode - The reported delta mode.
  30934. */
  30935. function WheelEventProxy (scaleFactor, deltaMode) {
  30936. /**
  30937. * @property {number} _scaleFactor - Scale factor as applied to wheelDelta/wheelDeltaX or details.
  30938. * @private
  30939. */
  30940. this._scaleFactor = scaleFactor;
  30941. /**
  30942. * @property {number} _deltaMode - The reported delta mode.
  30943. * @private
  30944. */
  30945. this._deltaMode = deltaMode;
  30946. /**
  30947. * @property {any} originalEvent - The original event _currently_ being proxied; the getters will follow suit.
  30948. * @private
  30949. */
  30950. this.originalEvent = null;
  30951. }
  30952. WheelEventProxy.prototype = {};
  30953. WheelEventProxy.prototype.constructor = WheelEventProxy;
  30954. WheelEventProxy.prototype.bindEvent = function (event) {
  30955. // Generate stubs automatically
  30956. if (!WheelEventProxy._stubsGenerated && event)
  30957. {
  30958. var makeBinder = function (name) {
  30959. return function () {
  30960. var v = this.originalEvent[name];
  30961. return typeof v !== 'function' ? v : v.bind(this.originalEvent);
  30962. };
  30963. };
  30964. for (var prop in event)
  30965. {
  30966. if (!(prop in WheelEventProxy.prototype))
  30967. {
  30968. Object.defineProperty(WheelEventProxy.prototype, prop, {
  30969. get: makeBinder(prop)
  30970. });
  30971. }
  30972. }
  30973. WheelEventProxy._stubsGenerated = true;
  30974. }
  30975. this.originalEvent = event;
  30976. return this;
  30977. };
  30978. Object.defineProperties(WheelEventProxy.prototype, {
  30979. "type": { value: "wheel" },
  30980. "deltaMode": { get: function () { return this._deltaMode; } },
  30981. "deltaY": {
  30982. get: function () {
  30983. return (this._scaleFactor * (this.originalEvent.wheelDelta || this.originalEvent.detail)) || 0;
  30984. }
  30985. },
  30986. "deltaX": {
  30987. get: function () {
  30988. return (this._scaleFactor * this.originalEvent.wheelDeltaX) || 0;
  30989. }
  30990. },
  30991. "deltaZ": { value: 0 }
  30992. });
  30993. /**
  30994. * @author Richard Davey <rich@photonstorm.com>
  30995. * @copyright 2016 Photon Storm Ltd.
  30996. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  30997. */
  30998. /**
  30999. * The MSPointer class handles Microsoft touch interactions with the game and the resulting Pointer objects.
  31000. *
  31001. * It will work only in Internet Explorer 10+ and Windows Store or Windows Phone 8 apps using JavaScript.
  31002. * http://msdn.microsoft.com/en-us/library/ie/hh673557(v=vs.85).aspx
  31003. *
  31004. * You should not normally access this class directly, but instead use a Phaser.Pointer object which
  31005. * normalises all game input for you including accurate button handling.
  31006. *
  31007. * Please note that at the current time of writing Phaser does not yet support chorded button interactions:
  31008. * http://www.w3.org/TR/pointerevents/#chorded-button-interactions
  31009. *
  31010. * @class Phaser.MSPointer
  31011. * @constructor
  31012. * @param {Phaser.Game} game - A reference to the currently running game.
  31013. */
  31014. Phaser.MSPointer = function (game) {
  31015. /**
  31016. * @property {Phaser.Game} game - A reference to the currently running game.
  31017. */
  31018. this.game = game;
  31019. /**
  31020. * @property {Phaser.Input} input - A reference to the Phaser Input Manager.
  31021. * @protected
  31022. */
  31023. this.input = game.input;
  31024. /**
  31025. * @property {object} callbackContext - The context under which callbacks are called (defaults to game).
  31026. */
  31027. this.callbackContext = this.game;
  31028. /**
  31029. * @property {function} pointerDownCallback - A callback that can be fired on a MSPointerDown event.
  31030. */
  31031. this.pointerDownCallback = null;
  31032. /**
  31033. * @property {function} pointerMoveCallback - A callback that can be fired on a MSPointerMove event.
  31034. */
  31035. this.pointerMoveCallback = null;
  31036. /**
  31037. * @property {function} pointerUpCallback - A callback that can be fired on a MSPointerUp event.
  31038. */
  31039. this.pointerUpCallback = null;
  31040. /**
  31041. * @property {boolean} capture - If true the Pointer events will have event.preventDefault applied to them, if false they will propagate fully.
  31042. */
  31043. this.capture = true;
  31044. /**
  31045. * This property was removed in Phaser 2.4 and should no longer be used.
  31046. * Instead please see the Pointer button properties such as `Pointer.leftButton`, `Pointer.rightButton` and so on.
  31047. * Or Pointer.button holds the DOM event button value if you require that.
  31048. * @property {number} button
  31049. */
  31050. this.button = -1;
  31051. /**
  31052. * The browser MSPointer DOM event. Will be null if no event has ever been received.
  31053. * Access this property only inside a Pointer event handler and do not keep references to it.
  31054. * @property {MSPointerEvent|null} event
  31055. * @default
  31056. */
  31057. this.event = null;
  31058. /**
  31059. * MSPointer input will only be processed if enabled.
  31060. * @property {boolean} enabled
  31061. * @default
  31062. */
  31063. this.enabled = true;
  31064. /**
  31065. * @property {function} _onMSPointerDown - Internal function to handle MSPointer events.
  31066. * @private
  31067. */
  31068. this._onMSPointerDown = null;
  31069. /**
  31070. * @property {function} _onMSPointerMove - Internal function to handle MSPointer events.
  31071. * @private
  31072. */
  31073. this._onMSPointerMove = null;
  31074. /**
  31075. * @property {function} _onMSPointerUp - Internal function to handle MSPointer events.
  31076. * @private
  31077. */
  31078. this._onMSPointerUp = null;
  31079. /**
  31080. * @property {function} _onMSPointerUpGlobal - Internal function to handle MSPointer events.
  31081. * @private
  31082. */
  31083. this._onMSPointerUpGlobal = null;
  31084. /**
  31085. * @property {function} _onMSPointerOut - Internal function to handle MSPointer events.
  31086. * @private
  31087. */
  31088. this._onMSPointerOut = null;
  31089. /**
  31090. * @property {function} _onMSPointerOver - Internal function to handle MSPointer events.
  31091. * @private
  31092. */
  31093. this._onMSPointerOver = null;
  31094. };
  31095. Phaser.MSPointer.prototype = {
  31096. /**
  31097. * Starts the event listeners running.
  31098. * @method Phaser.MSPointer#start
  31099. */
  31100. start: function () {
  31101. if (this._onMSPointerDown !== null)
  31102. {
  31103. // Avoid setting multiple listeners
  31104. return;
  31105. }
  31106. var _this = this;
  31107. if (this.game.device.mspointer)
  31108. {
  31109. this._onMSPointerDown = function (event) {
  31110. return _this.onPointerDown(event);
  31111. };
  31112. this._onMSPointerMove = function (event) {
  31113. return _this.onPointerMove(event);
  31114. };
  31115. this._onMSPointerUp = function (event) {
  31116. return _this.onPointerUp(event);
  31117. };
  31118. this._onMSPointerUpGlobal = function (event) {
  31119. return _this.onPointerUpGlobal(event);
  31120. };
  31121. this._onMSPointerOut = function (event) {
  31122. return _this.onPointerOut(event);
  31123. };
  31124. this._onMSPointerOver = function (event) {
  31125. return _this.onPointerOver(event);
  31126. };
  31127. var canvas = this.game.canvas;
  31128. canvas.addEventListener('MSPointerDown', this._onMSPointerDown, false);
  31129. canvas.addEventListener('MSPointerMove', this._onMSPointerMove, false);
  31130. canvas.addEventListener('MSPointerUp', this._onMSPointerUp, false);
  31131. // IE11+ uses non-prefix events
  31132. canvas.addEventListener('pointerdown', this._onMSPointerDown, false);
  31133. canvas.addEventListener('pointermove', this._onMSPointerMove, false);
  31134. canvas.addEventListener('pointerup', this._onMSPointerUp, false);
  31135. canvas.style['-ms-content-zooming'] = 'none';
  31136. canvas.style['-ms-touch-action'] = 'none';
  31137. if (!this.game.device.cocoonJS)
  31138. {
  31139. window.addEventListener('MSPointerUp', this._onMSPointerUpGlobal, true);
  31140. canvas.addEventListener('MSPointerOver', this._onMSPointerOver, true);
  31141. canvas.addEventListener('MSPointerOut', this._onMSPointerOut, true);
  31142. // IE11+ uses non-prefix events
  31143. window.addEventListener('pointerup', this._onMSPointerUpGlobal, true);
  31144. canvas.addEventListener('pointerover', this._onMSPointerOver, true);
  31145. canvas.addEventListener('pointerout', this._onMSPointerOut, true);
  31146. }
  31147. }
  31148. },
  31149. /**
  31150. * The function that handles the PointerDown event.
  31151. *
  31152. * @method Phaser.MSPointer#onPointerDown
  31153. * @param {PointerEvent} event - The native DOM event.
  31154. */
  31155. onPointerDown: function (event) {
  31156. this.event = event;
  31157. if (this.capture)
  31158. {
  31159. event.preventDefault();
  31160. }
  31161. if (this.pointerDownCallback)
  31162. {
  31163. this.pointerDownCallback.call(this.callbackContext, event);
  31164. }
  31165. if (!this.input.enabled || !this.enabled)
  31166. {
  31167. return;
  31168. }
  31169. event.identifier = event.pointerId;
  31170. if (event.pointerType === 'mouse' || event.pointerType === 0x00000004)
  31171. {
  31172. this.input.mousePointer.start(event);
  31173. }
  31174. else
  31175. {
  31176. this.input.startPointer(event);
  31177. }
  31178. },
  31179. /**
  31180. * The function that handles the PointerMove event.
  31181. * @method Phaser.MSPointer#onPointerMove
  31182. * @param {PointerEvent} event - The native DOM event.
  31183. */
  31184. onPointerMove: function (event) {
  31185. this.event = event;
  31186. if (this.capture)
  31187. {
  31188. event.preventDefault();
  31189. }
  31190. if (this.pointerMoveCallback)
  31191. {
  31192. this.pointerMoveCallback.call(this.callbackContext, event);
  31193. }
  31194. if (!this.input.enabled || !this.enabled)
  31195. {
  31196. return;
  31197. }
  31198. event.identifier = event.pointerId;
  31199. if (event.pointerType === 'mouse' || event.pointerType === 0x00000004)
  31200. {
  31201. this.input.mousePointer.move(event);
  31202. }
  31203. else
  31204. {
  31205. this.input.updatePointer(event);
  31206. }
  31207. },
  31208. /**
  31209. * The function that handles the PointerUp event.
  31210. * @method Phaser.MSPointer#onPointerUp
  31211. * @param {PointerEvent} event - The native DOM event.
  31212. */
  31213. onPointerUp: function (event) {
  31214. this.event = event;
  31215. if (this.capture)
  31216. {
  31217. event.preventDefault();
  31218. }
  31219. if (this.pointerUpCallback)
  31220. {
  31221. this.pointerUpCallback.call(this.callbackContext, event);
  31222. }
  31223. if (!this.input.enabled || !this.enabled)
  31224. {
  31225. return;
  31226. }
  31227. event.identifier = event.pointerId;
  31228. if (event.pointerType === 'mouse' || event.pointerType === 0x00000004)
  31229. {
  31230. this.input.mousePointer.stop(event);
  31231. }
  31232. else
  31233. {
  31234. this.input.stopPointer(event);
  31235. }
  31236. },
  31237. /**
  31238. * The internal method that handles the mouse up event from the window.
  31239. *
  31240. * @method Phaser.MSPointer#onPointerUpGlobal
  31241. * @param {PointerEvent} event - The native event from the browser. This gets stored in MSPointer.event.
  31242. */
  31243. onPointerUpGlobal: function (event) {
  31244. if ((event.pointerType === 'mouse' || event.pointerType === 0x00000004) && !this.input.mousePointer.withinGame)
  31245. {
  31246. this.onPointerUp(event);
  31247. }
  31248. else
  31249. {
  31250. var pointer = this.input.getPointerFromIdentifier(event.identifier);
  31251. if (pointer && pointer.withinGame)
  31252. {
  31253. this.onPointerUp(event);
  31254. }
  31255. }
  31256. },
  31257. /**
  31258. * The internal method that handles the pointer out event from the browser.
  31259. *
  31260. * @method Phaser.MSPointer#onPointerOut
  31261. * @param {PointerEvent} event - The native event from the browser. This gets stored in MSPointer.event.
  31262. */
  31263. onPointerOut: function (event) {
  31264. this.event = event;
  31265. if (this.capture)
  31266. {
  31267. event.preventDefault();
  31268. }
  31269. if (event.pointerType === 'mouse' || event.pointerType === 0x00000004)
  31270. {
  31271. this.input.mousePointer.withinGame = false;
  31272. }
  31273. else
  31274. {
  31275. var pointer = this.input.getPointerFromIdentifier(event.identifier);
  31276. if (pointer)
  31277. {
  31278. pointer.withinGame = false;
  31279. }
  31280. }
  31281. if (this.input.mouse.mouseOutCallback)
  31282. {
  31283. this.input.mouse.mouseOutCallback.call(this.input.mouse.callbackContext, event);
  31284. }
  31285. if (!this.input.enabled || !this.enabled)
  31286. {
  31287. return;
  31288. }
  31289. if (this.input.mouse.stopOnGameOut)
  31290. {
  31291. event['identifier'] = 0;
  31292. if (pointer)
  31293. {
  31294. pointer.stop(event);
  31295. }
  31296. else
  31297. {
  31298. this.input.mousePointer.stop(event);
  31299. }
  31300. }
  31301. },
  31302. /**
  31303. * The internal method that handles the pointer out event from the browser.
  31304. *
  31305. * @method Phaser.MSPointer#onPointerOut
  31306. * @param {PointerEvent} event - The native event from the browser. This gets stored in MSPointer.event.
  31307. */
  31308. onPointerOver: function (event) {
  31309. this.event = event;
  31310. if (this.capture)
  31311. {
  31312. event.preventDefault();
  31313. }
  31314. if (event.pointerType === 'mouse' || event.pointerType === 0x00000004)
  31315. {
  31316. this.input.mousePointer.withinGame = true;
  31317. }
  31318. else
  31319. {
  31320. var pointer = this.input.getPointerFromIdentifier(event.identifier);
  31321. if (pointer)
  31322. {
  31323. pointer.withinGame = true;
  31324. }
  31325. }
  31326. if (this.input.mouse.mouseOverCallback)
  31327. {
  31328. this.input.mouse.mouseOverCallback.call(this.input.mouse.callbackContext, event);
  31329. }
  31330. },
  31331. /**
  31332. * Stop the event listeners.
  31333. * @method Phaser.MSPointer#stop
  31334. */
  31335. stop: function () {
  31336. var canvas = this.game.canvas;
  31337. canvas.removeEventListener('MSPointerDown', this._onMSPointerDown, false);
  31338. canvas.removeEventListener('MSPointerMove', this._onMSPointerMove, false);
  31339. canvas.removeEventListener('MSPointerUp', this._onMSPointerUp, false);
  31340. // IE11+ uses non-prefix events
  31341. canvas.removeEventListener('pointerdown', this._onMSPointerDown, false);
  31342. canvas.removeEventListener('pointermove', this._onMSPointerMove, false);
  31343. canvas.removeEventListener('pointerup', this._onMSPointerUp, false);
  31344. window.removeEventListener('MSPointerUp', this._onMSPointerUpGlobal, true);
  31345. canvas.removeEventListener('MSPointerOver', this._onMSPointerOver, true);
  31346. canvas.removeEventListener('MSPointerOut', this._onMSPointerOut, true);
  31347. // IE11+ uses non-prefix events
  31348. window.removeEventListener('pointerup', this._onMSPointerUpGlobal, true);
  31349. canvas.removeEventListener('pointerover', this._onMSPointerOver, true);
  31350. canvas.removeEventListener('pointerout', this._onMSPointerOut, true);
  31351. }
  31352. };
  31353. Phaser.MSPointer.prototype.constructor = Phaser.MSPointer;
  31354. /**
  31355. * @author Richard Davey <rich@photonstorm.com>
  31356. * @author @karlmacklin <tacklemcclean@gmail.com>
  31357. * @copyright 2016 Photon Storm Ltd.
  31358. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  31359. */
  31360. /**
  31361. * DeviceButtons belong to both `Phaser.Pointer` and `Phaser.SinglePad` (Gamepad) instances.
  31362. *
  31363. * For Pointers they represent the various buttons that can exist on mice and pens, such as the left button, right button,
  31364. * middle button and advanced buttons like back and forward.
  31365. *
  31366. * Access them via `Pointer.leftbutton`, `Pointer.rightButton` and so on.
  31367. *
  31368. * On Gamepads they represent all buttons on the pad: from shoulder buttons to action buttons.
  31369. *
  31370. * At the time of writing this there are device limitations you should be aware of:
  31371. *
  31372. * - On Windows, if you install a mouse driver, and its utility software allows you to customize button actions
  31373. * (e.g., IntelliPoint and SetPoint), the middle (wheel) button, the 4th button, and the 5th button might not be set,
  31374. * even when they are pressed.
  31375. * - On Linux (GTK), the 4th button and the 5th button are not supported.
  31376. * - On Mac OS X 10.5 there is no platform API for implementing any advanced buttons.
  31377. *
  31378. * @class Phaser.DeviceButton
  31379. * @constructor
  31380. * @param {Phaser.Pointer|Phaser.SinglePad} parent - A reference to the parent of this button. Either a Pointer or a Gamepad.
  31381. * @param {number} buttonCode - The button code this DeviceButton is responsible for.
  31382. */
  31383. Phaser.DeviceButton = function (parent, buttonCode) {
  31384. /**
  31385. * @property {Phaser.Pointer|Phaser.SinglePad} parent - A reference to the Pointer or Gamepad that owns this button.
  31386. */
  31387. this.parent = parent;
  31388. /**
  31389. * @property {Phaser.Game} game - A reference to the currently running game.
  31390. */
  31391. this.game = parent.game;
  31392. /**
  31393. * @property {object} event - The DOM event that caused the change in button state.
  31394. * @default
  31395. */
  31396. this.event = null;
  31397. /**
  31398. * @property {boolean} isDown - The "down" state of the button.
  31399. * @default
  31400. */
  31401. this.isDown = false;
  31402. /**
  31403. * @property {boolean} isUp - The "up" state of the button.
  31404. * @default
  31405. */
  31406. this.isUp = true;
  31407. /**
  31408. * @property {number} timeDown - The timestamp when the button was last pressed down.
  31409. * @default
  31410. */
  31411. this.timeDown = 0;
  31412. /**
  31413. * @property {number} timeUp - The timestamp when the button was last released.
  31414. * @default
  31415. */
  31416. this.timeUp = 0;
  31417. /**
  31418. * Gamepad only.
  31419. * If a button is held down this holds down the number of times the button has 'repeated'.
  31420. * @property {number} repeats
  31421. * @default
  31422. */
  31423. this.repeats = 0;
  31424. /**
  31425. * True if the alt key was held down when this button was last pressed or released.
  31426. * Not supported on Gamepads.
  31427. * @property {boolean} altKey
  31428. * @default
  31429. */
  31430. this.altKey = false;
  31431. /**
  31432. * True if the shift key was held down when this button was last pressed or released.
  31433. * Not supported on Gamepads.
  31434. * @property {boolean} shiftKey
  31435. * @default
  31436. */
  31437. this.shiftKey = false;
  31438. /**
  31439. * True if the control key was held down when this button was last pressed or released.
  31440. * Not supported on Gamepads.
  31441. * @property {boolean} ctrlKey
  31442. * @default
  31443. */
  31444. this.ctrlKey = false;
  31445. /**
  31446. * @property {number} value - Button value. Mainly useful for checking analog buttons (like shoulder triggers) on Gamepads.
  31447. * @default
  31448. */
  31449. this.value = 0;
  31450. /**
  31451. * @property {number} buttonCode - The buttoncode of this button if a Gamepad, or the DOM button event value if a Pointer.
  31452. */
  31453. this.buttonCode = buttonCode;
  31454. /**
  31455. * This Signal is dispatched every time this DeviceButton is pressed down.
  31456. * It is only dispatched once (until the button is released again).
  31457. * When dispatched it sends 2 arguments: A reference to this DeviceButton and the value of the button.
  31458. * @property {Phaser.Signal} onDown
  31459. */
  31460. this.onDown = new Phaser.Signal();
  31461. /**
  31462. * This Signal is dispatched every time this DeviceButton is released from a down state.
  31463. * It is only dispatched once (until the button is pressed again).
  31464. * When dispatched it sends 2 arguments: A reference to this DeviceButton and the value of the button.
  31465. * @property {Phaser.Signal} onUp
  31466. */
  31467. this.onUp = new Phaser.Signal();
  31468. /**
  31469. * Gamepad only.
  31470. * This Signal is dispatched every time this DeviceButton changes floating value (between, but not exactly, 0 and 1).
  31471. * When dispatched it sends 2 arguments: A reference to this DeviceButton and the value of the button.
  31472. * @property {Phaser.Signal} onFloat
  31473. */
  31474. this.onFloat = new Phaser.Signal();
  31475. };
  31476. Phaser.DeviceButton.prototype = {
  31477. /**
  31478. * Called automatically by Phaser.Pointer and Phaser.SinglePad.
  31479. * Handles the button down state.
  31480. *
  31481. * @method Phaser.DeviceButton#start
  31482. * @protected
  31483. * @param {object} [event] - The DOM event that triggered the button change.
  31484. * @param {number} [value] - The button value. Only get for Gamepads.
  31485. */
  31486. start: function (event, value) {
  31487. if (this.isDown)
  31488. {
  31489. return;
  31490. }
  31491. this.isDown = true;
  31492. this.isUp = false;
  31493. this.timeDown = this.game.time.time;
  31494. this.repeats = 0;
  31495. this.event = event;
  31496. this.value = value;
  31497. if (event)
  31498. {
  31499. this.altKey = event.altKey;
  31500. this.shiftKey = event.shiftKey;
  31501. this.ctrlKey = event.ctrlKey;
  31502. }
  31503. this.onDown.dispatch(this, value);
  31504. },
  31505. /**
  31506. * Called automatically by Phaser.Pointer and Phaser.SinglePad.
  31507. * Handles the button up state.
  31508. *
  31509. * @method Phaser.DeviceButton#stop
  31510. * @protected
  31511. * @param {object} [event] - The DOM event that triggered the button change.
  31512. * @param {number} [value] - The button value. Only get for Gamepads.
  31513. */
  31514. stop: function (event, value) {
  31515. if (this.isUp)
  31516. {
  31517. return;
  31518. }
  31519. this.isDown = false;
  31520. this.isUp = true;
  31521. this.timeUp = this.game.time.time;
  31522. this.event = event;
  31523. this.value = value;
  31524. if (event)
  31525. {
  31526. this.altKey = event.altKey;
  31527. this.shiftKey = event.shiftKey;
  31528. this.ctrlKey = event.ctrlKey;
  31529. }
  31530. this.onUp.dispatch(this, value);
  31531. },
  31532. /**
  31533. * Called automatically by Phaser.SinglePad.
  31534. *
  31535. * @method Phaser.DeviceButton#padFloat
  31536. * @protected
  31537. * @param {number} value - Button value
  31538. */
  31539. padFloat: function (value) {
  31540. this.value = value;
  31541. this.onFloat.dispatch(this, value);
  31542. },
  31543. /**
  31544. * Returns the "just pressed" state of this button.
  31545. * Just pressed is considered true if the button was pressed down within the duration given (default 250ms).
  31546. *
  31547. * @method Phaser.DeviceButton#justPressed
  31548. * @param {number} [duration=250] - The duration in ms below which the button is considered as being just pressed.
  31549. * @return {boolean} True if the button is just pressed otherwise false.
  31550. */
  31551. justPressed: function (duration) {
  31552. duration = duration || 250;
  31553. return (this.isDown && (this.timeDown + duration) > this.game.time.time);
  31554. },
  31555. /**
  31556. * Returns the "just released" state of this button.
  31557. * Just released is considered as being true if the button was released within the duration given (default 250ms).
  31558. *
  31559. * @method Phaser.DeviceButton#justReleased
  31560. * @param {number} [duration=250] - The duration in ms below which the button is considered as being just released.
  31561. * @return {boolean} True if the button is just released otherwise false.
  31562. */
  31563. justReleased: function (duration) {
  31564. duration = duration || 250;
  31565. return (this.isUp && (this.timeUp + duration) > this.game.time.time);
  31566. },
  31567. /**
  31568. * Resets this DeviceButton, changing it to an isUp state and resetting the duration and repeats counters.
  31569. *
  31570. * @method Phaser.DeviceButton#reset
  31571. */
  31572. reset: function () {
  31573. this.isDown = false;
  31574. this.isUp = true;
  31575. this.timeDown = this.game.time.time;
  31576. this.repeats = 0;
  31577. this.altKey = false;
  31578. this.shiftKey = false;
  31579. this.ctrlKey = false;
  31580. },
  31581. /**
  31582. * Destroys this DeviceButton, this disposes of the onDown, onUp and onFloat signals
  31583. * and clears the parent and game references.
  31584. *
  31585. * @method Phaser.DeviceButton#destroy
  31586. */
  31587. destroy: function () {
  31588. this.onDown.dispose();
  31589. this.onUp.dispose();
  31590. this.onFloat.dispose();
  31591. this.parent = null;
  31592. this.game = null;
  31593. }
  31594. };
  31595. Phaser.DeviceButton.prototype.constructor = Phaser.DeviceButton;
  31596. /**
  31597. * How long the button has been held down for in milliseconds.
  31598. * If not currently down it returns -1.
  31599. *
  31600. * @name Phaser.DeviceButton#duration
  31601. * @property {number} duration
  31602. * @readonly
  31603. */
  31604. Object.defineProperty(Phaser.DeviceButton.prototype, "duration", {
  31605. get: function () {
  31606. if (this.isUp)
  31607. {
  31608. return -1;
  31609. }
  31610. return this.game.time.time - this.timeDown;
  31611. }
  31612. });
  31613. /**
  31614. * @author Richard Davey <rich@photonstorm.com>
  31615. * @copyright 2016 Photon Storm Ltd.
  31616. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  31617. */
  31618. /**
  31619. * A Pointer object is used by the Mouse, Touch and MSPoint managers and represents a single finger on the touch screen.
  31620. *
  31621. * @class Phaser.Pointer
  31622. * @constructor
  31623. * @param {Phaser.Game} game - A reference to the currently running game.
  31624. * @param {number} id - The ID of the Pointer object within the game. Each game can have up to 10 active pointers.
  31625. * @param {Phaser.PointerMode} pointerMode=(CURSOR|CONTACT) - The operational mode of this pointer, eg. CURSOR or TOUCH.
  31626. */
  31627. Phaser.Pointer = function (game, id, pointerMode) {
  31628. /**
  31629. * @property {Phaser.Game} game - A reference to the currently running game.
  31630. */
  31631. this.game = game;
  31632. /**
  31633. * @property {number} id - The ID of the Pointer object within the game. Each game can have up to 10 active pointers.
  31634. */
  31635. this.id = id;
  31636. /**
  31637. * @property {number} type - The const type of this object.
  31638. * @readonly
  31639. */
  31640. this.type = Phaser.POINTER;
  31641. /**
  31642. * @property {boolean} exists - A Pointer object that exists is allowed to be checked for physics collisions and overlaps.
  31643. * @default
  31644. */
  31645. this.exists = true;
  31646. /**
  31647. * @property {number} identifier - The identifier property of the Pointer as set by the DOM event when this Pointer is started.
  31648. * @default
  31649. */
  31650. this.identifier = 0;
  31651. /**
  31652. * @property {number} pointerId - The pointerId property of the Pointer as set by the DOM event when this Pointer is started. The browser can and will recycle this value.
  31653. * @default
  31654. */
  31655. this.pointerId = null;
  31656. /**
  31657. * @property {Phaser.PointerMode} pointerMode - The operational mode of this pointer.
  31658. */
  31659. this.pointerMode = pointerMode || (Phaser.PointerMode.CURSOR | Phaser.PointerMode.CONTACT);
  31660. /**
  31661. * @property {any} target - The target property of the Pointer as set by the DOM event when this Pointer is started.
  31662. * @default
  31663. */
  31664. this.target = null;
  31665. /**
  31666. * The button property of the most recent DOM event when this Pointer is started.
  31667. * You should not rely on this value for accurate button detection, instead use the Pointer properties
  31668. * `leftButton`, `rightButton`, `middleButton` and so on.
  31669. * @property {any} button
  31670. * @default
  31671. */
  31672. this.button = null;
  31673. /**
  31674. * If this Pointer is a Mouse or Pen / Stylus then you can access its left button directly through this property.
  31675. *
  31676. * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained
  31677. * button control.
  31678. *
  31679. * @property {Phaser.DeviceButton} leftButton
  31680. * @default
  31681. */
  31682. this.leftButton = new Phaser.DeviceButton(this, Phaser.Pointer.LEFT_BUTTON);
  31683. /**
  31684. * If this Pointer is a Mouse or Pen / Stylus then you can access its middle button directly through this property.
  31685. *
  31686. * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained
  31687. * button control.
  31688. *
  31689. * Please see the DeviceButton docs for details on browser button limitations.
  31690. *
  31691. * @property {Phaser.DeviceButton} middleButton
  31692. * @default
  31693. */
  31694. this.middleButton = new Phaser.DeviceButton(this, Phaser.Pointer.MIDDLE_BUTTON);
  31695. /**
  31696. * If this Pointer is a Mouse or Pen / Stylus then you can access its right button directly through this property.
  31697. *
  31698. * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained
  31699. * button control.
  31700. *
  31701. * Please see the DeviceButton docs for details on browser button limitations.
  31702. *
  31703. * @property {Phaser.DeviceButton} rightButton
  31704. * @default
  31705. */
  31706. this.rightButton = new Phaser.DeviceButton(this, Phaser.Pointer.RIGHT_BUTTON);
  31707. /**
  31708. * If this Pointer is a Mouse or Pen / Stylus then you can access its X1 (back) button directly through this property.
  31709. *
  31710. * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained
  31711. * button control.
  31712. *
  31713. * Please see the DeviceButton docs for details on browser button limitations.
  31714. *
  31715. * @property {Phaser.DeviceButton} backButton
  31716. * @default
  31717. */
  31718. this.backButton = new Phaser.DeviceButton(this, Phaser.Pointer.BACK_BUTTON);
  31719. /**
  31720. * If this Pointer is a Mouse or Pen / Stylus then you can access its X2 (forward) button directly through this property.
  31721. *
  31722. * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained
  31723. * button control.
  31724. *
  31725. * Please see the DeviceButton docs for details on browser button limitations.
  31726. *
  31727. * @property {Phaser.DeviceButton} forwardButton
  31728. * @default
  31729. */
  31730. this.forwardButton = new Phaser.DeviceButton(this, Phaser.Pointer.FORWARD_BUTTON);
  31731. /**
  31732. * If this Pointer is a Pen / Stylus then you can access its eraser button directly through this property.
  31733. *
  31734. * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained
  31735. * button control.
  31736. *
  31737. * Please see the DeviceButton docs for details on browser button limitations.
  31738. *
  31739. * @property {Phaser.DeviceButton} eraserButton
  31740. * @default
  31741. */
  31742. this.eraserButton = new Phaser.DeviceButton(this, Phaser.Pointer.ERASER_BUTTON);
  31743. /**
  31744. * @property {boolean} _holdSent - Local private variable to store the status of dispatching a hold event.
  31745. * @private
  31746. * @default
  31747. */
  31748. this._holdSent = false;
  31749. /**
  31750. * @property {array} _history - Local private variable storing the short-term history of pointer movements.
  31751. * @private
  31752. */
  31753. this._history = [];
  31754. /**
  31755. * @property {number} _nextDrop - Local private variable storing the time at which the next history drop should occur.
  31756. * @private
  31757. */
  31758. this._nextDrop = 0;
  31759. /**
  31760. * @property {boolean} _stateReset - Monitor events outside of a state reset loop.
  31761. * @private
  31762. */
  31763. this._stateReset = false;
  31764. /**
  31765. * @property {boolean} withinGame - true if the Pointer is over the game canvas, otherwise false.
  31766. */
  31767. this.withinGame = false;
  31768. /**
  31769. * @property {number} clientX - The horizontal coordinate of the Pointer within the application's client area at which the event occurred (as opposed to the coordinates within the page).
  31770. */
  31771. this.clientX = -1;
  31772. /**
  31773. * @property {number} clientY - The vertical coordinate of the Pointer within the application's client area at which the event occurred (as opposed to the coordinates within the page).
  31774. */
  31775. this.clientY = -1;
  31776. /**
  31777. * @property {number} pageX - The horizontal coordinate of the Pointer relative to whole document.
  31778. */
  31779. this.pageX = -1;
  31780. /**
  31781. * @property {number} pageY - The vertical coordinate of the Pointer relative to whole document.
  31782. */
  31783. this.pageY = -1;
  31784. /**
  31785. * @property {number} screenX - The horizontal coordinate of the Pointer relative to the screen.
  31786. */
  31787. this.screenX = -1;
  31788. /**
  31789. * @property {number} screenY - The vertical coordinate of the Pointer relative to the screen.
  31790. */
  31791. this.screenY = -1;
  31792. /**
  31793. * @property {number} rawMovementX - The horizontal raw relative movement of the Pointer in pixels since last event.
  31794. * @default
  31795. */
  31796. this.rawMovementX = 0;
  31797. /**
  31798. * @property {number} rawMovementY - The vertical raw relative movement of the Pointer in pixels since last event.
  31799. * @default
  31800. */
  31801. this.rawMovementY = 0;
  31802. /**
  31803. * @property {number} movementX - The horizontal processed relative movement of the Pointer in pixels since last event.
  31804. * @default
  31805. */
  31806. this.movementX = 0;
  31807. /**
  31808. * @property {number} movementY - The vertical processed relative movement of the Pointer in pixels since last event.
  31809. * @default
  31810. */
  31811. this.movementY = 0;
  31812. /**
  31813. * @property {number} x - The horizontal coordinate of the Pointer. This value is automatically scaled based on the game scale.
  31814. * @default
  31815. */
  31816. this.x = -1;
  31817. /**
  31818. * @property {number} y - The vertical coordinate of the Pointer. This value is automatically scaled based on the game scale.
  31819. * @default
  31820. */
  31821. this.y = -1;
  31822. /**
  31823. * @property {boolean} isMouse - If the Pointer is a mouse or pen / stylus this is true, otherwise false.
  31824. */
  31825. this.isMouse = (id === 0);
  31826. /**
  31827. * If the Pointer is touching the touchscreen, or *any* mouse or pen button is held down, isDown is set to true.
  31828. * If you need to check a specific mouse or pen button then use the button properties, i.e. Pointer.rightButton.isDown.
  31829. * @property {boolean} isDown
  31830. * @default
  31831. */
  31832. this.isDown = false;
  31833. /**
  31834. * If the Pointer is not touching the touchscreen, or *all* mouse or pen buttons are up, isUp is set to true.
  31835. * If you need to check a specific mouse or pen button then use the button properties, i.e. Pointer.rightButton.isUp.
  31836. * @property {boolean} isUp
  31837. * @default
  31838. */
  31839. this.isUp = true;
  31840. /**
  31841. * @property {number} timeDown - A timestamp representing when the Pointer first touched the touchscreen.
  31842. * @default
  31843. */
  31844. this.timeDown = 0;
  31845. /**
  31846. * @property {number} timeUp - A timestamp representing when the Pointer left the touchscreen.
  31847. * @default
  31848. */
  31849. this.timeUp = 0;
  31850. /**
  31851. * @property {number} previousTapTime - A timestamp representing when the Pointer was last tapped or clicked.
  31852. * @default
  31853. */
  31854. this.previousTapTime = 0;
  31855. /**
  31856. * @property {number} totalTouches - The total number of times this Pointer has been touched to the touchscreen.
  31857. * @default
  31858. */
  31859. this.totalTouches = 0;
  31860. /**
  31861. * @property {number} msSinceLastClick - The number of milliseconds since the last click or touch event.
  31862. * @default
  31863. */
  31864. this.msSinceLastClick = Number.MAX_VALUE;
  31865. /**
  31866. * @property {any} targetObject - The Game Object this Pointer is currently over / touching / dragging.
  31867. * @default
  31868. */
  31869. this.targetObject = null;
  31870. /**
  31871. * @property {boolean} active - An active pointer is one that is currently pressed down on the display. A Mouse is always active.
  31872. * @default
  31873. */
  31874. this.active = false;
  31875. /**
  31876. * @property {boolean} dirty - A dirty pointer needs to re-poll any interactive objects it may have been over, regardless if it has moved or not.
  31877. * @default
  31878. */
  31879. this.dirty = false;
  31880. /**
  31881. * @property {Phaser.Point} position - A Phaser.Point object containing the current x/y values of the pointer on the display.
  31882. */
  31883. this.position = new Phaser.Point();
  31884. /**
  31885. * @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.
  31886. */
  31887. this.positionDown = new Phaser.Point();
  31888. /**
  31889. * @property {Phaser.Point} positionUp - A Phaser.Point object containing the x/y values of the pointer when it was last released.
  31890. */
  31891. this.positionUp = new Phaser.Point();
  31892. /**
  31893. * A Phaser.Circle that is centered on the x/y coordinates of this pointer, useful for hit detection.
  31894. * The Circle size is 44px (Apples recommended "finger tip" size).
  31895. * @property {Phaser.Circle} circle
  31896. */
  31897. this.circle = new Phaser.Circle(0, 0, 44);
  31898. /**
  31899. * Click trampolines associated with this pointer. See `addClickTrampoline`.
  31900. * @property {object[]|null} _clickTrampolines
  31901. * @private
  31902. */
  31903. this._clickTrampolines = null;
  31904. /**
  31905. * When the Pointer has click trampolines the last target object is stored here
  31906. * so it can be used to check for validity of the trampoline in a post-Up/'stop'.
  31907. * @property {object} _trampolineTargetObject
  31908. * @private
  31909. */
  31910. this._trampolineTargetObject = null;
  31911. };
  31912. /**
  31913. * No buttons at all.
  31914. * @constant
  31915. * @type {number}
  31916. */
  31917. Phaser.Pointer.NO_BUTTON = 0;
  31918. /**
  31919. * The Left Mouse button, or in PointerEvent devices a Touch contact or Pen contact.
  31920. * @constant
  31921. * @type {number}
  31922. */
  31923. Phaser.Pointer.LEFT_BUTTON = 1;
  31924. /**
  31925. * The Right Mouse button, or in PointerEvent devices a Pen contact with a barrel button.
  31926. * @constant
  31927. * @type {number}
  31928. */
  31929. Phaser.Pointer.RIGHT_BUTTON = 2;
  31930. /**
  31931. * The Middle Mouse button.
  31932. * @constant
  31933. * @type {number}
  31934. */
  31935. Phaser.Pointer.MIDDLE_BUTTON = 4;
  31936. /**
  31937. * The X1 button. This is typically the mouse Back button, but is often reconfigured.
  31938. * On Linux (GTK) this is unsupported. On Windows if advanced pointer software (such as IntelliPoint) is installed this doesn't register.
  31939. * @constant
  31940. * @type {number}
  31941. */
  31942. Phaser.Pointer.BACK_BUTTON = 8;
  31943. /**
  31944. * The X2 button. This is typically the mouse Forward button, but is often reconfigured.
  31945. * On Linux (GTK) this is unsupported. On Windows if advanced pointer software (such as IntelliPoint) is installed this doesn't register.
  31946. * @constant
  31947. * @type {number}
  31948. */
  31949. Phaser.Pointer.FORWARD_BUTTON = 16;
  31950. /**
  31951. * The Eraser pen button on PointerEvent supported devices only.
  31952. * @constant
  31953. * @type {number}
  31954. */
  31955. Phaser.Pointer.ERASER_BUTTON = 32;
  31956. Phaser.Pointer.prototype = {
  31957. /**
  31958. * Resets the states of all the button booleans.
  31959. *
  31960. * @method Phaser.Pointer#resetButtons
  31961. * @protected
  31962. */
  31963. resetButtons: function () {
  31964. this.isDown = false;
  31965. this.isUp = true;
  31966. if (this.isMouse)
  31967. {
  31968. this.leftButton.reset();
  31969. this.middleButton.reset();
  31970. this.rightButton.reset();
  31971. this.backButton.reset();
  31972. this.forwardButton.reset();
  31973. this.eraserButton.reset();
  31974. }
  31975. },
  31976. /**
  31977. * Called by updateButtons.
  31978. *
  31979. * @method Phaser.Pointer#processButtonsDown
  31980. * @private
  31981. * @param {integer} buttons - The DOM event.buttons property.
  31982. * @param {MouseEvent} event - The DOM event.
  31983. */
  31984. processButtonsDown: function (buttons, event) {
  31985. // Note: These are bitwise checks, not booleans
  31986. if (Phaser.Pointer.LEFT_BUTTON & buttons)
  31987. {
  31988. this.leftButton.start(event);
  31989. }
  31990. if (Phaser.Pointer.RIGHT_BUTTON & buttons)
  31991. {
  31992. this.rightButton.start(event);
  31993. }
  31994. if (Phaser.Pointer.MIDDLE_BUTTON & buttons)
  31995. {
  31996. this.middleButton.start(event);
  31997. }
  31998. if (Phaser.Pointer.BACK_BUTTON & buttons)
  31999. {
  32000. this.backButton.start(event);
  32001. }
  32002. if (Phaser.Pointer.FORWARD_BUTTON & buttons)
  32003. {
  32004. this.forwardButton.start(event);
  32005. }
  32006. if (Phaser.Pointer.ERASER_BUTTON & buttons)
  32007. {
  32008. this.eraserButton.start(event);
  32009. }
  32010. },
  32011. /**
  32012. * Called by updateButtons.
  32013. *
  32014. * @method Phaser.Pointer#processButtonsUp
  32015. * @private
  32016. * @param {integer} buttons - The DOM event.buttons property.
  32017. * @param {MouseEvent} event - The DOM event.
  32018. */
  32019. processButtonsUp: function (button, event) {
  32020. // Note: These are bitwise checks, not booleans
  32021. if (button === Phaser.Mouse.LEFT_BUTTON)
  32022. {
  32023. this.leftButton.stop(event);
  32024. }
  32025. if (button === Phaser.Mouse.RIGHT_BUTTON)
  32026. {
  32027. this.rightButton.stop(event);
  32028. }
  32029. if (button === Phaser.Mouse.MIDDLE_BUTTON)
  32030. {
  32031. this.middleButton.stop(event);
  32032. }
  32033. if (button === Phaser.Mouse.BACK_BUTTON)
  32034. {
  32035. this.backButton.stop(event);
  32036. }
  32037. if (button === Phaser.Mouse.FORWARD_BUTTON)
  32038. {
  32039. this.forwardButton.stop(event);
  32040. }
  32041. if (button === 5)
  32042. {
  32043. this.eraserButton.stop(event);
  32044. }
  32045. },
  32046. /**
  32047. * Called when the event.buttons property changes from zero.
  32048. * Contains a button bitmask.
  32049. *
  32050. * @method Phaser.Pointer#updateButtons
  32051. * @protected
  32052. * @param {MouseEvent} event - The DOM event.
  32053. */
  32054. updateButtons: function (event) {
  32055. this.button = event.button;
  32056. var down = (event.type.toLowerCase().substr(-4) === 'down');
  32057. if (event.buttons !== undefined)
  32058. {
  32059. if (down)
  32060. {
  32061. this.processButtonsDown(event.buttons, event);
  32062. }
  32063. else
  32064. {
  32065. this.processButtonsUp(event.button, event);
  32066. }
  32067. }
  32068. else
  32069. {
  32070. // No buttons property (like Safari on OSX when using a trackpad)
  32071. if (down)
  32072. {
  32073. this.leftButton.start(event);
  32074. }
  32075. else
  32076. {
  32077. this.leftButton.stop(event);
  32078. this.rightButton.stop(event);
  32079. }
  32080. }
  32081. // On OS X (and other devices with trackpads) you have to press CTRL + the pad
  32082. // to initiate a right-click event, so we'll check for that here ONLY if
  32083. // event.buttons = 1 (i.e. they only have a 1 button mouse or trackpad)
  32084. if (event.buttons === 1 && event.ctrlKey && this.leftButton.isDown)
  32085. {
  32086. this.leftButton.stop(event);
  32087. this.rightButton.start(event);
  32088. }
  32089. this.isUp = true;
  32090. this.isDown = false;
  32091. if (this.leftButton.isDown || this.rightButton.isDown || this.middleButton.isDown || this.backButton.isDown || this.forwardButton.isDown || this.eraserButton.isDown)
  32092. {
  32093. this.isUp = false;
  32094. this.isDown = true;
  32095. }
  32096. },
  32097. /**
  32098. * Called when the Pointer is pressed onto the touchscreen.
  32099. * @method Phaser.Pointer#start
  32100. * @param {any} event - The DOM event from the browser.
  32101. */
  32102. start: function (event) {
  32103. var input = this.game.input;
  32104. if (event['pointerId'])
  32105. {
  32106. this.pointerId = event.pointerId;
  32107. }
  32108. this.identifier = event.identifier;
  32109. this.target = event.target;
  32110. if (this.isMouse)
  32111. {
  32112. this.updateButtons(event);
  32113. }
  32114. else
  32115. {
  32116. this.isDown = true;
  32117. this.isUp = false;
  32118. }
  32119. this.active = true;
  32120. this.withinGame = true;
  32121. this.dirty = false;
  32122. this._history = [];
  32123. this._clickTrampolines = null;
  32124. this._trampolineTargetObject = null;
  32125. // Work out how long it has been since the last click
  32126. this.msSinceLastClick = this.game.time.time - this.timeDown;
  32127. this.timeDown = this.game.time.time;
  32128. this._holdSent = false;
  32129. // This sets the x/y and other local values
  32130. this.move(event, true);
  32131. // x and y are the old values here?
  32132. this.positionDown.setTo(this.x, this.y);
  32133. if (input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH ||
  32134. input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE ||
  32135. (input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && input.totalActivePointers === 0))
  32136. {
  32137. input.x = this.x;
  32138. input.y = this.y;
  32139. input.position.setTo(this.x, this.y);
  32140. input.onDown.dispatch(this, event);
  32141. input.resetSpeed(this.x, this.y);
  32142. }
  32143. this._stateReset = false;
  32144. this.totalTouches++;
  32145. if (this.targetObject !== null)
  32146. {
  32147. this.targetObject._touchedHandler(this);
  32148. }
  32149. return this;
  32150. },
  32151. /**
  32152. * Called by the Input Manager.
  32153. * @method Phaser.Pointer#update
  32154. */
  32155. update: function () {
  32156. var input = this.game.input;
  32157. if (this.active)
  32158. {
  32159. // Force a check?
  32160. if (this.dirty)
  32161. {
  32162. if (input.interactiveItems.total > 0)
  32163. {
  32164. this.processInteractiveObjects(false);
  32165. }
  32166. this.dirty = false;
  32167. }
  32168. if (this._holdSent === false && this.duration >= input.holdRate)
  32169. {
  32170. if (input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH ||
  32171. input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE ||
  32172. (input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && input.totalActivePointers === 0))
  32173. {
  32174. input.onHold.dispatch(this);
  32175. }
  32176. this._holdSent = true;
  32177. }
  32178. // Update the droppings history
  32179. if (input.recordPointerHistory && this.game.time.time >= this._nextDrop)
  32180. {
  32181. this._nextDrop = this.game.time.time + input.recordRate;
  32182. this._history.push({
  32183. x: this.position.x,
  32184. y: this.position.y
  32185. });
  32186. if (this._history.length > input.recordLimit)
  32187. {
  32188. this._history.shift();
  32189. }
  32190. }
  32191. }
  32192. },
  32193. /**
  32194. * Called when the Pointer is moved.
  32195. *
  32196. * @method Phaser.Pointer#move
  32197. * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler.
  32198. * @param {boolean} [fromClick=false] - Was this called from the click event?
  32199. */
  32200. move: function (event, fromClick) {
  32201. var input = this.game.input;
  32202. if (input.pollLocked)
  32203. {
  32204. return;
  32205. }
  32206. if (fromClick === undefined) { fromClick = false; }
  32207. if (event.button !== undefined)
  32208. {
  32209. this.button = event.button;
  32210. }
  32211. if (fromClick && this.isMouse)
  32212. {
  32213. this.updateButtons(event);
  32214. }
  32215. this.clientX = event.clientX;
  32216. this.clientY = event.clientY;
  32217. this.pageX = event.pageX;
  32218. this.pageY = event.pageY;
  32219. this.screenX = event.screenX;
  32220. this.screenY = event.screenY;
  32221. if (this.isMouse && input.mouse.locked && !fromClick)
  32222. {
  32223. this.rawMovementX = event.movementX || event.mozMovementX || event.webkitMovementX || 0;
  32224. this.rawMovementY = event.movementY || event.mozMovementY || event.webkitMovementY || 0;
  32225. this.movementX += this.rawMovementX;
  32226. this.movementY += this.rawMovementY;
  32227. }
  32228. this.x = (this.pageX - this.game.scale.offset.x) * input.scale.x;
  32229. this.y = (this.pageY - this.game.scale.offset.y) * input.scale.y;
  32230. this.position.setTo(this.x, this.y);
  32231. this.circle.x = this.x;
  32232. this.circle.y = this.y;
  32233. if (input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH ||
  32234. input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE ||
  32235. (input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && input.totalActivePointers === 0))
  32236. {
  32237. input.activePointer = this;
  32238. input.x = this.x;
  32239. input.y = this.y;
  32240. input.position.setTo(input.x, input.y);
  32241. input.circle.x = input.x;
  32242. input.circle.y = input.y;
  32243. }
  32244. this.withinGame = this.game.scale.bounds.contains(this.pageX, this.pageY);
  32245. // If the game is paused we don't process any target objects or callbacks
  32246. if (this.game.paused)
  32247. {
  32248. return this;
  32249. }
  32250. var i = input.moveCallbacks.length;
  32251. while (i--)
  32252. {
  32253. input.moveCallbacks[i].callback.call(input.moveCallbacks[i].context, this, this.x, this.y, fromClick);
  32254. }
  32255. // Easy out if we're dragging something and it still exists
  32256. if (this.targetObject !== null && this.targetObject.isDragged === true)
  32257. {
  32258. if (this.targetObject.update(this) === false)
  32259. {
  32260. this.targetObject = null;
  32261. }
  32262. }
  32263. else if (input.interactiveItems.total > 0)
  32264. {
  32265. this.processInteractiveObjects(fromClick);
  32266. }
  32267. return this;
  32268. },
  32269. /**
  32270. * Process all interactive objects to find out which ones were updated in the recent Pointer move.
  32271. *
  32272. * @method Phaser.Pointer#processInteractiveObjects
  32273. * @protected
  32274. * @param {boolean} [fromClick=false] - Was this called from the click event?
  32275. * @return {boolean} True if this method processes an object (i.e. a Sprite becomes the Pointers currentTarget), otherwise false.
  32276. */
  32277. processInteractiveObjects: function (fromClick) {
  32278. // Work out which object is on the top
  32279. var highestRenderOrderID = Number.MAX_VALUE;
  32280. var highestInputPriorityID = -1;
  32281. var candidateTarget = null;
  32282. // First pass gets all objects that the pointer is over that DON'T use pixelPerfect checks and get the highest ID
  32283. // We know they'll be valid for input detection but not which is the top just yet
  32284. var currentNode = this.game.input.interactiveItems.first;
  32285. while (currentNode)
  32286. {
  32287. // Reset checked status
  32288. currentNode.checked = false;
  32289. if (currentNode.validForInput(highestInputPriorityID, highestRenderOrderID, false))
  32290. {
  32291. // Flag it as checked so we don't re-scan it on the next phase
  32292. currentNode.checked = true;
  32293. if ((fromClick && currentNode.checkPointerDown(this, true)) ||
  32294. (!fromClick && currentNode.checkPointerOver(this, true)))
  32295. {
  32296. highestRenderOrderID = currentNode.sprite.renderOrderID;
  32297. highestInputPriorityID = currentNode.priorityID;
  32298. candidateTarget = currentNode;
  32299. }
  32300. }
  32301. currentNode = this.game.input.interactiveItems.next;
  32302. }
  32303. // Then in the second sweep we process ONLY the pixel perfect ones that are checked and who have a higher ID
  32304. // because if their ID is lower anyway then we can just automatically discount them
  32305. // (A node that was previously checked did not request a pixel-perfect check.)
  32306. var currentNode = this.game.input.interactiveItems.first;
  32307. while (currentNode)
  32308. {
  32309. if (!currentNode.checked &&
  32310. currentNode.validForInput(highestInputPriorityID, highestRenderOrderID, true))
  32311. {
  32312. if ((fromClick && currentNode.checkPointerDown(this, false)) ||
  32313. (!fromClick && currentNode.checkPointerOver(this, false)))
  32314. {
  32315. highestRenderOrderID = currentNode.sprite.renderOrderID;
  32316. highestInputPriorityID = currentNode.priorityID;
  32317. candidateTarget = currentNode;
  32318. }
  32319. }
  32320. currentNode = this.game.input.interactiveItems.next;
  32321. }
  32322. // Now we know the top-most item (if any) we can process it
  32323. if (candidateTarget === null)
  32324. {
  32325. // The pointer isn't currently over anything, check if we've got a lingering previous target
  32326. if (this.targetObject)
  32327. {
  32328. this.targetObject._pointerOutHandler(this);
  32329. this.targetObject = null;
  32330. }
  32331. }
  32332. else
  32333. {
  32334. if (this.targetObject === null)
  32335. {
  32336. // And now set the new one
  32337. this.targetObject = candidateTarget;
  32338. candidateTarget._pointerOverHandler(this);
  32339. }
  32340. else
  32341. {
  32342. // We've got a target from the last update
  32343. if (this.targetObject === candidateTarget)
  32344. {
  32345. // Same target as before, so update it
  32346. if (candidateTarget.update(this) === false)
  32347. {
  32348. this.targetObject = null;
  32349. }
  32350. }
  32351. else
  32352. {
  32353. // The target has changed, so tell the old one we've left it
  32354. this.targetObject._pointerOutHandler(this);
  32355. // And now set the new one
  32356. this.targetObject = candidateTarget;
  32357. this.targetObject._pointerOverHandler(this);
  32358. }
  32359. }
  32360. }
  32361. return (this.targetObject !== null);
  32362. },
  32363. /**
  32364. * Called when the Pointer leaves the target area.
  32365. *
  32366. * @method Phaser.Pointer#leave
  32367. * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler.
  32368. */
  32369. leave: function (event) {
  32370. this.withinGame = false;
  32371. this.move(event, false);
  32372. },
  32373. /**
  32374. * Called when the Pointer leaves the touchscreen.
  32375. *
  32376. * @method Phaser.Pointer#stop
  32377. * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler.
  32378. */
  32379. stop: function (event) {
  32380. var input = this.game.input;
  32381. if (this._stateReset && this.withinGame)
  32382. {
  32383. event.preventDefault();
  32384. return;
  32385. }
  32386. this.timeUp = this.game.time.time;
  32387. if (input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH ||
  32388. input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE ||
  32389. (input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && input.totalActivePointers === 0))
  32390. {
  32391. input.onUp.dispatch(this, event);
  32392. // Was it a tap?
  32393. if (this.duration >= 0 && this.duration <= input.tapRate)
  32394. {
  32395. // Was it a double-tap?
  32396. if (this.timeUp - this.previousTapTime < input.doubleTapRate)
  32397. {
  32398. // Yes, let's dispatch the signal then with the 2nd parameter set to true
  32399. input.onTap.dispatch(this, true);
  32400. }
  32401. else
  32402. {
  32403. // Wasn't a double-tap, so dispatch a single tap signal
  32404. input.onTap.dispatch(this, false);
  32405. }
  32406. this.previousTapTime = this.timeUp;
  32407. }
  32408. }
  32409. if (this.isMouse)
  32410. {
  32411. this.updateButtons(event);
  32412. }
  32413. else
  32414. {
  32415. this.isDown = false;
  32416. this.isUp = true;
  32417. }
  32418. // Mouse is always active
  32419. if (this.id > 0)
  32420. {
  32421. this.active = false;
  32422. }
  32423. this.withinGame = this.game.scale.bounds.contains(event.pageX, event.pageY);
  32424. this.pointerId = null;
  32425. this.identifier = null;
  32426. this.positionUp.setTo(this.x, this.y);
  32427. if (this.isMouse === false)
  32428. {
  32429. input.currentPointers--;
  32430. }
  32431. input.interactiveItems.callAll('_releasedHandler', this);
  32432. if (this._clickTrampolines)
  32433. {
  32434. this._trampolineTargetObject = this.targetObject;
  32435. }
  32436. this.targetObject = null;
  32437. return this;
  32438. },
  32439. /**
  32440. * The Pointer is considered justPressed if the time it was pressed onto the touchscreen or clicked is less than justPressedRate.
  32441. * 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.
  32442. * If you wish to check if the Pointer was pressed down just once then see the Sprite.events.onInputDown event.
  32443. * @method Phaser.Pointer#justPressed
  32444. * @param {number} [duration] - The time to check against. If none given it will use InputManager.justPressedRate.
  32445. * @return {boolean} true if the Pointer was pressed down within the duration given.
  32446. */
  32447. justPressed: function (duration) {
  32448. duration = duration || this.game.input.justPressedRate;
  32449. return (this.isDown === true && (this.timeDown + duration) > this.game.time.time);
  32450. },
  32451. /**
  32452. * The Pointer is considered justReleased if the time it left the touchscreen is less than justReleasedRate.
  32453. * 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.
  32454. * If you wish to check if the Pointer was released just once then see the Sprite.events.onInputUp event.
  32455. * @method Phaser.Pointer#justReleased
  32456. * @param {number} [duration] - The time to check against. If none given it will use InputManager.justReleasedRate.
  32457. * @return {boolean} true if the Pointer was released within the duration given.
  32458. */
  32459. justReleased: function (duration) {
  32460. duration = duration || this.game.input.justReleasedRate;
  32461. return (this.isUp && (this.timeUp + duration) > this.game.time.time);
  32462. },
  32463. /**
  32464. * Add a click trampoline to this pointer.
  32465. *
  32466. * A click trampoline is a callback that is run on the DOM 'click' event; this is primarily
  32467. * needed with certain browsers (ie. IE11) which restrict some actions like requestFullscreen
  32468. * to the DOM 'click' event and rejects it for 'pointer*' and 'mouse*' events.
  32469. *
  32470. * This is used internally by the ScaleManager; click trampoline usage is uncommon.
  32471. * Click trampolines can only be added to pointers that are currently down.
  32472. *
  32473. * @method Phaser.Pointer#addClickTrampoline
  32474. * @protected
  32475. * @param {string} name - The name of the trampoline; must be unique among active trampolines in this pointer.
  32476. * @param {function} callback - Callback to run/trampoline.
  32477. * @param {object} callbackContext - Context of the callback.
  32478. * @param {object[]|null} callbackArgs - Additional callback args, if any. Supplied as an array.
  32479. */
  32480. addClickTrampoline: function (name, callback, callbackContext, callbackArgs) {
  32481. if (!this.isDown)
  32482. {
  32483. return;
  32484. }
  32485. var trampolines = (this._clickTrampolines = this._clickTrampolines || []);
  32486. for (var i = 0; i < trampolines.length; i++)
  32487. {
  32488. if (trampolines[i].name === name)
  32489. {
  32490. trampolines.splice(i, 1);
  32491. break;
  32492. }
  32493. }
  32494. trampolines.push({
  32495. name: name,
  32496. targetObject: this.targetObject,
  32497. callback: callback,
  32498. callbackContext: callbackContext,
  32499. callbackArgs: callbackArgs
  32500. });
  32501. },
  32502. /**
  32503. * Fire all click trampolines for which the pointers are still referring to the registered object.
  32504. * @method Phaser.Pointer#processClickTrampolines
  32505. * @private
  32506. */
  32507. processClickTrampolines: function () {
  32508. var trampolines = this._clickTrampolines;
  32509. if (!trampolines)
  32510. {
  32511. return;
  32512. }
  32513. for (var i = 0; i < trampolines.length; i++)
  32514. {
  32515. var trampoline = trampolines[i];
  32516. if (trampoline.targetObject === this._trampolineTargetObject)
  32517. {
  32518. trampoline.callback.apply(trampoline.callbackContext, trampoline.callbackArgs);
  32519. }
  32520. }
  32521. this._clickTrampolines = null;
  32522. this._trampolineTargetObject = null;
  32523. },
  32524. /**
  32525. * Resets the Pointer properties. Called by InputManager.reset when you perform a State change.
  32526. * @method Phaser.Pointer#reset
  32527. */
  32528. reset: function () {
  32529. if (this.isMouse === false)
  32530. {
  32531. this.active = false;
  32532. }
  32533. this.pointerId = null;
  32534. this.identifier = null;
  32535. this.dirty = false;
  32536. this.totalTouches = 0;
  32537. this._holdSent = false;
  32538. this._history.length = 0;
  32539. this._stateReset = true;
  32540. this.resetButtons();
  32541. if (this.targetObject)
  32542. {
  32543. this.targetObject._releasedHandler(this);
  32544. }
  32545. this.targetObject = null;
  32546. },
  32547. /**
  32548. * Resets the movementX and movementY properties. Use in your update handler after retrieving the values.
  32549. * @method Phaser.Pointer#resetMovement
  32550. */
  32551. resetMovement: function() {
  32552. this.movementX = 0;
  32553. this.movementY = 0;
  32554. }
  32555. };
  32556. Phaser.Pointer.prototype.constructor = Phaser.Pointer;
  32557. /**
  32558. * How long the Pointer has been depressed on the touchscreen or *any* of the mouse buttons have been held down.
  32559. * If not currently down it returns -1.
  32560. * If you need to test a specific mouse or pen button then access the buttons directly, i.e. `Pointer.rightButton.duration`.
  32561. *
  32562. * @name Phaser.Pointer#duration
  32563. * @property {number} duration
  32564. * @readonly
  32565. */
  32566. Object.defineProperty(Phaser.Pointer.prototype, "duration", {
  32567. get: function () {
  32568. if (this.isUp)
  32569. {
  32570. return -1;
  32571. }
  32572. return this.game.time.time - this.timeDown;
  32573. }
  32574. });
  32575. /**
  32576. * Gets the X value of this Pointer in world coordinates based on the world camera.
  32577. * @name Phaser.Pointer#worldX
  32578. * @property {number} duration - The X value of this Pointer in world coordinates based on the world camera.
  32579. * @readonly
  32580. */
  32581. Object.defineProperty(Phaser.Pointer.prototype, "worldX", {
  32582. get: function () {
  32583. return this.game.world.camera.x + this.x;
  32584. }
  32585. });
  32586. /**
  32587. * Gets the Y value of this Pointer in world coordinates based on the world camera.
  32588. * @name Phaser.Pointer#worldY
  32589. * @property {number} duration - The Y value of this Pointer in world coordinates based on the world camera.
  32590. * @readonly
  32591. */
  32592. Object.defineProperty(Phaser.Pointer.prototype, "worldY", {
  32593. get: function () {
  32594. return this.game.world.camera.y + this.y;
  32595. }
  32596. });
  32597. /**
  32598. * Enumeration categorizing operational modes of pointers.
  32599. *
  32600. * PointerType values represent valid bitmasks.
  32601. * For example, a value representing both Mouse and Touch devices
  32602. * can be expressed as `PointerMode.CURSOR | PointerMode.CONTACT`.
  32603. *
  32604. * Values may be added for future mode categorizations.
  32605. * @class Phaser.PointerMode
  32606. */
  32607. Phaser.PointerMode = {
  32608. /**
  32609. * A 'CURSOR' is a pointer with a *passive cursor* such as a mouse, touchpad, watcom stylus, or even TV-control arrow-pad.
  32610. *
  32611. * It has the property that a cursor is passively moved without activating the input.
  32612. * This currently corresponds with {@link Phaser.Pointer#isMouse} property.
  32613. * @constant
  32614. */
  32615. CURSOR: 1 << 0,
  32616. /**
  32617. * A 'CONTACT' pointer has an *active cursor* that only tracks movement when actived; notably this is a touch-style input.
  32618. * @constant
  32619. */
  32620. CONTACT: 1 << 1
  32621. };
  32622. /**
  32623. * @author Richard Davey <rich@photonstorm.com>
  32624. * @copyright 2016 Photon Storm Ltd.
  32625. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  32626. */
  32627. /**
  32628. * Phaser.Touch handles touch events with your game. Note: Android 2.x only supports 1 touch event at once, no multi-touch.
  32629. *
  32630. * You should not normally access this class directly, but instead use a Phaser.Pointer object which normalises all game input for you.
  32631. *
  32632. * @class Phaser.Touch
  32633. * @constructor
  32634. * @param {Phaser.Game} game - A reference to the currently running game.
  32635. */
  32636. Phaser.Touch = function (game) {
  32637. /**
  32638. * @property {Phaser.Game} game - A reference to the currently running game.
  32639. */
  32640. this.game = game;
  32641. /**
  32642. * Touch events will only be processed if enabled.
  32643. * @property {boolean} enabled
  32644. * @default
  32645. */
  32646. this.enabled = true;
  32647. /**
  32648. * An array of callbacks that will be fired every time a native touch start or touch end event is received from the browser.
  32649. * This is used internally to handle audio and video unlocking on mobile devices.
  32650. * To add a callback to this array please use `Touch.addTouchLockCallback`.
  32651. * @property {array} touchLockCallbacks
  32652. * @protected
  32653. */
  32654. this.touchLockCallbacks = [];
  32655. /**
  32656. * @property {object} callbackContext - The context under which callbacks are called.
  32657. */
  32658. this.callbackContext = this.game;
  32659. /**
  32660. * @property {function} touchStartCallback - A callback that can be fired on a touchStart event.
  32661. */
  32662. this.touchStartCallback = null;
  32663. /**
  32664. * @property {function} touchMoveCallback - A callback that can be fired on a touchMove event.
  32665. */
  32666. this.touchMoveCallback = null;
  32667. /**
  32668. * @property {function} touchEndCallback - A callback that can be fired on a touchEnd event.
  32669. */
  32670. this.touchEndCallback = null;
  32671. /**
  32672. * @property {function} touchEnterCallback - A callback that can be fired on a touchEnter event.
  32673. */
  32674. this.touchEnterCallback = null;
  32675. /**
  32676. * @property {function} touchLeaveCallback - A callback that can be fired on a touchLeave event.
  32677. */
  32678. this.touchLeaveCallback = null;
  32679. /**
  32680. * @property {function} touchCancelCallback - A callback that can be fired on a touchCancel event.
  32681. */
  32682. this.touchCancelCallback = null;
  32683. /**
  32684. * @property {boolean} preventDefault - If true the TouchEvent will have prevent.default called on it.
  32685. * @default
  32686. */
  32687. this.preventDefault = true;
  32688. /**
  32689. * @property {TouchEvent} event - The browser touch DOM event. Will be set to null if no touch event has ever been received.
  32690. * @default
  32691. */
  32692. this.event = null;
  32693. /**
  32694. * @property {function} _onTouchStart - Internal event handler reference.
  32695. * @private
  32696. */
  32697. this._onTouchStart = null;
  32698. /**
  32699. * @property {function} _onTouchMove - Internal event handler reference.
  32700. * @private
  32701. */
  32702. this._onTouchMove = null;
  32703. /**
  32704. * @property {function} _onTouchEnd - Internal event handler reference.
  32705. * @private
  32706. */
  32707. this._onTouchEnd = null;
  32708. /**
  32709. * @property {function} _onTouchEnter - Internal event handler reference.
  32710. * @private
  32711. */
  32712. this._onTouchEnter = null;
  32713. /**
  32714. * @property {function} _onTouchLeave - Internal event handler reference.
  32715. * @private
  32716. */
  32717. this._onTouchLeave = null;
  32718. /**
  32719. * @property {function} _onTouchCancel - Internal event handler reference.
  32720. * @private
  32721. */
  32722. this._onTouchCancel = null;
  32723. /**
  32724. * @property {function} _onTouchMove - Internal event handler reference.
  32725. * @private
  32726. */
  32727. this._onTouchMove = null;
  32728. };
  32729. Phaser.Touch.prototype = {
  32730. /**
  32731. * Starts the event listeners running.
  32732. * @method Phaser.Touch#start
  32733. */
  32734. start: function () {
  32735. if (this._onTouchStart !== null)
  32736. {
  32737. // Avoid setting multiple listeners
  32738. return;
  32739. }
  32740. var _this = this;
  32741. if (this.game.device.touch)
  32742. {
  32743. this._onTouchStart = function (event) {
  32744. return _this.onTouchStart(event);
  32745. };
  32746. this._onTouchMove = function (event) {
  32747. return _this.onTouchMove(event);
  32748. };
  32749. this._onTouchEnd = function (event) {
  32750. return _this.onTouchEnd(event);
  32751. };
  32752. this._onTouchEnter = function (event) {
  32753. return _this.onTouchEnter(event);
  32754. };
  32755. this._onTouchLeave = function (event) {
  32756. return _this.onTouchLeave(event);
  32757. };
  32758. this._onTouchCancel = function (event) {
  32759. return _this.onTouchCancel(event);
  32760. };
  32761. this.game.canvas.addEventListener('touchstart', this._onTouchStart, false);
  32762. this.game.canvas.addEventListener('touchmove', this._onTouchMove, false);
  32763. this.game.canvas.addEventListener('touchend', this._onTouchEnd, false);
  32764. this.game.canvas.addEventListener('touchcancel', this._onTouchCancel, false);
  32765. if (!this.game.device.cocoonJS)
  32766. {
  32767. this.game.canvas.addEventListener('touchenter', this._onTouchEnter, false);
  32768. this.game.canvas.addEventListener('touchleave', this._onTouchLeave, false);
  32769. }
  32770. }
  32771. },
  32772. /**
  32773. * Consumes all touchmove events on the document (only enable this if you know you need it!).
  32774. * @method Phaser.Touch#consumeTouchMove
  32775. */
  32776. consumeDocumentTouches: function () {
  32777. this._documentTouchMove = function (event) {
  32778. event.preventDefault();
  32779. };
  32780. document.addEventListener('touchmove', this._documentTouchMove, false);
  32781. },
  32782. /**
  32783. * Adds a callback that is fired when a browser touchstart or touchend event is received.
  32784. *
  32785. * This is used internally to handle audio and video unlocking on mobile devices.
  32786. *
  32787. * If the callback returns 'true' then the callback is automatically deleted once invoked.
  32788. *
  32789. * The callback is added to the Phaser.Touch.touchLockCallbacks array and should be removed with Phaser.Touch.removeTouchLockCallback.
  32790. *
  32791. * @method Phaser.Touch#addTouchLockCallback
  32792. * @param {function} callback - The callback that will be called when a touchstart event is received.
  32793. * @param {object} context - The context in which the callback will be called.
  32794. * @param {boolean} [onEnd=false] - Will the callback fire on a touchstart (default) or touchend event?
  32795. */
  32796. addTouchLockCallback: function (callback, context, onEnd) {
  32797. if (onEnd === undefined) { onEnd = false; }
  32798. this.touchLockCallbacks.push({ callback: callback, context: context, onEnd: onEnd });
  32799. },
  32800. /**
  32801. * Removes the callback at the defined index from the Phaser.Touch.touchLockCallbacks array
  32802. *
  32803. * @method Phaser.Touch#removeTouchLockCallback
  32804. * @param {function} callback - The callback to be removed.
  32805. * @param {object} context - The context in which the callback exists.
  32806. * @return {boolean} True if the callback was deleted, otherwise false.
  32807. */
  32808. removeTouchLockCallback: function (callback, context) {
  32809. var i = this.touchLockCallbacks.length;
  32810. while (i--)
  32811. {
  32812. if (this.touchLockCallbacks[i].callback === callback && this.touchLockCallbacks[i].context === context)
  32813. {
  32814. this.touchLockCallbacks.splice(i, 1);
  32815. return true;
  32816. }
  32817. }
  32818. return false;
  32819. },
  32820. /**
  32821. * The internal method that handles the touchstart event from the browser.
  32822. * @method Phaser.Touch#onTouchStart
  32823. * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
  32824. */
  32825. onTouchStart: function (event) {
  32826. var i = this.touchLockCallbacks.length;
  32827. while (i--)
  32828. {
  32829. var cb = this.touchLockCallbacks[i];
  32830. if (!cb.onEnd && cb.callback.call(cb.context, this, event))
  32831. {
  32832. this.touchLockCallbacks.splice(i, 1);
  32833. }
  32834. }
  32835. this.event = event;
  32836. if (!this.game.input.enabled || !this.enabled)
  32837. {
  32838. return;
  32839. }
  32840. if (this.touchStartCallback)
  32841. {
  32842. this.touchStartCallback.call(this.callbackContext, event);
  32843. }
  32844. if (this.preventDefault)
  32845. {
  32846. event.preventDefault();
  32847. }
  32848. // event.targetTouches = list of all touches on the TARGET ELEMENT (i.e. game dom element)
  32849. // event.touches = list of all touches on the ENTIRE DOCUMENT, not just the target element
  32850. // event.changedTouches = the touches that CHANGED in this event, not the total number of them
  32851. for (var i = 0; i < event.changedTouches.length; i++)
  32852. {
  32853. this.game.input.startPointer(event.changedTouches[i]);
  32854. }
  32855. },
  32856. /**
  32857. * Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome).
  32858. * Occurs for example on iOS when you put down 4 fingers and the app selector UI appears.
  32859. * @method Phaser.Touch#onTouchCancel
  32860. * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
  32861. */
  32862. onTouchCancel: function (event) {
  32863. this.event = event;
  32864. if (this.touchCancelCallback)
  32865. {
  32866. this.touchCancelCallback.call(this.callbackContext, event);
  32867. }
  32868. if (!this.game.input.enabled || !this.enabled)
  32869. {
  32870. return;
  32871. }
  32872. if (this.preventDefault)
  32873. {
  32874. event.preventDefault();
  32875. }
  32876. // Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome)
  32877. // http://www.w3.org/TR/touch-events/#dfn-touchcancel
  32878. for (var i = 0; i < event.changedTouches.length; i++)
  32879. {
  32880. this.game.input.stopPointer(event.changedTouches[i]);
  32881. }
  32882. },
  32883. /**
  32884. * For touch enter and leave its a list of the touch points that have entered or left the target.
  32885. * Doesn't appear to be supported by most browsers on a canvas element yet.
  32886. * @method Phaser.Touch#onTouchEnter
  32887. * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
  32888. */
  32889. onTouchEnter: function (event) {
  32890. this.event = event;
  32891. if (this.touchEnterCallback)
  32892. {
  32893. this.touchEnterCallback.call(this.callbackContext, event);
  32894. }
  32895. if (!this.game.input.enabled || !this.enabled)
  32896. {
  32897. return;
  32898. }
  32899. if (this.preventDefault)
  32900. {
  32901. event.preventDefault();
  32902. }
  32903. },
  32904. /**
  32905. * For touch enter and leave its a list of the touch points that have entered or left the target.
  32906. * Doesn't appear to be supported by most browsers on a canvas element yet.
  32907. * @method Phaser.Touch#onTouchLeave
  32908. * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
  32909. */
  32910. onTouchLeave: function (event) {
  32911. this.event = event;
  32912. if (this.touchLeaveCallback)
  32913. {
  32914. this.touchLeaveCallback.call(this.callbackContext, event);
  32915. }
  32916. if (this.preventDefault)
  32917. {
  32918. event.preventDefault();
  32919. }
  32920. },
  32921. /**
  32922. * The handler for the touchmove events.
  32923. * @method Phaser.Touch#onTouchMove
  32924. * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
  32925. */
  32926. onTouchMove: function (event) {
  32927. this.event = event;
  32928. if (this.touchMoveCallback)
  32929. {
  32930. this.touchMoveCallback.call(this.callbackContext, event);
  32931. }
  32932. if (this.preventDefault)
  32933. {
  32934. event.preventDefault();
  32935. }
  32936. for (var i = 0; i < event.changedTouches.length; i++)
  32937. {
  32938. this.game.input.updatePointer(event.changedTouches[i]);
  32939. }
  32940. },
  32941. /**
  32942. * The handler for the touchend events.
  32943. * @method Phaser.Touch#onTouchEnd
  32944. * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
  32945. */
  32946. onTouchEnd: function (event) {
  32947. var i = this.touchLockCallbacks.length;
  32948. while (i--)
  32949. {
  32950. var cb = this.touchLockCallbacks[i];
  32951. if (cb.onEnd && cb.callback.call(cb.context, this, event))
  32952. {
  32953. this.touchLockCallbacks.splice(i, 1);
  32954. }
  32955. }
  32956. this.event = event;
  32957. if (this.touchEndCallback)
  32958. {
  32959. this.touchEndCallback.call(this.callbackContext, event);
  32960. }
  32961. if (this.preventDefault)
  32962. {
  32963. event.preventDefault();
  32964. }
  32965. // For touch end its a list of the touch points that have been removed from the surface
  32966. // https://developer.mozilla.org/en-US/docs/DOM/TouchList
  32967. // event.changedTouches = the touches that CHANGED in this event, not the total number of them
  32968. for (var i = 0; i < event.changedTouches.length; i++)
  32969. {
  32970. this.game.input.stopPointer(event.changedTouches[i]);
  32971. }
  32972. },
  32973. /**
  32974. * Stop the event listeners.
  32975. * @method Phaser.Touch#stop
  32976. */
  32977. stop: function () {
  32978. if (this.game.device.touch)
  32979. {
  32980. this.game.canvas.removeEventListener('touchstart', this._onTouchStart);
  32981. this.game.canvas.removeEventListener('touchmove', this._onTouchMove);
  32982. this.game.canvas.removeEventListener('touchend', this._onTouchEnd);
  32983. this.game.canvas.removeEventListener('touchenter', this._onTouchEnter);
  32984. this.game.canvas.removeEventListener('touchleave', this._onTouchLeave);
  32985. this.game.canvas.removeEventListener('touchcancel', this._onTouchCancel);
  32986. }
  32987. }
  32988. };
  32989. Phaser.Touch.prototype.constructor = Phaser.Touch;
  32990. /**
  32991. * @author Richard Davey <rich@photonstorm.com>
  32992. * @copyright 2016 Photon Storm Ltd.
  32993. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  32994. */
  32995. /**
  32996. * The Input Handler is bound to a specific Sprite and is responsible for managing all Input events on that Sprite.
  32997. *
  32998. * @class Phaser.InputHandler
  32999. * @constructor
  33000. * @param {Phaser.Sprite} sprite - The Sprite object to which this Input Handler belongs.
  33001. */
  33002. Phaser.InputHandler = function (sprite) {
  33003. /**
  33004. * @property {Phaser.Sprite} sprite - The Sprite object to which this Input Handler belongs.
  33005. */
  33006. this.sprite = sprite;
  33007. /**
  33008. * @property {Phaser.Game} game - A reference to the currently running game.
  33009. */
  33010. this.game = sprite.game;
  33011. /**
  33012. * @property {boolean} enabled - If enabled the Input Handler will process input requests and monitor pointer activity.
  33013. * @default
  33014. */
  33015. this.enabled = false;
  33016. /**
  33017. * @property {boolean} checked - A disposable flag used by the Pointer class when performing priority checks.
  33018. * @protected
  33019. */
  33020. this.checked = false;
  33021. /**
  33022. * The priorityID is used to determine which game objects should get priority when input events occur. For example if you have
  33023. * several Sprites that overlap, by default the one at the top of the display list is given priority for input events. You can
  33024. * stop this from happening by controlling the priorityID value. The higher the value, the more important they are considered to the Input events.
  33025. * @property {number} priorityID
  33026. * @default
  33027. */
  33028. this.priorityID = 0;
  33029. /**
  33030. * @property {boolean} useHandCursor - On a desktop browser you can set the 'hand' cursor to appear when moving over the Sprite.
  33031. * @default
  33032. */
  33033. this.useHandCursor = false;
  33034. /**
  33035. * @property {boolean} _setHandCursor - Did this Sprite trigger the hand cursor?
  33036. * @private
  33037. */
  33038. this._setHandCursor = false;
  33039. /**
  33040. * @property {boolean} isDragged - true if the Sprite is being currently dragged.
  33041. * @default
  33042. */
  33043. this.isDragged = false;
  33044. /**
  33045. * @property {boolean} allowHorizontalDrag - Controls if the Sprite is allowed to be dragged horizontally.
  33046. * @default
  33047. */
  33048. this.allowHorizontalDrag = true;
  33049. /**
  33050. * @property {boolean} allowVerticalDrag - Controls if the Sprite is allowed to be dragged vertically.
  33051. * @default
  33052. */
  33053. this.allowVerticalDrag = true;
  33054. /**
  33055. * @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.
  33056. * @default
  33057. */
  33058. this.bringToTop = false;
  33059. /**
  33060. * @property {Phaser.Point} snapOffset - A Point object that contains by how far the Sprite snap is offset.
  33061. * @default
  33062. */
  33063. this.snapOffset = null;
  33064. /**
  33065. * @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.
  33066. * @default
  33067. */
  33068. this.snapOnDrag = false;
  33069. /**
  33070. * @property {boolean} snapOnRelease - When the Sprite is dragged this controls if the Sprite will be snapped on release.
  33071. * @default
  33072. */
  33073. this.snapOnRelease = false;
  33074. /**
  33075. * @property {number} snapX - When a Sprite has snapping enabled this holds the width of the snap grid.
  33076. * @default
  33077. */
  33078. this.snapX = 0;
  33079. /**
  33080. * @property {number} snapY - When a Sprite has snapping enabled this holds the height of the snap grid.
  33081. * @default
  33082. */
  33083. this.snapY = 0;
  33084. /**
  33085. * @property {number} snapOffsetX - This defines the top-left X coordinate of the snap grid.
  33086. * @default
  33087. */
  33088. this.snapOffsetX = 0;
  33089. /**
  33090. * @property {number} snapOffsetY - This defines the top-left Y coordinate of the snap grid..
  33091. * @default
  33092. */
  33093. this.snapOffsetY = 0;
  33094. /**
  33095. * Set to true to use pixel perfect hit detection when checking if the pointer is over this Sprite.
  33096. * The x/y coordinates of the pointer are tested against the image in combination with the InputHandler.pixelPerfectAlpha value.
  33097. * This feature only works for display objects with image based textures such as Sprites. It won't work on BitmapText or Rope.
  33098. * Warning: This is expensive, especially on mobile (where it's not even needed!) so only enable if required. Also see the less-expensive InputHandler.pixelPerfectClick.
  33099. * @property {boolean} pixelPerfectOver - Use a pixel perfect check when testing for pointer over.
  33100. * @default
  33101. */
  33102. this.pixelPerfectOver = false;
  33103. /**
  33104. * Set to true to use pixel perfect hit detection when checking if the pointer is over this Sprite when it's clicked or touched.
  33105. * The x/y coordinates of the pointer are tested against the image in combination with the InputHandler.pixelPerfectAlpha value.
  33106. * This feature only works for display objects with image based textures such as Sprites. It won't work on BitmapText or Rope.
  33107. * Warning: This is expensive so only enable if you really need it.
  33108. * @property {boolean} pixelPerfectClick - Use a pixel perfect check when testing for clicks or touches on the Sprite.
  33109. * @default
  33110. */
  33111. this.pixelPerfectClick = false;
  33112. /**
  33113. * @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.
  33114. * @default
  33115. */
  33116. this.pixelPerfectAlpha = 255;
  33117. /**
  33118. * @property {boolean} draggable - Is this sprite allowed to be dragged by the mouse? true = yes, false = no
  33119. * @default
  33120. */
  33121. this.draggable = false;
  33122. /**
  33123. * @property {Phaser.Rectangle} boundsRect - A region of the game world within which the sprite is restricted during drag.
  33124. * @default
  33125. */
  33126. this.boundsRect = null;
  33127. /**
  33128. * @property {Phaser.Sprite} boundsSprite - A Sprite the bounds of which this sprite is restricted during drag.
  33129. * @default
  33130. */
  33131. this.boundsSprite = null;
  33132. /**
  33133. * @property {boolean} scaleLayer - EXPERIMENTAL: Please do not use this property unless you know what it does. Likely to change in the future.
  33134. */
  33135. this.scaleLayer = false;
  33136. /**
  33137. * @property {Phaser.Point} dragOffset - The offset from the Sprites position that dragging takes place from.
  33138. */
  33139. this.dragOffset = new Phaser.Point();
  33140. /**
  33141. * @property {boolean} dragFromCenter - Is the Sprite dragged from its center, or the point at which the Pointer was pressed down upon it?
  33142. */
  33143. this.dragFromCenter = false;
  33144. /**
  33145. * @property {Phaser.Point} dragStartPoint - The Point from which the most recent drag started from. Useful if you need to return an object to its starting position.
  33146. */
  33147. this.dragStartPoint = new Phaser.Point();
  33148. /**
  33149. * @property {Phaser.Point} snapPoint - If the sprite is set to snap while dragging this holds the point of the most recent 'snap' event.
  33150. */
  33151. this.snapPoint = new Phaser.Point();
  33152. /**
  33153. * @property {Phaser.Point} _dragPoint - Internal cache var.
  33154. * @private
  33155. */
  33156. this._dragPoint = new Phaser.Point();
  33157. /**
  33158. * @property {boolean} _dragPhase - Internal cache var.
  33159. * @private
  33160. */
  33161. this._dragPhase = false;
  33162. /**
  33163. * @property {boolean} _wasEnabled - Internal cache var.
  33164. * @private
  33165. */
  33166. this._wasEnabled = false;
  33167. /**
  33168. * @property {Phaser.Point} _tempPoint - Internal cache var.
  33169. * @private
  33170. */
  33171. this._tempPoint = new Phaser.Point();
  33172. /**
  33173. * @property {array} _pointerData - Internal cache var.
  33174. * @private
  33175. */
  33176. this._pointerData = [];
  33177. this._pointerData.push({
  33178. id: 0,
  33179. x: 0,
  33180. y: 0,
  33181. camX: 0,
  33182. camY: 0,
  33183. isDown: false,
  33184. isUp: false,
  33185. isOver: false,
  33186. isOut: false,
  33187. timeOver: 0,
  33188. timeOut: 0,
  33189. timeDown: 0,
  33190. timeUp: 0,
  33191. downDuration: 0,
  33192. isDragged: false
  33193. });
  33194. };
  33195. Phaser.InputHandler.prototype = {
  33196. /**
  33197. * 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.
  33198. * @method Phaser.InputHandler#start
  33199. * @param {number} priority - Higher priority sprites take click priority over low-priority sprites when they are stacked on-top of each other.
  33200. * @param {boolean} useHandCursor - If true the Sprite will show the hand cursor on mouse-over (doesn't apply to mobile browsers)
  33201. * @return {Phaser.Sprite} The Sprite object to which the Input Handler is bound.
  33202. */
  33203. start: function (priority, useHandCursor) {
  33204. priority = priority || 0;
  33205. if (useHandCursor === undefined) { useHandCursor = false; }
  33206. // Turning on
  33207. if (this.enabled === false)
  33208. {
  33209. // Register, etc
  33210. this.game.input.interactiveItems.add(this);
  33211. this.useHandCursor = useHandCursor;
  33212. this.priorityID = priority;
  33213. for (var i = 0; i < 10; i++)
  33214. {
  33215. this._pointerData[i] = {
  33216. id: i,
  33217. x: 0,
  33218. y: 0,
  33219. isDown: false,
  33220. isUp: false,
  33221. isOver: false,
  33222. isOut: false,
  33223. timeOver: 0,
  33224. timeOut: 0,
  33225. timeDown: 0,
  33226. timeUp: 0,
  33227. downDuration: 0,
  33228. isDragged: false
  33229. };
  33230. }
  33231. this.snapOffset = new Phaser.Point();
  33232. this.enabled = true;
  33233. this._wasEnabled = true;
  33234. }
  33235. this.sprite.events.onAddedToGroup.add(this.addedToGroup, this);
  33236. this.sprite.events.onRemovedFromGroup.add(this.removedFromGroup, this);
  33237. this.flagged = false;
  33238. return this.sprite;
  33239. },
  33240. /**
  33241. * Handles when the parent Sprite is added to a new Group.
  33242. *
  33243. * @method Phaser.InputHandler#addedToGroup
  33244. * @private
  33245. */
  33246. addedToGroup: function () {
  33247. if (this._dragPhase)
  33248. {
  33249. return;
  33250. }
  33251. if (this._wasEnabled && !this.enabled)
  33252. {
  33253. this.start();
  33254. }
  33255. },
  33256. /**
  33257. * Handles when the parent Sprite is removed from a Group.
  33258. *
  33259. * @method Phaser.InputHandler#removedFromGroup
  33260. * @private
  33261. */
  33262. removedFromGroup: function () {
  33263. if (this._dragPhase)
  33264. {
  33265. return;
  33266. }
  33267. if (this.enabled)
  33268. {
  33269. this._wasEnabled = true;
  33270. this.stop();
  33271. }
  33272. else
  33273. {
  33274. this._wasEnabled = false;
  33275. }
  33276. },
  33277. /**
  33278. * Resets the Input Handler and disables it.
  33279. * @method Phaser.InputHandler#reset
  33280. */
  33281. reset: function () {
  33282. this.enabled = false;
  33283. this.flagged = false;
  33284. for (var i = 0; i < 10; i++)
  33285. {
  33286. this._pointerData[i] = {
  33287. id: i,
  33288. x: 0,
  33289. y: 0,
  33290. isDown: false,
  33291. isUp: false,
  33292. isOver: false,
  33293. isOut: false,
  33294. timeOver: 0,
  33295. timeOut: 0,
  33296. timeDown: 0,
  33297. timeUp: 0,
  33298. downDuration: 0,
  33299. isDragged: false
  33300. };
  33301. }
  33302. },
  33303. /**
  33304. * Stops the Input Handler from running.
  33305. * @method Phaser.InputHandler#stop
  33306. */
  33307. stop: function () {
  33308. // Turning off
  33309. if (this.enabled === false)
  33310. {
  33311. return;
  33312. }
  33313. else
  33314. {
  33315. // De-register, etc
  33316. this.enabled = false;
  33317. this.game.input.interactiveItems.remove(this);
  33318. }
  33319. },
  33320. /**
  33321. * Clean up memory.
  33322. * @method Phaser.InputHandler#destroy
  33323. */
  33324. destroy: function () {
  33325. if (this.sprite)
  33326. {
  33327. if (this._setHandCursor)
  33328. {
  33329. this.game.canvas.style.cursor = "default";
  33330. this._setHandCursor = false;
  33331. }
  33332. this.enabled = false;
  33333. this.game.input.interactiveItems.remove(this);
  33334. this._pointerData.length = 0;
  33335. this.boundsRect = null;
  33336. this.boundsSprite = null;
  33337. this.sprite = null;
  33338. }
  33339. },
  33340. /**
  33341. * Checks if the object this InputHandler is bound to is valid for consideration in the Pointer move event.
  33342. * This is called by Phaser.Pointer and shouldn't typically be called directly.
  33343. *
  33344. * @method Phaser.InputHandler#validForInput
  33345. * @protected
  33346. * @param {number} highestID - The highest ID currently processed by the Pointer.
  33347. * @param {number} highestRenderID - The highest Render Order ID currently processed by the Pointer.
  33348. * @param {boolean} [includePixelPerfect=true] - If this object has `pixelPerfectClick` or `pixelPerfectOver` set should it be considered as valid?
  33349. * @return {boolean} True if the object this InputHandler is bound to should be considered as valid for input detection.
  33350. */
  33351. validForInput: function (highestID, highestRenderID, includePixelPerfect) {
  33352. if (includePixelPerfect === undefined) { includePixelPerfect = true; }
  33353. if (!this.enabled || this.sprite.scale.x === 0 || this.sprite.scale.y === 0 || this.priorityID < this.game.input.minPriorityID)
  33354. {
  33355. return false;
  33356. }
  33357. // If we're trying to specifically IGNORE pixel perfect objects, then set includePixelPerfect to false and skip it
  33358. if (!includePixelPerfect && (this.pixelPerfectClick || this.pixelPerfectOver))
  33359. {
  33360. return false;
  33361. }
  33362. if (this.priorityID > highestID || (this.priorityID === highestID && this.sprite.renderOrderID < highestRenderID))
  33363. {
  33364. return true;
  33365. }
  33366. return false;
  33367. },
  33368. /**
  33369. * Is this object using pixel perfect checking?
  33370. *
  33371. * @method Phaser.InputHandler#isPixelPerfect
  33372. * @return {boolean} True if the this InputHandler has either `pixelPerfectClick` or `pixelPerfectOver` set to `true`.
  33373. */
  33374. isPixelPerfect: function () {
  33375. return (this.pixelPerfectClick || this.pixelPerfectOver);
  33376. },
  33377. /**
  33378. * The x coordinate of the Input pointer, relative to the top-left of the parent Sprite.
  33379. * This value is only set when the pointer is over this Sprite.
  33380. *
  33381. * @method Phaser.InputHandler#pointerX
  33382. * @param {integer} [pointerId=0]
  33383. * @return {number} The x coordinate of the Input pointer.
  33384. */
  33385. pointerX: function (pointerId) {
  33386. pointerId = pointerId || 0;
  33387. return this._pointerData[pointerId].x;
  33388. },
  33389. /**
  33390. * The y coordinate of the Input pointer, relative to the top-left of the parent Sprite
  33391. * This value is only set when the pointer is over this Sprite.
  33392. *
  33393. * @method Phaser.InputHandler#pointerY
  33394. * @param {integer} [pointerId=0]
  33395. * @return {number} The y coordinate of the Input pointer.
  33396. */
  33397. pointerY: function (pointerId) {
  33398. pointerId = pointerId || 0;
  33399. return this._pointerData[pointerId].y;
  33400. },
  33401. /**
  33402. * If the Pointer is down this returns true.
  33403. * This *only* checks if the Pointer is down, not if it's down over any specific Sprite.
  33404. *
  33405. * @method Phaser.InputHandler#pointerDown
  33406. * @param {integer} [pointerId=0]
  33407. * @return {boolean} - True if the given pointer is down, otherwise false.
  33408. */
  33409. pointerDown: function (pointerId) {
  33410. pointerId = pointerId || 0;
  33411. return this._pointerData[pointerId].isDown;
  33412. },
  33413. /**
  33414. * If the Pointer is up this returns true.
  33415. * This *only* checks if the Pointer is up, not if it's up over any specific Sprite.
  33416. *
  33417. * @method Phaser.InputHandler#pointerUp
  33418. * @param {integer} [pointerId=0]
  33419. * @return {boolean} - True if the given pointer is up, otherwise false.
  33420. */
  33421. pointerUp: function (pointerId) {
  33422. pointerId = pointerId || 0;
  33423. return this._pointerData[pointerId].isUp;
  33424. },
  33425. /**
  33426. * A timestamp representing when the Pointer first touched the touchscreen.
  33427. *
  33428. * @method Phaser.InputHandler#pointerTimeDown
  33429. * @param {integer} [pointerId=(check all)]
  33430. * @return {number}
  33431. */
  33432. pointerTimeDown: function (pointerId) {
  33433. pointerId = pointerId || 0;
  33434. return this._pointerData[pointerId].timeDown;
  33435. },
  33436. /**
  33437. * A timestamp representing when the Pointer left the touchscreen.
  33438. *
  33439. * @method Phaser.InputHandler#pointerTimeUp
  33440. * @param {integer} [pointerId=0]
  33441. * @return {number}
  33442. */
  33443. pointerTimeUp: function (pointerId) {
  33444. pointerId = pointerId || 0;
  33445. return this._pointerData[pointerId].timeUp;
  33446. },
  33447. /**
  33448. * Is the Pointer over this Sprite?
  33449. *
  33450. * @method Phaser.InputHandler#pointerOver
  33451. * @param {integer} [pointerId=(check all)] The ID number of a Pointer to check. If you don't provide a number it will check all Pointers.
  33452. * @return {boolean} - True if the given pointer (if a index was given, or any pointer if not) is over this object.
  33453. */
  33454. pointerOver: function (pointerId) {
  33455. if (!this.enabled)
  33456. {
  33457. return false;
  33458. }
  33459. if (pointerId === undefined)
  33460. {
  33461. for (var i = 0; i < 10; i++)
  33462. {
  33463. if (this._pointerData[i].isOver)
  33464. {
  33465. return true;
  33466. }
  33467. }
  33468. return false;
  33469. }
  33470. else
  33471. {
  33472. return this._pointerData[pointerId].isOver;
  33473. }
  33474. },
  33475. /**
  33476. * Is the Pointer outside of this Sprite?
  33477. *
  33478. * @method Phaser.InputHandler#pointerOut
  33479. * @param {integer} [pointerId=(check all)] The ID number of a Pointer to check. If you don't provide a number it will check all Pointers.
  33480. * @return {boolean} True if the given pointer (if a index was given, or any pointer if not) is out of this object.
  33481. */
  33482. pointerOut: function (pointerId) {
  33483. if (!this.enabled)
  33484. {
  33485. return false;
  33486. }
  33487. if (pointerId === undefined)
  33488. {
  33489. for (var i = 0; i < 10; i++)
  33490. {
  33491. if (this._pointerData[i].isOut)
  33492. {
  33493. return true;
  33494. }
  33495. }
  33496. }
  33497. else
  33498. {
  33499. return this._pointerData[pointerId].isOut;
  33500. }
  33501. },
  33502. /**
  33503. * A timestamp representing when the Pointer first touched the touchscreen.
  33504. *
  33505. * @method Phaser.InputHandler#pointerTimeOver
  33506. * @param {integer} [pointerId=0]
  33507. * @return {number}
  33508. */
  33509. pointerTimeOver: function (pointerId) {
  33510. pointerId = pointerId || 0;
  33511. return this._pointerData[pointerId].timeOver;
  33512. },
  33513. /**
  33514. * A timestamp representing when the Pointer left the touchscreen.
  33515. *
  33516. * @method Phaser.InputHandler#pointerTimeOut
  33517. * @param {integer} [pointerId=0]
  33518. * @return {number}
  33519. */
  33520. pointerTimeOut: function (pointerId) {
  33521. pointerId = pointerId || 0;
  33522. return this._pointerData[pointerId].timeOut;
  33523. },
  33524. /**
  33525. * Is this sprite being dragged by the mouse or not?
  33526. *
  33527. * @method Phaser.InputHandler#pointerDragged
  33528. * @param {integer} [pointerId=0]
  33529. * @return {boolean} True if the pointer is dragging an object, otherwise false.
  33530. */
  33531. pointerDragged: function (pointerId) {
  33532. pointerId = pointerId || 0;
  33533. return this._pointerData[pointerId].isDragged;
  33534. },
  33535. /**
  33536. * Checks if the given pointer is both down and over the Sprite this InputHandler belongs to.
  33537. * Use the `fastTest` flag is to quickly check just the bounding hit area even if `InputHandler.pixelPerfectOver` is `true`.
  33538. *
  33539. * @method Phaser.InputHandler#checkPointerDown
  33540. * @param {Phaser.Pointer} pointer
  33541. * @param {boolean} [fastTest=false] - Force a simple hit area check even if `pixelPerfectOver` is true for this object?
  33542. * @return {boolean} True if the pointer is down, otherwise false.
  33543. */
  33544. checkPointerDown: function (pointer, fastTest) {
  33545. if (!pointer.isDown || !this.enabled || !this.sprite || !this.sprite.parent || !this.sprite.visible || !this.sprite.parent.visible)
  33546. {
  33547. return false;
  33548. }
  33549. // Need to pass it a temp point, in case we need it again for the pixel check
  33550. if (this.game.input.hitTest(this.sprite, pointer, this._tempPoint))
  33551. {
  33552. if (fastTest === undefined)
  33553. {
  33554. fastTest = false;
  33555. }
  33556. if (!fastTest && this.pixelPerfectClick)
  33557. {
  33558. return this.checkPixel(this._tempPoint.x, this._tempPoint.y);
  33559. }
  33560. else
  33561. {
  33562. return true;
  33563. }
  33564. }
  33565. return false;
  33566. },
  33567. /**
  33568. * Checks if the given pointer is over the Sprite this InputHandler belongs to.
  33569. * Use the `fastTest` flag is to quickly check just the bounding hit area even if `InputHandler.pixelPerfectOver` is `true`.
  33570. *
  33571. * @method Phaser.InputHandler#checkPointerOver
  33572. * @param {Phaser.Pointer} pointer
  33573. * @param {boolean} [fastTest=false] - Force a simple hit area check even if `pixelPerfectOver` is true for this object?
  33574. * @return {boolean}
  33575. */
  33576. checkPointerOver: function (pointer, fastTest) {
  33577. if (!this.enabled || !this.sprite || !this.sprite.parent || !this.sprite.visible || !this.sprite.parent.visible)
  33578. {
  33579. return false;
  33580. }
  33581. // Need to pass it a temp point, in case we need it again for the pixel check
  33582. if (this.game.input.hitTest(this.sprite, pointer, this._tempPoint))
  33583. {
  33584. if (fastTest === undefined)
  33585. {
  33586. fastTest = false;
  33587. }
  33588. if (!fastTest && this.pixelPerfectOver)
  33589. {
  33590. return this.checkPixel(this._tempPoint.x, this._tempPoint.y);
  33591. }
  33592. else
  33593. {
  33594. return true;
  33595. }
  33596. }
  33597. return false;
  33598. },
  33599. /**
  33600. * Runs a pixel perfect check against the given x/y coordinates of the Sprite this InputHandler is bound to.
  33601. * It compares the alpha value of the pixel and if >= InputHandler.pixelPerfectAlpha it returns true.
  33602. *
  33603. * @method Phaser.InputHandler#checkPixel
  33604. * @param {number} x - The x coordinate to check.
  33605. * @param {number} y - The y coordinate to check.
  33606. * @param {Phaser.Pointer} [pointer] - The pointer to get the x/y coordinate from if not passed as the first two parameters.
  33607. * @return {boolean} true if there is the alpha of the pixel is >= InputHandler.pixelPerfectAlpha
  33608. */
  33609. checkPixel: function (x, y, pointer) {
  33610. // Grab a pixel from our image into the hitCanvas and then test it
  33611. if (this.sprite.texture.baseTexture.source)
  33612. {
  33613. if (x === null && y === null)
  33614. {
  33615. // Use the pointer parameter
  33616. this.game.input.getLocalPosition(this.sprite, pointer, this._tempPoint);
  33617. var x = this._tempPoint.x;
  33618. var y = this._tempPoint.y;
  33619. }
  33620. if (this.sprite.anchor.x !== 0)
  33621. {
  33622. x -= -this.sprite.texture.frame.width * this.sprite.anchor.x;
  33623. }
  33624. if (this.sprite.anchor.y !== 0)
  33625. {
  33626. y -= -this.sprite.texture.frame.height * this.sprite.anchor.y;
  33627. }
  33628. x += this.sprite.texture.frame.x;
  33629. y += this.sprite.texture.frame.y;
  33630. if (this.sprite.texture.trim)
  33631. {
  33632. x -= this.sprite.texture.trim.x;
  33633. y -= this.sprite.texture.trim.y;
  33634. // If the coordinates are outside the trim area we return false immediately, to save doing a draw call
  33635. if (x < this.sprite.texture.crop.x || x > this.sprite.texture.crop.right || y < this.sprite.texture.crop.y || y > this.sprite.texture.crop.bottom)
  33636. {
  33637. this._dx = x;
  33638. this._dy = y;
  33639. return false;
  33640. }
  33641. }
  33642. this._dx = x;
  33643. this._dy = y;
  33644. this.game.input.hitContext.clearRect(0, 0, 1, 1);
  33645. this.game.input.hitContext.drawImage(this.sprite.texture.baseTexture.source, x, y, 1, 1, 0, 0, 1, 1);
  33646. var rgb = this.game.input.hitContext.getImageData(0, 0, 1, 1);
  33647. if (rgb.data[3] >= this.pixelPerfectAlpha)
  33648. {
  33649. return true;
  33650. }
  33651. }
  33652. return false;
  33653. },
  33654. /**
  33655. * Update.
  33656. *
  33657. * @method Phaser.InputHandler#update
  33658. * @protected
  33659. * @param {Phaser.Pointer} pointer
  33660. */
  33661. update: function (pointer) {
  33662. if (this.sprite === null || this.sprite.parent === undefined)
  33663. {
  33664. // Abort. We've been destroyed.
  33665. return;
  33666. }
  33667. if (!this.enabled || !this.sprite.visible || !this.sprite.parent.visible)
  33668. {
  33669. this._pointerOutHandler(pointer);
  33670. return false;
  33671. }
  33672. if (this.draggable && this._draggedPointerID === pointer.id)
  33673. {
  33674. return this.updateDrag(pointer);
  33675. }
  33676. else if (this._pointerData[pointer.id].isOver)
  33677. {
  33678. if (this.checkPointerOver(pointer))
  33679. {
  33680. this._pointerData[pointer.id].x = pointer.x - this.sprite.x;
  33681. this._pointerData[pointer.id].y = pointer.y - this.sprite.y;
  33682. return true;
  33683. }
  33684. else
  33685. {
  33686. this._pointerOutHandler(pointer);
  33687. return false;
  33688. }
  33689. }
  33690. },
  33691. /**
  33692. * Internal method handling the pointer over event.
  33693. *
  33694. * @method Phaser.InputHandler#_pointerOverHandler
  33695. * @private
  33696. * @param {Phaser.Pointer} pointer - The pointer that triggered the event
  33697. */
  33698. _pointerOverHandler: function (pointer) {
  33699. if (this.sprite === null)
  33700. {
  33701. // Abort. We've been destroyed.
  33702. return;
  33703. }
  33704. var data = this._pointerData[pointer.id];
  33705. if (data.isOver === false || pointer.dirty)
  33706. {
  33707. var sendEvent = (data.isOver === false);
  33708. data.isOver = true;
  33709. data.isOut = false;
  33710. data.timeOver = this.game.time.time;
  33711. data.x = pointer.x - this.sprite.x;
  33712. data.y = pointer.y - this.sprite.y;
  33713. if (this.useHandCursor && data.isDragged === false)
  33714. {
  33715. this.game.canvas.style.cursor = "pointer";
  33716. this._setHandCursor = true;
  33717. }
  33718. if (sendEvent && this.sprite && this.sprite.events)
  33719. {
  33720. this.sprite.events.onInputOver$dispatch(this.sprite, pointer);
  33721. }
  33722. }
  33723. },
  33724. /**
  33725. * Internal method handling the pointer out event.
  33726. *
  33727. * @method Phaser.InputHandler#_pointerOutHandler
  33728. * @private
  33729. * @param {Phaser.Pointer} pointer - The pointer that triggered the event.
  33730. */
  33731. _pointerOutHandler: function (pointer) {
  33732. if (this.sprite === null)
  33733. {
  33734. // Abort. We've been destroyed.
  33735. return;
  33736. }
  33737. var data = this._pointerData[pointer.id];
  33738. data.isOver = false;
  33739. data.isOut = true;
  33740. data.timeOut = this.game.time.time;
  33741. if (this.useHandCursor && data.isDragged === false)
  33742. {
  33743. this.game.canvas.style.cursor = "default";
  33744. this._setHandCursor = false;
  33745. }
  33746. if (this.sprite && this.sprite.events)
  33747. {
  33748. this.sprite.events.onInputOut$dispatch(this.sprite, pointer);
  33749. }
  33750. },
  33751. /**
  33752. * Internal method handling the touched / clicked event.
  33753. *
  33754. * @method Phaser.InputHandler#_touchedHandler
  33755. * @private
  33756. * @param {Phaser.Pointer} pointer - The pointer that triggered the event.
  33757. */
  33758. _touchedHandler: function (pointer) {
  33759. if (this.sprite === null)
  33760. {
  33761. // Abort. We've been destroyed.
  33762. return;
  33763. }
  33764. var data = this._pointerData[pointer.id];
  33765. if (!data.isDown && data.isOver)
  33766. {
  33767. if (this.pixelPerfectClick && !this.checkPixel(null, null, pointer))
  33768. {
  33769. return;
  33770. }
  33771. data.isDown = true;
  33772. data.isUp = false;
  33773. data.timeDown = this.game.time.time;
  33774. // It's possible the onInputDown event creates a new Sprite that is on-top of this one, so we ought to force a Pointer update
  33775. pointer.dirty = true;
  33776. if (this.sprite && this.sprite.events)
  33777. {
  33778. this.sprite.events.onInputDown$dispatch(this.sprite, pointer);
  33779. // The onInputDown event might have destroyed this sprite.
  33780. if (this.sprite === null)
  33781. {
  33782. return;
  33783. }
  33784. }
  33785. // Start drag
  33786. if (this.draggable && this.isDragged === false)
  33787. {
  33788. this.startDrag(pointer);
  33789. }
  33790. if (this.bringToTop)
  33791. {
  33792. this.sprite.bringToTop();
  33793. }
  33794. }
  33795. },
  33796. /**
  33797. * Internal method handling the pointer released event.
  33798. * @method Phaser.InputHandler#_releasedHandler
  33799. * @private
  33800. * @param {Phaser.Pointer} pointer
  33801. */
  33802. _releasedHandler: function (pointer) {
  33803. if (this.sprite === null)
  33804. {
  33805. // Abort. We've been destroyed.
  33806. return;
  33807. }
  33808. var data = this._pointerData[pointer.id];
  33809. // If was previously touched by this Pointer, check if still is AND still over this item
  33810. if (data.isDown && pointer.isUp)
  33811. {
  33812. data.isDown = false;
  33813. data.isUp = true;
  33814. data.timeUp = this.game.time.time;
  33815. data.downDuration = data.timeUp - data.timeDown;
  33816. // Only release the InputUp signal if the pointer is still over this sprite
  33817. var isOver = this.checkPointerOver(pointer);
  33818. if (this.sprite && this.sprite.events)
  33819. {
  33820. this.sprite.events.onInputUp$dispatch(this.sprite, pointer, isOver);
  33821. // The onInputUp event may have changed the sprite so that checkPointerOver is no longer true, so update it.
  33822. if (isOver)
  33823. {
  33824. isOver = this.checkPointerOver(pointer);
  33825. }
  33826. }
  33827. data.isOver = isOver;
  33828. if (!isOver && this.useHandCursor)
  33829. {
  33830. this.game.canvas.style.cursor = "default";
  33831. this._setHandCursor = false;
  33832. }
  33833. // It's possible the onInputUp event created a new Sprite that is on-top of this one, so force a Pointer update
  33834. pointer.dirty = true;
  33835. // Stop drag
  33836. if (this.draggable && this.isDragged && this._draggedPointerID === pointer.id)
  33837. {
  33838. this.stopDrag(pointer);
  33839. }
  33840. }
  33841. },
  33842. /**
  33843. * Updates the Pointer drag on this Sprite.
  33844. * @method Phaser.InputHandler#updateDrag
  33845. * @param {Phaser.Pointer} pointer
  33846. * @return {boolean}
  33847. */
  33848. updateDrag: function (pointer, fromStart) {
  33849. if (pointer.isUp)
  33850. {
  33851. this.stopDrag(pointer);
  33852. return false;
  33853. }
  33854. if (fromStart === undefined)
  33855. {
  33856. fromStart = false;
  33857. }
  33858. var px = this.globalToLocalX(pointer.x) + this._dragPoint.x + this.dragOffset.x;
  33859. var py = this.globalToLocalY(pointer.y) + this._dragPoint.y + this.dragOffset.y;
  33860. if (this.sprite.fixedToCamera)
  33861. {
  33862. if (this.allowHorizontalDrag)
  33863. {
  33864. this.sprite.cameraOffset.x = px;
  33865. }
  33866. if (this.allowVerticalDrag)
  33867. {
  33868. this.sprite.cameraOffset.y = py;
  33869. }
  33870. if (this.boundsRect)
  33871. {
  33872. this.checkBoundsRect();
  33873. }
  33874. if (this.boundsSprite)
  33875. {
  33876. this.checkBoundsSprite();
  33877. }
  33878. if (this.snapOnDrag)
  33879. {
  33880. this.sprite.cameraOffset.x = Math.round((this.sprite.cameraOffset.x - (this.snapOffsetX % this.snapX)) / this.snapX) * this.snapX + (this.snapOffsetX % this.snapX);
  33881. this.sprite.cameraOffset.y = Math.round((this.sprite.cameraOffset.y - (this.snapOffsetY % this.snapY)) / this.snapY) * this.snapY + (this.snapOffsetY % this.snapY);
  33882. this.snapPoint.set(this.sprite.cameraOffset.x, this.sprite.cameraOffset.y);
  33883. }
  33884. }
  33885. else
  33886. {
  33887. var cx = this.game.camera.x - this._pointerData[pointer.id].camX;
  33888. var cy = this.game.camera.y - this._pointerData[pointer.id].camY;
  33889. if (this.allowHorizontalDrag)
  33890. {
  33891. this.sprite.x = px + cx;
  33892. }
  33893. if (this.allowVerticalDrag)
  33894. {
  33895. this.sprite.y = py + cy;
  33896. }
  33897. if (this.boundsRect)
  33898. {
  33899. this.checkBoundsRect();
  33900. }
  33901. if (this.boundsSprite)
  33902. {
  33903. this.checkBoundsSprite();
  33904. }
  33905. if (this.snapOnDrag)
  33906. {
  33907. this.sprite.x = Math.round((this.sprite.x - (this.snapOffsetX % this.snapX)) / this.snapX) * this.snapX + (this.snapOffsetX % this.snapX);
  33908. this.sprite.y = Math.round((this.sprite.y - (this.snapOffsetY % this.snapY)) / this.snapY) * this.snapY + (this.snapOffsetY % this.snapY);
  33909. this.snapPoint.set(this.sprite.x, this.sprite.y);
  33910. }
  33911. }
  33912. this.sprite.events.onDragUpdate.dispatch(this.sprite, pointer, px, py, this.snapPoint, fromStart);
  33913. return true;
  33914. },
  33915. /**
  33916. * Returns true if the pointer has entered the Sprite within the specified delay time (defaults to 500ms, half a second)
  33917. *
  33918. * @method Phaser.InputHandler#justOver
  33919. * @param {integer} [pointerId=0]
  33920. * @param {number} delay - The time below which the pointer is considered as just over.
  33921. * @return {boolean}
  33922. */
  33923. justOver: function (pointerId, delay) {
  33924. pointerId = pointerId || 0;
  33925. delay = delay || 500;
  33926. return (this._pointerData[pointerId].isOver && this.overDuration(pointerId) < delay);
  33927. },
  33928. /**
  33929. * Returns true if the pointer has left the Sprite within the specified delay time (defaults to 500ms, half a second)
  33930. *
  33931. * @method Phaser.InputHandler#justOut
  33932. * @param {integer} [pointerId=0]
  33933. * @param {number} delay - The time below which the pointer is considered as just out.
  33934. * @return {boolean}
  33935. */
  33936. justOut: function (pointerId, delay) {
  33937. pointerId = pointerId || 0;
  33938. delay = delay || 500;
  33939. return (this._pointerData[pointerId].isOut && (this.game.time.time - this._pointerData[pointerId].timeOut < delay));
  33940. },
  33941. /**
  33942. * Returns true if the pointer has touched or clicked on the Sprite within the specified delay time (defaults to 500ms, half a second)
  33943. *
  33944. * @method Phaser.InputHandler#justPressed
  33945. * @param {integer} [pointerId=0]
  33946. * @param {number} delay - The time below which the pointer is considered as just over.
  33947. * @return {boolean}
  33948. */
  33949. justPressed: function (pointerId, delay) {
  33950. pointerId = pointerId || 0;
  33951. delay = delay || 500;
  33952. return (this._pointerData[pointerId].isDown && this.downDuration(pointerId) < delay);
  33953. },
  33954. /**
  33955. * Returns true if the pointer was touching this Sprite, but has been released within the specified delay time (defaults to 500ms, half a second)
  33956. *
  33957. * @method Phaser.InputHandler#justReleased
  33958. * @param {integer} [pointerId=0]
  33959. * @param {number} delay - The time below which the pointer is considered as just out.
  33960. * @return {boolean}
  33961. */
  33962. justReleased: function (pointerId, delay) {
  33963. pointerId = pointerId || 0;
  33964. delay = delay || 500;
  33965. return (this._pointerData[pointerId].isUp && (this.game.time.time - this._pointerData[pointerId].timeUp < delay));
  33966. },
  33967. /**
  33968. * If the pointer is currently over this Sprite this returns how long it has been there for in milliseconds.
  33969. *
  33970. * @method Phaser.InputHandler#overDuration
  33971. * @param {integer} [pointerId=0]
  33972. * @return {number} The number of milliseconds the pointer has been over the Sprite, or -1 if not over.
  33973. */
  33974. overDuration: function (pointerId) {
  33975. pointerId = pointerId || 0;
  33976. if (this._pointerData[pointerId].isOver)
  33977. {
  33978. return this.game.time.time - this._pointerData[pointerId].timeOver;
  33979. }
  33980. return -1;
  33981. },
  33982. /**
  33983. * If the pointer is currently over this Sprite this returns how long it has been there for in milliseconds.
  33984. *
  33985. * @method Phaser.InputHandler#downDuration
  33986. * @param {integer} [pointerId=0]
  33987. * @return {number} The number of milliseconds the pointer has been pressed down on the Sprite, or -1 if not over.
  33988. */
  33989. downDuration: function (pointerId) {
  33990. pointerId = pointerId || 0;
  33991. if (this._pointerData[pointerId].isDown)
  33992. {
  33993. return this.game.time.time - this._pointerData[pointerId].timeDown;
  33994. }
  33995. return -1;
  33996. },
  33997. /**
  33998. * Allow this Sprite to be dragged by any valid pointer.
  33999. *
  34000. * When the drag begins the Sprite.events.onDragStart event will be dispatched.
  34001. *
  34002. * When the drag completes by way of the user letting go of the pointer that was dragging the sprite, the Sprite.events.onDragStop event is dispatched.
  34003. *
  34004. * For the duration of the drag the Sprite.events.onDragUpdate event is dispatched. This event is only dispatched when the pointer actually
  34005. * changes position and moves. The event sends 5 parameters: `sprite`, `pointer`, `dragX`, `dragY` and `snapPoint`.
  34006. *
  34007. * @method Phaser.InputHandler#enableDrag
  34008. * @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.
  34009. * @param {boolean} [bringToTop=false] - If true the Sprite will be bought to the top of the rendering list in its current Group.
  34010. * @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.
  34011. * @param {boolean} [alphaThreshold=255] - If using pixel perfect collision this specifies the alpha level from 0 to 255 above which a collision is processed.
  34012. * @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.
  34013. * @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.
  34014. */
  34015. enableDrag: function (lockCenter, bringToTop, pixelPerfect, alphaThreshold, boundsRect, boundsSprite) {
  34016. if (lockCenter === undefined) { lockCenter = false; }
  34017. if (bringToTop === undefined) { bringToTop = false; }
  34018. if (pixelPerfect === undefined) { pixelPerfect = false; }
  34019. if (alphaThreshold === undefined) { alphaThreshold = 255; }
  34020. if (boundsRect === undefined) { boundsRect = null; }
  34021. if (boundsSprite === undefined) { boundsSprite = null; }
  34022. this._dragPoint = new Phaser.Point();
  34023. this.draggable = true;
  34024. this.bringToTop = bringToTop;
  34025. this.dragOffset = new Phaser.Point();
  34026. this.dragFromCenter = lockCenter;
  34027. this.pixelPerfectClick = pixelPerfect;
  34028. this.pixelPerfectAlpha = alphaThreshold;
  34029. if (boundsRect)
  34030. {
  34031. this.boundsRect = boundsRect;
  34032. }
  34033. if (boundsSprite)
  34034. {
  34035. this.boundsSprite = boundsSprite;
  34036. }
  34037. },
  34038. /**
  34039. * Stops this sprite from being able to be dragged.
  34040. * If it is currently the target of an active drag it will be stopped immediately; also disables any set callbacks.
  34041. *
  34042. * @method Phaser.InputHandler#disableDrag
  34043. */
  34044. disableDrag: function () {
  34045. if (this._pointerData)
  34046. {
  34047. for (var i = 0; i < 10; i++)
  34048. {
  34049. this._pointerData[i].isDragged = false;
  34050. }
  34051. }
  34052. this.draggable = false;
  34053. this.isDragged = false;
  34054. this._draggedPointerID = -1;
  34055. },
  34056. /**
  34057. * Called by Pointer when drag starts on this Sprite. Should not usually be called directly.
  34058. *
  34059. * @method Phaser.InputHandler#startDrag
  34060. * @param {Phaser.Pointer} pointer
  34061. */
  34062. startDrag: function (pointer) {
  34063. var x = this.sprite.x;
  34064. var y = this.sprite.y;
  34065. this.isDragged = true;
  34066. this._draggedPointerID = pointer.id;
  34067. this._pointerData[pointer.id].camX = this.game.camera.x;
  34068. this._pointerData[pointer.id].camY = this.game.camera.y;
  34069. this._pointerData[pointer.id].isDragged = true;
  34070. if (this.sprite.fixedToCamera)
  34071. {
  34072. if (this.dragFromCenter)
  34073. {
  34074. var bounds = this.sprite.getBounds();
  34075. this.sprite.cameraOffset.x = this.globalToLocalX(pointer.x) + (this.sprite.cameraOffset.x - bounds.centerX);
  34076. this.sprite.cameraOffset.y = this.globalToLocalY(pointer.y) + (this.sprite.cameraOffset.y - bounds.centerY);
  34077. }
  34078. this._dragPoint.setTo(this.sprite.cameraOffset.x - pointer.x, this.sprite.cameraOffset.y - pointer.y);
  34079. }
  34080. else
  34081. {
  34082. if (this.dragFromCenter)
  34083. {
  34084. var bounds = this.sprite.getBounds();
  34085. this.sprite.x = this.globalToLocalX(pointer.x) + (this.sprite.x - bounds.centerX);
  34086. this.sprite.y = this.globalToLocalY(pointer.y) + (this.sprite.y - bounds.centerY);
  34087. }
  34088. this._dragPoint.setTo(this.sprite.x - this.globalToLocalX(pointer.x), this.sprite.y - this.globalToLocalY(pointer.y));
  34089. }
  34090. this.updateDrag(pointer, true);
  34091. if (this.bringToTop)
  34092. {
  34093. this._dragPhase = true;
  34094. this.sprite.bringToTop();
  34095. }
  34096. this.dragStartPoint.set(x, y);
  34097. this.sprite.events.onDragStart$dispatch(this.sprite, pointer, x, y);
  34098. },
  34099. /**
  34100. * Warning: EXPERIMENTAL
  34101. *
  34102. * @method Phaser.InputHandler#globalToLocalX
  34103. * @param {number} x
  34104. */
  34105. globalToLocalX: function (x) {
  34106. if (this.scaleLayer)
  34107. {
  34108. x -= this.game.scale.grid.boundsFluid.x;
  34109. x *= this.game.scale.grid.scaleFluidInversed.x;
  34110. }
  34111. return x;
  34112. },
  34113. /**
  34114. * Warning: EXPERIMENTAL
  34115. *
  34116. * @method Phaser.InputHandler#globalToLocalY
  34117. * @param {number} y
  34118. */
  34119. globalToLocalY: function (y) {
  34120. if (this.scaleLayer)
  34121. {
  34122. y -= this.game.scale.grid.boundsFluid.y;
  34123. y *= this.game.scale.grid.scaleFluidInversed.y;
  34124. }
  34125. return y;
  34126. },
  34127. /**
  34128. * Called by Pointer when drag is stopped on this Sprite. Should not usually be called directly.
  34129. *
  34130. * @method Phaser.InputHandler#stopDrag
  34131. * @param {Phaser.Pointer} pointer
  34132. */
  34133. stopDrag: function (pointer) {
  34134. this.isDragged = false;
  34135. this._draggedPointerID = -1;
  34136. this._pointerData[pointer.id].isDragged = false;
  34137. this._dragPhase = false;
  34138. if (this.snapOnRelease)
  34139. {
  34140. if (this.sprite.fixedToCamera)
  34141. {
  34142. this.sprite.cameraOffset.x = Math.round((this.sprite.cameraOffset.x - (this.snapOffsetX % this.snapX)) / this.snapX) * this.snapX + (this.snapOffsetX % this.snapX);
  34143. this.sprite.cameraOffset.y = Math.round((this.sprite.cameraOffset.y - (this.snapOffsetY % this.snapY)) / this.snapY) * this.snapY + (this.snapOffsetY % this.snapY);
  34144. }
  34145. else
  34146. {
  34147. this.sprite.x = Math.round((this.sprite.x - (this.snapOffsetX % this.snapX)) / this.snapX) * this.snapX + (this.snapOffsetX % this.snapX);
  34148. this.sprite.y = Math.round((this.sprite.y - (this.snapOffsetY % this.snapY)) / this.snapY) * this.snapY + (this.snapOffsetY % this.snapY);
  34149. }
  34150. }
  34151. this.sprite.events.onDragStop$dispatch(this.sprite, pointer);
  34152. if (this.checkPointerOver(pointer) === false)
  34153. {
  34154. this._pointerOutHandler(pointer);
  34155. }
  34156. },
  34157. /**
  34158. * Restricts this sprite to drag movement only on the given axis. Note: If both are set to false the sprite will never move!
  34159. *
  34160. * @method Phaser.InputHandler#setDragLock
  34161. * @param {boolean} [allowHorizontal=true] - To enable the sprite to be dragged horizontally set to true, otherwise false.
  34162. * @param {boolean} [allowVertical=true] - To enable the sprite to be dragged vertically set to true, otherwise false.
  34163. */
  34164. setDragLock: function (allowHorizontal, allowVertical) {
  34165. if (allowHorizontal === undefined) { allowHorizontal = true; }
  34166. if (allowVertical === undefined) { allowVertical = true; }
  34167. this.allowHorizontalDrag = allowHorizontal;
  34168. this.allowVerticalDrag = allowVertical;
  34169. },
  34170. /**
  34171. * Make this Sprite snap to the given grid either during drag or when it's released.
  34172. * For example 16x16 as the snapX and snapY would make the sprite snap to every 16 pixels.
  34173. *
  34174. * @method Phaser.InputHandler#enableSnap
  34175. * @param {number} snapX - The width of the grid cell to snap to.
  34176. * @param {number} snapY - The height of the grid cell to snap to.
  34177. * @param {boolean} [onDrag=true] - If true the sprite will snap to the grid while being dragged.
  34178. * @param {boolean} [onRelease=false] - If true the sprite will snap to the grid when released.
  34179. * @param {number} [snapOffsetX=0] - Used to offset the top-left starting point of the snap grid.
  34180. * @param {number} [snapOffsetY=0] - Used to offset the top-left starting point of the snap grid.
  34181. */
  34182. enableSnap: function (snapX, snapY, onDrag, onRelease, snapOffsetX, snapOffsetY) {
  34183. if (onDrag === undefined) { onDrag = true; }
  34184. if (onRelease === undefined) { onRelease = false; }
  34185. if (snapOffsetX === undefined) { snapOffsetX = 0; }
  34186. if (snapOffsetY === undefined) { snapOffsetY = 0; }
  34187. this.snapX = snapX;
  34188. this.snapY = snapY;
  34189. this.snapOffsetX = snapOffsetX;
  34190. this.snapOffsetY = snapOffsetY;
  34191. this.snapOnDrag = onDrag;
  34192. this.snapOnRelease = onRelease;
  34193. },
  34194. /**
  34195. * Stops the sprite from snapping to a grid during drag or release.
  34196. *
  34197. * @method Phaser.InputHandler#disableSnap
  34198. */
  34199. disableSnap: function () {
  34200. this.snapOnDrag = false;
  34201. this.snapOnRelease = false;
  34202. },
  34203. /**
  34204. * Bounds Rect check for the sprite drag
  34205. *
  34206. * @method Phaser.InputHandler#checkBoundsRect
  34207. */
  34208. checkBoundsRect: function () {
  34209. if (this.sprite.fixedToCamera)
  34210. {
  34211. if (this.sprite.cameraOffset.x < this.boundsRect.left)
  34212. {
  34213. this.sprite.cameraOffset.x = this.boundsRect.left;
  34214. }
  34215. else if ((this.sprite.cameraOffset.x + this.sprite.width) > this.boundsRect.right)
  34216. {
  34217. this.sprite.cameraOffset.x = this.boundsRect.right - this.sprite.width;
  34218. }
  34219. if (this.sprite.cameraOffset.y < this.boundsRect.top)
  34220. {
  34221. this.sprite.cameraOffset.y = this.boundsRect.top;
  34222. }
  34223. else if ((this.sprite.cameraOffset.y + this.sprite.height) > this.boundsRect.bottom)
  34224. {
  34225. this.sprite.cameraOffset.y = this.boundsRect.bottom - this.sprite.height;
  34226. }
  34227. }
  34228. else
  34229. {
  34230. if (this.sprite.left < this.boundsRect.left)
  34231. {
  34232. this.sprite.x = this.boundsRect.x + this.sprite.offsetX;
  34233. }
  34234. else if (this.sprite.right > this.boundsRect.right)
  34235. {
  34236. this.sprite.x = this.boundsRect.right - (this.sprite.width - this.sprite.offsetX);
  34237. }
  34238. if (this.sprite.top < this.boundsRect.top)
  34239. {
  34240. this.sprite.y = this.boundsRect.top + this.sprite.offsetY;
  34241. }
  34242. else if (this.sprite.bottom > this.boundsRect.bottom)
  34243. {
  34244. this.sprite.y = this.boundsRect.bottom - (this.sprite.height - this.sprite.offsetY);
  34245. }
  34246. }
  34247. },
  34248. /**
  34249. * Parent Sprite Bounds check for the sprite drag.
  34250. *
  34251. * @method Phaser.InputHandler#checkBoundsSprite
  34252. */
  34253. checkBoundsSprite: function () {
  34254. if (this.sprite.fixedToCamera && this.boundsSprite.fixedToCamera)
  34255. {
  34256. if (this.sprite.cameraOffset.x < this.boundsSprite.cameraOffset.x)
  34257. {
  34258. this.sprite.cameraOffset.x = this.boundsSprite.cameraOffset.x;
  34259. }
  34260. else if ((this.sprite.cameraOffset.x + this.sprite.width) > (this.boundsSprite.cameraOffset.x + this.boundsSprite.width))
  34261. {
  34262. this.sprite.cameraOffset.x = (this.boundsSprite.cameraOffset.x + this.boundsSprite.width) - this.sprite.width;
  34263. }
  34264. if (this.sprite.cameraOffset.y < this.boundsSprite.cameraOffset.y)
  34265. {
  34266. this.sprite.cameraOffset.y = this.boundsSprite.cameraOffset.y;
  34267. }
  34268. else if ((this.sprite.cameraOffset.y + this.sprite.height) > (this.boundsSprite.cameraOffset.y + this.boundsSprite.height))
  34269. {
  34270. this.sprite.cameraOffset.y = (this.boundsSprite.cameraOffset.y + this.boundsSprite.height) - this.sprite.height;
  34271. }
  34272. }
  34273. else
  34274. {
  34275. if (this.sprite.left < this.boundsSprite.left)
  34276. {
  34277. this.sprite.x = this.boundsSprite.left + this.sprite.offsetX;
  34278. }
  34279. else if (this.sprite.right > this.boundsSprite.right)
  34280. {
  34281. this.sprite.x = this.boundsSprite.right - (this.sprite.width - this.sprite.offsetX);
  34282. }
  34283. if (this.sprite.top < this.boundsSprite.top)
  34284. {
  34285. this.sprite.y = this.boundsSprite.top + this.sprite.offsetY;
  34286. }
  34287. else if (this.sprite.bottom > this.boundsSprite.bottom)
  34288. {
  34289. this.sprite.y = this.boundsSprite.bottom - (this.sprite.height - this.sprite.offsetY);
  34290. }
  34291. // if (this.sprite.x < this.boundsSprite.x)
  34292. // {
  34293. // this.sprite.x = this.boundsSprite.x;
  34294. // }
  34295. // else if ((this.sprite.x + this.sprite.width) > (this.boundsSprite.x + this.boundsSprite.width))
  34296. // {
  34297. // this.sprite.x = (this.boundsSprite.x + this.boundsSprite.width) - this.sprite.width;
  34298. // }
  34299. // if (this.sprite.y < this.boundsSprite.y)
  34300. // {
  34301. // this.sprite.y = this.boundsSprite.y;
  34302. // }
  34303. // else if ((this.sprite.y + this.sprite.height) > (this.boundsSprite.y + this.boundsSprite.height))
  34304. // {
  34305. // this.sprite.y = (this.boundsSprite.y + this.boundsSprite.height) - this.sprite.height;
  34306. // }
  34307. }
  34308. }
  34309. };
  34310. Phaser.InputHandler.prototype.constructor = Phaser.InputHandler;
  34311. /**
  34312. * @author @karlmacklin <tacklemcclean@gmail.com>
  34313. * @copyright 2016 Photon Storm Ltd.
  34314. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  34315. */
  34316. /**
  34317. * The Gamepad class handles gamepad input and dispatches gamepad events.
  34318. *
  34319. * Remember to call `gamepad.start()`.
  34320. *
  34321. * HTML5 GAMEPAD API SUPPORT IS AT AN EXPERIMENTAL STAGE!
  34322. * At moment of writing this (end of 2013) only Chrome supports parts of it out of the box. Firefox supports it
  34323. * via prefs flags (about:config, search gamepad). The browsers map the same controllers differently.
  34324. * This class has constants for Windows 7 Chrome mapping of XBOX 360 controller.
  34325. *
  34326. * @class Phaser.Gamepad
  34327. * @constructor
  34328. * @param {Phaser.Game} game - A reference to the currently running game.
  34329. */
  34330. Phaser.Gamepad = function (game) {
  34331. /**
  34332. * @property {Phaser.Game} game - Local reference to game.
  34333. */
  34334. this.game = game;
  34335. /**
  34336. * @property {object} _gamepadIndexMap - Maps the browsers gamepad indices to our Phaser Gamepads
  34337. * @private
  34338. */
  34339. this._gamepadIndexMap = {};
  34340. /**
  34341. * @property {Array} _rawPads - The raw state of the gamepads from the browser
  34342. * @private
  34343. */
  34344. this._rawPads = [];
  34345. /**
  34346. * @property {boolean} _active - Private flag for whether or not the API is polled
  34347. * @private
  34348. * @default
  34349. */
  34350. this._active = false;
  34351. /**
  34352. * Gamepad input will only be processed if enabled.
  34353. * @property {boolean} enabled
  34354. * @default
  34355. */
  34356. this.enabled = true;
  34357. /**
  34358. * Whether or not gamepads are supported in the current browser. Note that as of Dec. 2013 this check is actually not accurate at all due to poor implementation.
  34359. * @property {boolean} _gamepadSupportAvailable - Are gamepads supported in this browser or not?
  34360. * @private
  34361. */
  34362. this._gamepadSupportAvailable = !!navigator.webkitGetGamepads || !!navigator.webkitGamepads || (navigator.userAgent.indexOf('Firefox/') != -1) || !!navigator.getGamepads;
  34363. /**
  34364. * Used to check for differences between earlier polls and current state of gamepads.
  34365. * @property {Array} _prevRawGamepadTypes
  34366. * @private
  34367. * @default
  34368. */
  34369. this._prevRawGamepadTypes = [];
  34370. /**
  34371. * Used to check for differences between earlier polls and current state of gamepads.
  34372. * @property {Array} _prevTimestamps
  34373. * @private
  34374. * @default
  34375. */
  34376. this._prevTimestamps = [];
  34377. /**
  34378. * @property {object} callbackContext - The context under which the callbacks are run.
  34379. */
  34380. this.callbackContext = this;
  34381. /**
  34382. * @property {function} onConnectCallback - This callback is invoked every time any gamepad is connected
  34383. */
  34384. this.onConnectCallback = null;
  34385. /**
  34386. * @property {function} onDisconnectCallback - This callback is invoked every time any gamepad is disconnected
  34387. */
  34388. this.onDisconnectCallback = null;
  34389. /**
  34390. * @property {function} onDownCallback - This callback is invoked every time any gamepad button is pressed down.
  34391. */
  34392. this.onDownCallback = null;
  34393. /**
  34394. * @property {function} onUpCallback - This callback is invoked every time any gamepad button is released.
  34395. */
  34396. this.onUpCallback = null;
  34397. /**
  34398. * @property {function} onAxisCallback - This callback is invoked every time any gamepad axis is changed.
  34399. */
  34400. this.onAxisCallback = null;
  34401. /**
  34402. * @property {function} onFloatCallback - This callback is invoked every time any gamepad button is changed to a value where value > 0 and value < 1.
  34403. */
  34404. this.onFloatCallback = null;
  34405. /**
  34406. * @property {function} _ongamepadconnected - Private callback for Firefox gamepad connection handling
  34407. * @private
  34408. */
  34409. this._ongamepadconnected = null;
  34410. /**
  34411. * @property {function} _gamepaddisconnected - Private callback for Firefox gamepad connection handling
  34412. * @private
  34413. */
  34414. this._gamepaddisconnected = null;
  34415. /**
  34416. * @property {Array<Phaser.SinglePad>} _gamepads - The four Phaser Gamepads.
  34417. * @private
  34418. */
  34419. this._gamepads = [
  34420. new Phaser.SinglePad(game, this),
  34421. new Phaser.SinglePad(game, this),
  34422. new Phaser.SinglePad(game, this),
  34423. new Phaser.SinglePad(game, this)
  34424. ];
  34425. };
  34426. Phaser.Gamepad.prototype = {
  34427. /**
  34428. * Add callbacks to the main Gamepad handler to handle connect/disconnect/button down/button up/axis change/float value buttons.
  34429. *
  34430. * @method Phaser.Gamepad#addCallbacks
  34431. * @param {object} context - The context under which the callbacks are run.
  34432. * @param {object} callbacks - Object that takes six different callback methods:
  34433. * onConnectCallback, onDisconnectCallback, onDownCallback, onUpCallback, onAxisCallback, onFloatCallback
  34434. */
  34435. addCallbacks: function (context, callbacks) {
  34436. if (typeof callbacks !== 'undefined')
  34437. {
  34438. this.onConnectCallback = (typeof callbacks.onConnect === 'function') ? callbacks.onConnect : this.onConnectCallback;
  34439. this.onDisconnectCallback = (typeof callbacks.onDisconnect === 'function') ? callbacks.onDisconnect : this.onDisconnectCallback;
  34440. this.onDownCallback = (typeof callbacks.onDown === 'function') ? callbacks.onDown : this.onDownCallback;
  34441. this.onUpCallback = (typeof callbacks.onUp === 'function') ? callbacks.onUp : this.onUpCallback;
  34442. this.onAxisCallback = (typeof callbacks.onAxis === 'function') ? callbacks.onAxis : this.onAxisCallback;
  34443. this.onFloatCallback = (typeof callbacks.onFloat === 'function') ? callbacks.onFloat : this.onFloatCallback;
  34444. this.callbackContext = context;
  34445. }
  34446. },
  34447. /**
  34448. * Starts the Gamepad event handling.
  34449. * This MUST be called manually before Phaser will start polling the Gamepad API.
  34450. *
  34451. * @method Phaser.Gamepad#start
  34452. */
  34453. start: function () {
  34454. if (this._active)
  34455. {
  34456. // Avoid setting multiple listeners
  34457. return;
  34458. }
  34459. this._active = true;
  34460. var _this = this;
  34461. this._onGamepadConnected = function (event) {
  34462. return _this.onGamepadConnected(event);
  34463. };
  34464. this._onGamepadDisconnected = function (event) {
  34465. return _this.onGamepadDisconnected(event);
  34466. };
  34467. window.addEventListener('gamepadconnected', this._onGamepadConnected, false);
  34468. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnected, false);
  34469. },
  34470. /**
  34471. * Handles the connection of a Gamepad.
  34472. *
  34473. * @method onGamepadConnected
  34474. * @private
  34475. * @param {object} event - The DOM event.
  34476. */
  34477. onGamepadConnected: function (event) {
  34478. var newPad = event.gamepad;
  34479. this._rawPads.push(newPad);
  34480. this._gamepads[newPad.index].connect(newPad);
  34481. },
  34482. /**
  34483. * Handles the disconnection of a Gamepad.
  34484. *
  34485. * @method onGamepadDisconnected
  34486. * @private
  34487. * @param {object} event - The DOM event.
  34488. */
  34489. onGamepadDisconnected: function (event) {
  34490. var removedPad = event.gamepad;
  34491. for (var i in this._rawPads)
  34492. {
  34493. if (this._rawPads[i].index === removedPad.index)
  34494. {
  34495. this._rawPads.splice(i,1);
  34496. }
  34497. }
  34498. this._gamepads[removedPad.index].disconnect();
  34499. },
  34500. /**
  34501. * Main gamepad update loop. Should not be called manually.
  34502. * @method Phaser.Gamepad#update
  34503. * @protected
  34504. */
  34505. update: function () {
  34506. this._pollGamepads();
  34507. this.pad1.pollStatus();
  34508. this.pad2.pollStatus();
  34509. this.pad3.pollStatus();
  34510. this.pad4.pollStatus();
  34511. },
  34512. /**
  34513. * Updating connected gamepads (for Google Chrome). Should not be called manually.
  34514. *
  34515. * @method Phaser.Gamepad#_pollGamepads
  34516. * @private
  34517. */
  34518. _pollGamepads: function () {
  34519. if (navigator['getGamepads'])
  34520. {
  34521. var rawGamepads = navigator.getGamepads();
  34522. }
  34523. else if (navigator['webkitGetGamepads'])
  34524. {
  34525. var rawGamepads = navigator.webkitGetGamepads();
  34526. }
  34527. else if (navigator['webkitGamepads'])
  34528. {
  34529. var rawGamepads = navigator.webkitGamepads();
  34530. }
  34531. if (rawGamepads)
  34532. {
  34533. this._rawPads = [];
  34534. var gamepadsChanged = false;
  34535. for (var i = 0; i < rawGamepads.length; i++)
  34536. {
  34537. if (typeof rawGamepads[i] !== this._prevRawGamepadTypes[i])
  34538. {
  34539. gamepadsChanged = true;
  34540. this._prevRawGamepadTypes[i] = typeof rawGamepads[i];
  34541. }
  34542. if (rawGamepads[i])
  34543. {
  34544. this._rawPads.push(rawGamepads[i]);
  34545. }
  34546. // Support max 4 pads at the moment
  34547. if (i === 3)
  34548. {
  34549. break;
  34550. }
  34551. }
  34552. if (gamepadsChanged)
  34553. {
  34554. var validConnections = { rawIndices: {}, padIndices: {} };
  34555. var singlePad;
  34556. for (var j = 0; j < this._gamepads.length; j++)
  34557. {
  34558. singlePad = this._gamepads[j];
  34559. if (singlePad.connected)
  34560. {
  34561. for (var k = 0; k < this._rawPads.length; k++)
  34562. {
  34563. if (this._rawPads[k].index === singlePad.index)
  34564. {
  34565. validConnections.rawIndices[singlePad.index] = true;
  34566. validConnections.padIndices[j] = true;
  34567. }
  34568. }
  34569. }
  34570. }
  34571. for (var l = 0; l < this._gamepads.length; l++)
  34572. {
  34573. singlePad = this._gamepads[l];
  34574. if (validConnections.padIndices[l])
  34575. {
  34576. continue;
  34577. }
  34578. if (this._rawPads.length < 1)
  34579. {
  34580. singlePad.disconnect();
  34581. }
  34582. for (var m = 0; m < this._rawPads.length; m++)
  34583. {
  34584. if (validConnections.padIndices[l])
  34585. {
  34586. break;
  34587. }
  34588. var rawPad = this._rawPads[m];
  34589. if (rawPad)
  34590. {
  34591. if (validConnections.rawIndices[rawPad.index])
  34592. {
  34593. singlePad.disconnect();
  34594. continue;
  34595. }
  34596. else
  34597. {
  34598. singlePad.connect(rawPad);
  34599. validConnections.rawIndices[rawPad.index] = true;
  34600. validConnections.padIndices[l] = true;
  34601. }
  34602. }
  34603. else
  34604. {
  34605. singlePad.disconnect();
  34606. }
  34607. }
  34608. }
  34609. }
  34610. }
  34611. },
  34612. /**
  34613. * Sets the deadZone variable for all four gamepads
  34614. * @method Phaser.Gamepad#setDeadZones
  34615. */
  34616. setDeadZones: function (value) {
  34617. for (var i = 0; i < this._gamepads.length; i++)
  34618. {
  34619. this._gamepads[i].deadZone = value;
  34620. }
  34621. },
  34622. /**
  34623. * Stops the Gamepad event handling.
  34624. *
  34625. * @method Phaser.Gamepad#stop
  34626. */
  34627. stop: function () {
  34628. this._active = false;
  34629. window.removeEventListener('gamepadconnected', this._onGamepadConnected);
  34630. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnected);
  34631. },
  34632. /**
  34633. * Reset all buttons/axes of all gamepads
  34634. * @method Phaser.Gamepad#reset
  34635. */
  34636. reset: function () {
  34637. this.update();
  34638. for (var i = 0; i < this._gamepads.length; i++)
  34639. {
  34640. this._gamepads[i].reset();
  34641. }
  34642. },
  34643. /**
  34644. * Returns the "just pressed" state of a button from ANY gamepad connected. Just pressed is considered true if the button was pressed down within the duration given (default 250ms).
  34645. * @method Phaser.Gamepad#justPressed
  34646. * @param {number} buttonCode - The buttonCode of the button to check for.
  34647. * @param {number} [duration=250] - The duration below which the button is considered as being just pressed.
  34648. * @return {boolean} True if the button is just pressed otherwise false.
  34649. */
  34650. justPressed: function (buttonCode, duration) {
  34651. for (var i = 0; i < this._gamepads.length; i++)
  34652. {
  34653. if (this._gamepads[i].justPressed(buttonCode, duration) === true)
  34654. {
  34655. return true;
  34656. }
  34657. }
  34658. return false;
  34659. },
  34660. /**
  34661. * Returns the "just released" state of a button from ANY gamepad connected. Just released is considered as being true if the button was released within the duration given (default 250ms).
  34662. * @method Phaser.Gamepad#justPressed
  34663. * @param {number} buttonCode - The buttonCode of the button to check for.
  34664. * @param {number} [duration=250] - The duration below which the button is considered as being just released.
  34665. * @return {boolean} True if the button is just released otherwise false.
  34666. */
  34667. justReleased: function (buttonCode, duration) {
  34668. for (var i = 0; i < this._gamepads.length; i++)
  34669. {
  34670. if (this._gamepads[i].justReleased(buttonCode, duration) === true)
  34671. {
  34672. return true;
  34673. }
  34674. }
  34675. return false;
  34676. },
  34677. /**
  34678. * Returns true if the button is currently pressed down, on ANY gamepad.
  34679. * @method Phaser.Gamepad#isDown
  34680. * @param {number} buttonCode - The buttonCode of the button to check for.
  34681. * @return {boolean} True if a button is currently down.
  34682. */
  34683. isDown: function (buttonCode) {
  34684. for (var i = 0; i < this._gamepads.length; i++)
  34685. {
  34686. if (this._gamepads[i].isDown(buttonCode) === true)
  34687. {
  34688. return true;
  34689. }
  34690. }
  34691. return false;
  34692. },
  34693. /**
  34694. * Destroys this object and the associated event listeners.
  34695. *
  34696. * @method Phaser.Gamepad#destroy
  34697. */
  34698. destroy: function () {
  34699. this.stop();
  34700. for (var i = 0; i < this._gamepads.length; i++)
  34701. {
  34702. this._gamepads[i].destroy();
  34703. }
  34704. }
  34705. };
  34706. Phaser.Gamepad.prototype.constructor = Phaser.Gamepad;
  34707. /**
  34708. * If the gamepad input is active or not - if not active it should not be updated from Input.js
  34709. * @name Phaser.Gamepad#active
  34710. * @property {boolean} active - If the gamepad input is active or not.
  34711. * @readonly
  34712. */
  34713. Object.defineProperty(Phaser.Gamepad.prototype, "active", {
  34714. get: function () {
  34715. return this._active;
  34716. }
  34717. });
  34718. /**
  34719. * Whether or not gamepads are supported in current browser.
  34720. * @name Phaser.Gamepad#supported
  34721. * @property {boolean} supported - Whether or not gamepads are supported in current browser.
  34722. * @readonly
  34723. */
  34724. Object.defineProperty(Phaser.Gamepad.prototype, "supported", {
  34725. get: function () {
  34726. return this._gamepadSupportAvailable;
  34727. }
  34728. });
  34729. /**
  34730. * How many live gamepads are currently connected.
  34731. * @name Phaser.Gamepad#padsConnected
  34732. * @property {number} padsConnected - How many live gamepads are currently connected.
  34733. * @readonly
  34734. */
  34735. Object.defineProperty(Phaser.Gamepad.prototype, "padsConnected", {
  34736. get: function () {
  34737. return this._rawPads.length;
  34738. }
  34739. });
  34740. /**
  34741. * Gamepad #1
  34742. * @name Phaser.Gamepad#pad1
  34743. * @property {Phaser.SinglePad} pad1 - Gamepad #1;
  34744. * @readonly
  34745. */
  34746. Object.defineProperty(Phaser.Gamepad.prototype, "pad1", {
  34747. get: function () {
  34748. return this._gamepads[0];
  34749. }
  34750. });
  34751. /**
  34752. * Gamepad #2
  34753. * @name Phaser.Gamepad#pad2
  34754. * @property {Phaser.SinglePad} pad2 - Gamepad #2
  34755. * @readonly
  34756. */
  34757. Object.defineProperty(Phaser.Gamepad.prototype, "pad2", {
  34758. get: function () {
  34759. return this._gamepads[1];
  34760. }
  34761. });
  34762. /**
  34763. * Gamepad #3
  34764. * @name Phaser.Gamepad#pad3
  34765. * @property {Phaser.SinglePad} pad3 - Gamepad #3
  34766. * @readonly
  34767. */
  34768. Object.defineProperty(Phaser.Gamepad.prototype, "pad3", {
  34769. get: function () {
  34770. return this._gamepads[2];
  34771. }
  34772. });
  34773. /**
  34774. * Gamepad #4
  34775. * @name Phaser.Gamepad#pad4
  34776. * @property {Phaser.SinglePad} pad4 - Gamepad #4
  34777. * @readonly
  34778. */
  34779. Object.defineProperty(Phaser.Gamepad.prototype, "pad4", {
  34780. get: function () {
  34781. return this._gamepads[3];
  34782. }
  34783. });
  34784. Phaser.Gamepad.BUTTON_0 = 0;
  34785. Phaser.Gamepad.BUTTON_1 = 1;
  34786. Phaser.Gamepad.BUTTON_2 = 2;
  34787. Phaser.Gamepad.BUTTON_3 = 3;
  34788. Phaser.Gamepad.BUTTON_4 = 4;
  34789. Phaser.Gamepad.BUTTON_5 = 5;
  34790. Phaser.Gamepad.BUTTON_6 = 6;
  34791. Phaser.Gamepad.BUTTON_7 = 7;
  34792. Phaser.Gamepad.BUTTON_8 = 8;
  34793. Phaser.Gamepad.BUTTON_9 = 9;
  34794. Phaser.Gamepad.BUTTON_10 = 10;
  34795. Phaser.Gamepad.BUTTON_11 = 11;
  34796. Phaser.Gamepad.BUTTON_12 = 12;
  34797. Phaser.Gamepad.BUTTON_13 = 13;
  34798. Phaser.Gamepad.BUTTON_14 = 14;
  34799. Phaser.Gamepad.BUTTON_15 = 15;
  34800. Phaser.Gamepad.AXIS_0 = 0;
  34801. Phaser.Gamepad.AXIS_1 = 1;
  34802. Phaser.Gamepad.AXIS_2 = 2;
  34803. Phaser.Gamepad.AXIS_3 = 3;
  34804. Phaser.Gamepad.AXIS_4 = 4;
  34805. Phaser.Gamepad.AXIS_5 = 5;
  34806. Phaser.Gamepad.AXIS_6 = 6;
  34807. Phaser.Gamepad.AXIS_7 = 7;
  34808. Phaser.Gamepad.AXIS_8 = 8;
  34809. Phaser.Gamepad.AXIS_9 = 9;
  34810. // Below mapping applies to XBOX 360 Wired and Wireless controller on Google Chrome (tested on Windows 7).
  34811. // - Firefox uses different map! Separate amount of buttons and axes. DPAD = axis and not a button.
  34812. // In other words - discrepancies when using gamepads.
  34813. Phaser.Gamepad.XBOX360_A = 0;
  34814. Phaser.Gamepad.XBOX360_B = 1;
  34815. Phaser.Gamepad.XBOX360_X = 2;
  34816. Phaser.Gamepad.XBOX360_Y = 3;
  34817. Phaser.Gamepad.XBOX360_LEFT_BUMPER = 4;
  34818. Phaser.Gamepad.XBOX360_RIGHT_BUMPER = 5;
  34819. Phaser.Gamepad.XBOX360_LEFT_TRIGGER = 6;
  34820. Phaser.Gamepad.XBOX360_RIGHT_TRIGGER = 7;
  34821. Phaser.Gamepad.XBOX360_BACK = 8;
  34822. Phaser.Gamepad.XBOX360_START = 9;
  34823. Phaser.Gamepad.XBOX360_STICK_LEFT_BUTTON = 10;
  34824. Phaser.Gamepad.XBOX360_STICK_RIGHT_BUTTON = 11;
  34825. Phaser.Gamepad.XBOX360_DPAD_LEFT = 14;
  34826. Phaser.Gamepad.XBOX360_DPAD_RIGHT = 15;
  34827. Phaser.Gamepad.XBOX360_DPAD_UP = 12;
  34828. Phaser.Gamepad.XBOX360_DPAD_DOWN = 13;
  34829. // On FF 0 = Y, 1 = X, 2 = Y, 3 = X, 4 = left bumper, 5 = dpad left, 6 = dpad right
  34830. Phaser.Gamepad.XBOX360_STICK_LEFT_X = 0;
  34831. Phaser.Gamepad.XBOX360_STICK_LEFT_Y = 1;
  34832. Phaser.Gamepad.XBOX360_STICK_RIGHT_X = 2;
  34833. Phaser.Gamepad.XBOX360_STICK_RIGHT_Y = 3;
  34834. // PlayStation 3 controller (masquerading as xbox360 controller) button mappings
  34835. Phaser.Gamepad.PS3XC_X = 0;
  34836. Phaser.Gamepad.PS3XC_CIRCLE = 1;
  34837. Phaser.Gamepad.PS3XC_SQUARE = 2;
  34838. Phaser.Gamepad.PS3XC_TRIANGLE = 3;
  34839. Phaser.Gamepad.PS3XC_L1 = 4;
  34840. Phaser.Gamepad.PS3XC_R1 = 5;
  34841. Phaser.Gamepad.PS3XC_L2 = 6; // analog trigger, range 0..1
  34842. Phaser.Gamepad.PS3XC_R2 = 7; // analog trigger, range 0..1
  34843. Phaser.Gamepad.PS3XC_SELECT = 8;
  34844. Phaser.Gamepad.PS3XC_START = 9;
  34845. Phaser.Gamepad.PS3XC_STICK_LEFT_BUTTON = 10;
  34846. Phaser.Gamepad.PS3XC_STICK_RIGHT_BUTTON = 11;
  34847. Phaser.Gamepad.PS3XC_DPAD_UP = 12;
  34848. Phaser.Gamepad.PS3XC_DPAD_DOWN = 13;
  34849. Phaser.Gamepad.PS3XC_DPAD_LEFT = 14;
  34850. Phaser.Gamepad.PS3XC_DPAD_RIGHT = 15;
  34851. Phaser.Gamepad.PS3XC_STICK_LEFT_X = 0; // analog stick, range -1..1
  34852. Phaser.Gamepad.PS3XC_STICK_LEFT_Y = 1; // analog stick, range -1..1
  34853. Phaser.Gamepad.PS3XC_STICK_RIGHT_X = 2; // analog stick, range -1..1
  34854. Phaser.Gamepad.PS3XC_STICK_RIGHT_Y = 3; // analog stick, range -1..1
  34855. /**
  34856. * @author @karlmacklin <tacklemcclean@gmail.com>
  34857. * @author Richard Davey <rich@photonstorm.com>
  34858. * @copyright 2016 Photon Storm Ltd.
  34859. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  34860. */
  34861. /**
  34862. * A single Phaser Gamepad
  34863. *
  34864. * @class Phaser.SinglePad
  34865. * @constructor
  34866. * @param {Phaser.Game} game - Current game instance.
  34867. * @param {object} padParent - The parent Phaser.Gamepad object (all gamepads reside under this)
  34868. */
  34869. Phaser.SinglePad = function (game, padParent) {
  34870. /**
  34871. * @property {Phaser.Game} game - Local reference to game.
  34872. */
  34873. this.game = game;
  34874. /**
  34875. * @property {number} index - The gamepad index as per browsers data
  34876. * @readonly
  34877. */
  34878. this.index = null;
  34879. /**
  34880. * @property {boolean} connected - Whether or not this particular gamepad is connected or not.
  34881. * @readonly
  34882. */
  34883. this.connected = false;
  34884. /**
  34885. * @property {object} callbackContext - The context under which the callbacks are run.
  34886. */
  34887. this.callbackContext = this;
  34888. /**
  34889. * @property {function} onConnectCallback - This callback is invoked every time this gamepad is connected
  34890. */
  34891. this.onConnectCallback = null;
  34892. /**
  34893. * @property {function} onDisconnectCallback - This callback is invoked every time this gamepad is disconnected
  34894. */
  34895. this.onDisconnectCallback = null;
  34896. /**
  34897. * @property {function} onDownCallback - This callback is invoked every time a button is pressed down.
  34898. */
  34899. this.onDownCallback = null;
  34900. /**
  34901. * @property {function} onUpCallback - This callback is invoked every time a gamepad button is released.
  34902. */
  34903. this.onUpCallback = null;
  34904. /**
  34905. * @property {function} onAxisCallback - This callback is invoked every time an axis is changed.
  34906. */
  34907. this.onAxisCallback = null;
  34908. /**
  34909. * @property {function} onFloatCallback - This callback is invoked every time a button is changed to a value where value > 0 and value < 1.
  34910. */
  34911. this.onFloatCallback = null;
  34912. /**
  34913. * @property {number} deadZone - Dead zone for axis feedback - within this value you won't trigger updates.
  34914. */
  34915. this.deadZone = 0.26;
  34916. /**
  34917. * @property {Phaser.Gamepad} padParent - Main Phaser Gamepad object
  34918. * @private
  34919. */
  34920. this._padParent = padParent;
  34921. /**
  34922. * @property {object} _rawPad - The 'raw' gamepad data.
  34923. * @private
  34924. */
  34925. this._rawPad = null;
  34926. /**
  34927. * @property {number} _prevTimestamp - Used to check for differences between earlier polls and current state of gamepads.
  34928. * @private
  34929. */
  34930. this._prevTimestamp = null;
  34931. /**
  34932. * @property {Array} _buttons - Array of Phaser.DeviceButton objects. This array is populated when the gamepad is connected.
  34933. * @private
  34934. */
  34935. this._buttons = [];
  34936. /**
  34937. * @property {number} _buttonsLen - Length of the _buttons array.
  34938. * @private
  34939. */
  34940. this._buttonsLen = 0;
  34941. /**
  34942. * @property {Array} _axes - Current axes state.
  34943. * @private
  34944. */
  34945. this._axes = [];
  34946. /**
  34947. * @property {number} _axesLen - Length of the _axes array.
  34948. * @private
  34949. */
  34950. this._axesLen = 0;
  34951. };
  34952. Phaser.SinglePad.prototype = {
  34953. /**
  34954. * Add callbacks to this Gamepad to handle connect / disconnect / button down / button up / axis change / float value buttons.
  34955. *
  34956. * @method Phaser.SinglePad#addCallbacks
  34957. * @param {object} context - The context under which the callbacks are run.
  34958. * @param {object} callbacks - Object that takes six different callbak methods:
  34959. * onConnectCallback, onDisconnectCallback, onDownCallback, onUpCallback, onAxisCallback, onFloatCallback
  34960. */
  34961. addCallbacks: function (context, callbacks) {
  34962. if (typeof callbacks !== 'undefined')
  34963. {
  34964. this.onConnectCallback = (typeof callbacks.onConnect === 'function') ? callbacks.onConnect : this.onConnectCallback;
  34965. this.onDisconnectCallback = (typeof callbacks.onDisconnect === 'function') ? callbacks.onDisconnect : this.onDisconnectCallback;
  34966. this.onDownCallback = (typeof callbacks.onDown === 'function') ? callbacks.onDown : this.onDownCallback;
  34967. this.onUpCallback = (typeof callbacks.onUp === 'function') ? callbacks.onUp : this.onUpCallback;
  34968. this.onAxisCallback = (typeof callbacks.onAxis === 'function') ? callbacks.onAxis : this.onAxisCallback;
  34969. this.onFloatCallback = (typeof callbacks.onFloat === 'function') ? callbacks.onFloat : this.onFloatCallback;
  34970. this.callbackContext = context;
  34971. }
  34972. },
  34973. /**
  34974. * Gets a DeviceButton object from this controller to be stored and referenced locally.
  34975. * The DeviceButton object can then be polled, have events attached to it, etc.
  34976. *
  34977. * @method Phaser.SinglePad#getButton
  34978. * @param {number} buttonCode - The buttonCode of the button, i.e. Phaser.Gamepad.BUTTON_0, Phaser.Gamepad.XBOX360_A, etc.
  34979. * @return {Phaser.DeviceButton} The DeviceButton object which you can store locally and reference directly.
  34980. */
  34981. getButton: function (buttonCode) {
  34982. if (this._buttons[buttonCode])
  34983. {
  34984. return this._buttons[buttonCode];
  34985. }
  34986. else
  34987. {
  34988. return null;
  34989. }
  34990. },
  34991. /**
  34992. * Main update function called by Phaser.Gamepad.
  34993. *
  34994. * @method Phaser.SinglePad#pollStatus
  34995. */
  34996. pollStatus: function () {
  34997. if (!this.connected || !this.game.input.enabled || !this.game.input.gamepad.enabled || (this._rawPad.timestamp && (this._rawPad.timestamp === this._prevTimestamp)))
  34998. {
  34999. return;
  35000. }
  35001. for (var i = 0; i < this._buttonsLen; i++)
  35002. {
  35003. var rawButtonVal = isNaN(this._rawPad.buttons[i]) ? this._rawPad.buttons[i].value : this._rawPad.buttons[i];
  35004. if (rawButtonVal !== this._buttons[i].value)
  35005. {
  35006. if (rawButtonVal === 1)
  35007. {
  35008. this.processButtonDown(i, rawButtonVal);
  35009. }
  35010. else if (rawButtonVal === 0)
  35011. {
  35012. this.processButtonUp(i, rawButtonVal);
  35013. }
  35014. else
  35015. {
  35016. this.processButtonFloat(i, rawButtonVal);
  35017. }
  35018. }
  35019. }
  35020. for (var index = 0; index < this._axesLen; index++)
  35021. {
  35022. var value = this._rawPad.axes[index];
  35023. if ((value > 0 && value > this.deadZone) || (value < 0 && value < -this.deadZone))
  35024. {
  35025. this.processAxisChange(index, value);
  35026. }
  35027. else
  35028. {
  35029. this.processAxisChange(index, 0);
  35030. }
  35031. }
  35032. this._prevTimestamp = this._rawPad.timestamp;
  35033. },
  35034. /**
  35035. * Gamepad connect function, should be called by Phaser.Gamepad.
  35036. *
  35037. * @method Phaser.SinglePad#connect
  35038. * @param {object} rawPad - The raw gamepad object
  35039. */
  35040. connect: function (rawPad) {
  35041. var triggerCallback = !this.connected;
  35042. this.connected = true;
  35043. this.index = rawPad.index;
  35044. this._rawPad = rawPad;
  35045. this._buttons = [];
  35046. this._buttonsLen = rawPad.buttons.length;
  35047. this._axes = [];
  35048. this._axesLen = rawPad.axes.length;
  35049. for (var a = 0; a < this._axesLen; a++)
  35050. {
  35051. this._axes[a] = rawPad.axes[a];
  35052. }
  35053. for (var buttonCode in rawPad.buttons)
  35054. {
  35055. buttonCode = parseInt(buttonCode, 10);
  35056. this._buttons[buttonCode] = new Phaser.DeviceButton(this, buttonCode);
  35057. }
  35058. if (triggerCallback && this._padParent.onConnectCallback)
  35059. {
  35060. this._padParent.onConnectCallback.call(this._padParent.callbackContext, this.index);
  35061. }
  35062. if (triggerCallback && this.onConnectCallback)
  35063. {
  35064. this.onConnectCallback.call(this.callbackContext);
  35065. }
  35066. },
  35067. /**
  35068. * Gamepad disconnect function, should be called by Phaser.Gamepad.
  35069. *
  35070. * @method Phaser.SinglePad#disconnect
  35071. */
  35072. disconnect: function () {
  35073. var triggerCallback = this.connected;
  35074. var disconnectingIndex = this.index;
  35075. this.connected = false;
  35076. this.index = null;
  35077. this._rawPad = undefined;
  35078. for (var i = 0; i < this._buttonsLen; i++)
  35079. {
  35080. this._buttons[i].destroy();
  35081. }
  35082. this._buttons = [];
  35083. this._buttonsLen = 0;
  35084. this._axes = [];
  35085. this._axesLen = 0;
  35086. if (triggerCallback && this._padParent.onDisconnectCallback)
  35087. {
  35088. this._padParent.onDisconnectCallback.call(this._padParent.callbackContext, disconnectingIndex);
  35089. }
  35090. if (triggerCallback && this.onDisconnectCallback)
  35091. {
  35092. this.onDisconnectCallback.call(this.callbackContext);
  35093. }
  35094. },
  35095. /**
  35096. * Destroys this object and associated callback references.
  35097. *
  35098. * @method Phaser.SinglePad#destroy
  35099. */
  35100. destroy: function () {
  35101. this._rawPad = undefined;
  35102. for (var i = 0; i < this._buttonsLen; i++)
  35103. {
  35104. this._buttons[i].destroy();
  35105. }
  35106. this._buttons = [];
  35107. this._buttonsLen = 0;
  35108. this._axes = [];
  35109. this._axesLen = 0;
  35110. this.onConnectCallback = null;
  35111. this.onDisconnectCallback = null;
  35112. this.onDownCallback = null;
  35113. this.onUpCallback = null;
  35114. this.onAxisCallback = null;
  35115. this.onFloatCallback = null;
  35116. },
  35117. /**
  35118. * Handles changes in axis.
  35119. *
  35120. * @method Phaser.SinglePad#processAxisChange
  35121. * @param {object} axisState - State of the relevant axis
  35122. */
  35123. processAxisChange: function (index, value) {
  35124. if (this._axes[index] === value)
  35125. {
  35126. return;
  35127. }
  35128. this._axes[index] = value;
  35129. if (this._padParent.onAxisCallback)
  35130. {
  35131. this._padParent.onAxisCallback.call(this._padParent.callbackContext, this, index, value);
  35132. }
  35133. if (this.onAxisCallback)
  35134. {
  35135. this.onAxisCallback.call(this.callbackContext, this, index, value);
  35136. }
  35137. },
  35138. /**
  35139. * Handles button down press.
  35140. *
  35141. * @method Phaser.SinglePad#processButtonDown
  35142. * @param {number} buttonCode - Which buttonCode of this button
  35143. * @param {object} value - Button value
  35144. */
  35145. processButtonDown: function (buttonCode, value) {
  35146. if (this._buttons[buttonCode])
  35147. {
  35148. this._buttons[buttonCode].start(null, value);
  35149. }
  35150. if (this._padParent.onDownCallback)
  35151. {
  35152. this._padParent.onDownCallback.call(this._padParent.callbackContext, buttonCode, value, this.index);
  35153. }
  35154. if (this.onDownCallback)
  35155. {
  35156. this.onDownCallback.call(this.callbackContext, buttonCode, value);
  35157. }
  35158. },
  35159. /**
  35160. * Handles button release.
  35161. *
  35162. * @method Phaser.SinglePad#processButtonUp
  35163. * @param {number} buttonCode - Which buttonCode of this button
  35164. * @param {object} value - Button value
  35165. */
  35166. processButtonUp: function (buttonCode, value) {
  35167. if (this._padParent.onUpCallback)
  35168. {
  35169. this._padParent.onUpCallback.call(this._padParent.callbackContext, buttonCode, value, this.index);
  35170. }
  35171. if (this.onUpCallback)
  35172. {
  35173. this.onUpCallback.call(this.callbackContext, buttonCode, value);
  35174. }
  35175. if (this._buttons[buttonCode])
  35176. {
  35177. this._buttons[buttonCode].stop(null, value);
  35178. }
  35179. },
  35180. /**
  35181. * Handles buttons with floating values (like analog buttons that acts almost like an axis but still registers like a button)
  35182. *
  35183. * @method Phaser.SinglePad#processButtonFloat
  35184. * @param {number} buttonCode - Which buttonCode of this button
  35185. * @param {object} value - Button value (will range somewhere between 0 and 1, but not specifically 0 or 1.
  35186. */
  35187. processButtonFloat: function (buttonCode, value) {
  35188. if (this._padParent.onFloatCallback)
  35189. {
  35190. this._padParent.onFloatCallback.call(this._padParent.callbackContext, buttonCode, value, this.index);
  35191. }
  35192. if (this.onFloatCallback)
  35193. {
  35194. this.onFloatCallback.call(this.callbackContext, buttonCode, value);
  35195. }
  35196. if (this._buttons[buttonCode])
  35197. {
  35198. this._buttons[buttonCode].padFloat(value);
  35199. }
  35200. },
  35201. /**
  35202. * Returns value of requested axis.
  35203. *
  35204. * @method Phaser.SinglePad#axis
  35205. * @param {number} axisCode - The index of the axis to check
  35206. * @return {number} Axis value if available otherwise false
  35207. */
  35208. axis: function (axisCode) {
  35209. if (this._axes[axisCode])
  35210. {
  35211. return this._axes[axisCode];
  35212. }
  35213. return false;
  35214. },
  35215. /**
  35216. * Returns true if the button is pressed down.
  35217. *
  35218. * @method Phaser.SinglePad#isDown
  35219. * @param {number} buttonCode - The buttonCode of the button to check.
  35220. * @return {boolean} True if the button is pressed down.
  35221. */
  35222. isDown: function (buttonCode) {
  35223. if (this._buttons[buttonCode])
  35224. {
  35225. return this._buttons[buttonCode].isDown;
  35226. }
  35227. return false;
  35228. },
  35229. /**
  35230. * Returns true if the button is not currently pressed.
  35231. *
  35232. * @method Phaser.SinglePad#isUp
  35233. * @param {number} buttonCode - The buttonCode of the button to check.
  35234. * @return {boolean} True if the button is not currently pressed down.
  35235. */
  35236. isUp: function (buttonCode) {
  35237. if (this._buttons[buttonCode])
  35238. {
  35239. return this._buttons[buttonCode].isUp;
  35240. }
  35241. return false;
  35242. },
  35243. /**
  35244. * Returns the "just released" state of a button from this gamepad. Just released is considered as being true if the button was released within the duration given (default 250ms).
  35245. *
  35246. * @method Phaser.SinglePad#justReleased
  35247. * @param {number} buttonCode - The buttonCode of the button to check for.
  35248. * @param {number} [duration=250] - The duration below which the button is considered as being just released.
  35249. * @return {boolean} True if the button is just released otherwise false.
  35250. */
  35251. justReleased: function (buttonCode, duration) {
  35252. if (this._buttons[buttonCode])
  35253. {
  35254. return this._buttons[buttonCode].justReleased(duration);
  35255. }
  35256. },
  35257. /**
  35258. * Returns the "just pressed" state of a button from this gamepad. Just pressed is considered true if the button was pressed down within the duration given (default 250ms).
  35259. *
  35260. * @method Phaser.SinglePad#justPressed
  35261. * @param {number} buttonCode - The buttonCode of the button to check for.
  35262. * @param {number} [duration=250] - The duration below which the button is considered as being just pressed.
  35263. * @return {boolean} True if the button is just pressed otherwise false.
  35264. */
  35265. justPressed: function (buttonCode, duration) {
  35266. if (this._buttons[buttonCode])
  35267. {
  35268. return this._buttons[buttonCode].justPressed(duration);
  35269. }
  35270. },
  35271. /**
  35272. * Returns the value of a gamepad button. Intended mainly for cases when you have floating button values, for example
  35273. * analog trigger buttons on the XBOX 360 controller.
  35274. *
  35275. * @method Phaser.SinglePad#buttonValue
  35276. * @param {number} buttonCode - The buttonCode of the button to check.
  35277. * @return {number} Button value if available otherwise null. Be careful as this can incorrectly evaluate to 0.
  35278. */
  35279. buttonValue: function (buttonCode) {
  35280. if (this._buttons[buttonCode])
  35281. {
  35282. return this._buttons[buttonCode].value;
  35283. }
  35284. return null;
  35285. },
  35286. /**
  35287. * Reset all buttons/axes of this gamepad.
  35288. *
  35289. * @method Phaser.SinglePad#reset
  35290. */
  35291. reset: function () {
  35292. for (var j = 0; j < this._axes.length; j++)
  35293. {
  35294. this._axes[j] = 0;
  35295. }
  35296. }
  35297. };
  35298. Phaser.SinglePad.prototype.constructor = Phaser.SinglePad;
  35299. /**
  35300. * @author Richard Davey <rich@photonstorm.com>
  35301. * @copyright 2016 Photon Storm Ltd.
  35302. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  35303. */
  35304. /**
  35305. * If you need more fine-grained control over the handling of specific keys you can create and use Phaser.Key objects.
  35306. *
  35307. * @class Phaser.Key
  35308. * @constructor
  35309. * @param {Phaser.Game} game - Current game instance.
  35310. * @param {integer} keycode - The key code this Key is responsible for. See {@link Phaser.KeyCode}.
  35311. */
  35312. Phaser.Key = function (game, keycode) {
  35313. /**
  35314. * @property {Phaser.Game} game - A reference to the currently running game.
  35315. */
  35316. this.game = game;
  35317. /**
  35318. * The enabled state of the key - see `enabled`.
  35319. * @property {boolean} _enabled
  35320. * @private
  35321. */
  35322. this._enabled = true;
  35323. /**
  35324. * @property {object} event - Stores the most recent DOM event.
  35325. * @readonly
  35326. */
  35327. this.event = null;
  35328. /**
  35329. * @property {boolean} isDown - The "down" state of the key. This will remain `true` for as long as the keyboard thinks this key is held down.
  35330. * @default
  35331. */
  35332. this.isDown = false;
  35333. /**
  35334. * @property {boolean} isUp - The "up" state of the key. This will remain `true` for as long as the keyboard thinks this key is up.
  35335. * @default
  35336. */
  35337. this.isUp = true;
  35338. /**
  35339. * @property {boolean} altKey - The down state of the ALT key, if pressed at the same time as this key.
  35340. * @default
  35341. */
  35342. this.altKey = false;
  35343. /**
  35344. * @property {boolean} ctrlKey - The down state of the CTRL key, if pressed at the same time as this key.
  35345. * @default
  35346. */
  35347. this.ctrlKey = false;
  35348. /**
  35349. * @property {boolean} shiftKey - The down state of the SHIFT key, if pressed at the same time as this key.
  35350. * @default
  35351. */
  35352. this.shiftKey = false;
  35353. /**
  35354. * @property {number} timeDown - The timestamp when the key was last pressed down. This is based on Game.time.now.
  35355. */
  35356. this.timeDown = 0;
  35357. /**
  35358. * If the key is down this value holds the duration of that key press and is constantly updated.
  35359. * If the key is up it holds the duration of the previous down session.
  35360. * @property {number} duration - The number of milliseconds this key has been held down for.
  35361. * @default
  35362. */
  35363. this.duration = 0;
  35364. /**
  35365. * @property {number} timeUp - The timestamp when the key was last released. This is based on Game.time.now.
  35366. * @default
  35367. */
  35368. this.timeUp = -2500;
  35369. /**
  35370. * @property {number} repeats - If a key is held down this holds down the number of times the key has 'repeated'.
  35371. * @default
  35372. */
  35373. this.repeats = 0;
  35374. /**
  35375. * @property {number} keyCode - The keycode of this key.
  35376. */
  35377. this.keyCode = keycode;
  35378. /**
  35379. * @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).
  35380. */
  35381. this.onDown = new Phaser.Signal();
  35382. /**
  35383. * @property {function} onHoldCallback - A callback that is called while this Key is held down. Warning: Depending on refresh rate that could be 60+ times per second.
  35384. */
  35385. this.onHoldCallback = null;
  35386. /**
  35387. * @property {object} onHoldContext - The context under which the onHoldCallback will be called.
  35388. */
  35389. this.onHoldContext = null;
  35390. /**
  35391. * @property {Phaser.Signal} onUp - This Signal is dispatched every time this Key is released. It is only dispatched once (until the key is pressed and released again).
  35392. */
  35393. this.onUp = new Phaser.Signal();
  35394. /**
  35395. * @property {boolean} _justDown - True if the key has just been pressed (NOTE: requires to be reset, see justDown getter)
  35396. * @private
  35397. */
  35398. this._justDown = false;
  35399. /**
  35400. * @property {boolean} _justUp - True if the key has just been pressed (NOTE: requires to be reset, see justDown getter)
  35401. * @private
  35402. */
  35403. this._justUp = false;
  35404. };
  35405. Phaser.Key.prototype = {
  35406. /**
  35407. * Called automatically by Phaser.Keyboard.
  35408. *
  35409. * @method Phaser.Key#update
  35410. * @protected
  35411. */
  35412. update: function () {
  35413. if (!this._enabled) { return; }
  35414. if (this.isDown)
  35415. {
  35416. this.duration = this.game.time.time - this.timeDown;
  35417. this.repeats++;
  35418. if (this.onHoldCallback)
  35419. {
  35420. this.onHoldCallback.call(this.onHoldContext, this);
  35421. }
  35422. }
  35423. },
  35424. /**
  35425. * Called automatically by Phaser.Keyboard.
  35426. *
  35427. * @method Phaser.Key#processKeyDown
  35428. * @param {KeyboardEvent} event - The DOM event that triggered this.
  35429. * @protected
  35430. */
  35431. processKeyDown: function (event) {
  35432. if (!this._enabled) { return; }
  35433. this.event = event;
  35434. // exit if this key down is from auto-repeat
  35435. if (this.isDown)
  35436. {
  35437. return;
  35438. }
  35439. this.altKey = event.altKey;
  35440. this.ctrlKey = event.ctrlKey;
  35441. this.shiftKey = event.shiftKey;
  35442. this.isDown = true;
  35443. this.isUp = false;
  35444. this.timeDown = this.game.time.time;
  35445. this.duration = 0;
  35446. this.repeats = 0;
  35447. // _justDown will remain true until it is read via the justDown Getter
  35448. // this enables the game to poll for past presses, or reset it at the start of a new game state
  35449. this._justDown = true;
  35450. this.onDown.dispatch(this);
  35451. },
  35452. /**
  35453. * Called automatically by Phaser.Keyboard.
  35454. *
  35455. * @method Phaser.Key#processKeyUp
  35456. * @param {KeyboardEvent} event - The DOM event that triggered this.
  35457. * @protected
  35458. */
  35459. processKeyUp: function (event) {
  35460. if (!this._enabled) { return; }
  35461. this.event = event;
  35462. if (this.isUp)
  35463. {
  35464. return;
  35465. }
  35466. this.isDown = false;
  35467. this.isUp = true;
  35468. this.timeUp = this.game.time.time;
  35469. this.duration = this.game.time.time - this.timeDown;
  35470. // _justUp will remain true until it is read via the justUp Getter
  35471. // this enables the game to poll for past presses, or reset it at the start of a new game state
  35472. this._justUp = true;
  35473. this.onUp.dispatch(this);
  35474. },
  35475. /**
  35476. * Resets the state of this Key.
  35477. *
  35478. * This sets isDown to false, isUp to true, resets the time to be the current time, and _enables_ the key.
  35479. * In addition, if it is a "hard reset", it clears clears any callbacks associated with the onDown and onUp events and removes the onHoldCallback.
  35480. *
  35481. * @method Phaser.Key#reset
  35482. * @param {boolean} [hard=true] - A soft reset won't reset any events or callbacks; a hard reset will.
  35483. */
  35484. reset: function (hard) {
  35485. if (hard === undefined) { hard = true; }
  35486. this.isDown = false;
  35487. this.isUp = true;
  35488. this.timeUp = this.game.time.time;
  35489. this.duration = 0;
  35490. this._enabled = true; // .enabled causes reset(false)
  35491. this._justDown = false;
  35492. this._justUp = false;
  35493. if (hard)
  35494. {
  35495. this.onDown.removeAll();
  35496. this.onUp.removeAll();
  35497. this.onHoldCallback = null;
  35498. this.onHoldContext = null;
  35499. }
  35500. },
  35501. /**
  35502. * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down,
  35503. * or was pressed down longer ago than then given duration.
  35504. *
  35505. * @method Phaser.Key#downDuration
  35506. * @param {number} [duration=50] - The duration within which the key is considered as being just pressed. Given in ms.
  35507. * @return {boolean} True if the key was pressed down within the given duration.
  35508. */
  35509. downDuration: function (duration) {
  35510. if (duration === undefined) { duration = 50; }
  35511. return (this.isDown && this.duration < duration);
  35512. },
  35513. /**
  35514. * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down,
  35515. * or was pressed down longer ago than then given duration.
  35516. *
  35517. * @method Phaser.Key#upDuration
  35518. * @param {number} [duration=50] - The duration within which the key is considered as being just released. Given in ms.
  35519. * @return {boolean} True if the key was released within the given duration.
  35520. */
  35521. upDuration: function (duration) {
  35522. if (duration === undefined) { duration = 50; }
  35523. return (!this.isDown && ((this.game.time.time - this.timeUp) < duration));
  35524. }
  35525. };
  35526. /**
  35527. * The justDown value allows you to test if this Key has just been pressed down or not.
  35528. * When you check this value it will return `true` if the Key is down, otherwise `false`.
  35529. * You can only call justDown once per key press. It will only return `true` once, until the Key is released and pressed down again.
  35530. * This allows you to use it in situations where you want to check if this key is down without using a Signal, such as in a core game loop.
  35531. *
  35532. * @property {boolean} justDown
  35533. * @memberof Phaser.Key
  35534. * @default false
  35535. */
  35536. Object.defineProperty(Phaser.Key.prototype, "justDown", {
  35537. get: function () {
  35538. var current = this._justDown;
  35539. this._justDown = false;
  35540. return current;
  35541. }
  35542. });
  35543. /**
  35544. * The justUp value allows you to test if this Key has just been released or not.
  35545. * When you check this value it will return `true` if the Key is up, otherwise `false`.
  35546. * You can only call justUp once per key release. It will only return `true` once, until the Key is pressed down and released again.
  35547. * This allows you to use it in situations where you want to check if this key is up without using a Signal, such as in a core game loop.
  35548. *
  35549. * @property {boolean} justUp
  35550. * @memberof Phaser.Key
  35551. * @default false
  35552. */
  35553. Object.defineProperty(Phaser.Key.prototype, "justUp", {
  35554. get: function () {
  35555. var current = this._justUp;
  35556. this._justUp = false;
  35557. return current;
  35558. }
  35559. });
  35560. /**
  35561. * An enabled key processes its update and dispatches events.
  35562. * A key can be disabled momentarily at runtime instead of deleting it.
  35563. *
  35564. * @property {boolean} enabled
  35565. * @memberof Phaser.Key
  35566. * @default true
  35567. */
  35568. Object.defineProperty(Phaser.Key.prototype, "enabled", {
  35569. get: function () {
  35570. return this._enabled;
  35571. },
  35572. set: function (value) {
  35573. value = !!value;
  35574. if (value !== this._enabled)
  35575. {
  35576. if (!value)
  35577. {
  35578. this.reset(false);
  35579. }
  35580. this._enabled = value;
  35581. }
  35582. }
  35583. });
  35584. Phaser.Key.prototype.constructor = Phaser.Key;
  35585. /**
  35586. * @author Richard Davey <rich@photonstorm.com>
  35587. * @copyright 2016 Photon Storm Ltd.
  35588. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  35589. */
  35590. /**
  35591. * The Keyboard class monitors keyboard input and dispatches keyboard events.
  35592. *
  35593. * _Note_: many keyboards are unable to process certain combinations of keys due to hardware limitations known as ghosting.
  35594. * See http://www.html5gamedevs.com/topic/4876-impossible-to-use-more-than-2-keyboard-input-buttons-at-the-same-time/ for more details.
  35595. *
  35596. * Also please be aware that certain browser extensions can disable or override Phaser keyboard handling.
  35597. * For example the Chrome extension vimium is known to disable Phaser from using the D key. And there are others.
  35598. * So please check your extensions before opening Phaser issues.
  35599. *
  35600. * @class Phaser.Keyboard
  35601. * @constructor
  35602. * @param {Phaser.Game} game - A reference to the currently running game.
  35603. */
  35604. Phaser.Keyboard = function (game) {
  35605. /**
  35606. * @property {Phaser.Game} game - Local reference to game.
  35607. */
  35608. this.game = game;
  35609. /**
  35610. * Keyboard input will only be processed if enabled.
  35611. * @property {boolean} enabled
  35612. * @default
  35613. */
  35614. this.enabled = true;
  35615. /**
  35616. * @property {object} event - The most recent DOM event from keydown or keyup. This is updated every time a new key is pressed or released.
  35617. */
  35618. this.event = null;
  35619. /**
  35620. * @property {object} pressEvent - The most recent DOM event from keypress.
  35621. */
  35622. this.pressEvent = null;
  35623. /**
  35624. * @property {object} callbackContext - The context under which the callbacks are run.
  35625. */
  35626. this.callbackContext = this;
  35627. /**
  35628. * @property {function} onDownCallback - This callback is invoked every time a key is pressed down, including key repeats when a key is held down.
  35629. */
  35630. this.onDownCallback = null;
  35631. /**
  35632. * @property {function} onPressCallback - This callback is invoked every time a DOM onkeypress event is raised, which is only for printable keys.
  35633. */
  35634. this.onPressCallback = null;
  35635. /**
  35636. * @property {function} onUpCallback - This callback is invoked every time a key is released.
  35637. */
  35638. this.onUpCallback = null;
  35639. /**
  35640. * @property {array<Phaser.Key>} _keys - The array the Phaser.Key objects are stored in.
  35641. * @private
  35642. */
  35643. this._keys = [];
  35644. /**
  35645. * @property {array} _capture - The array the key capture values are stored in.
  35646. * @private
  35647. */
  35648. this._capture = [];
  35649. /**
  35650. * @property {function} _onKeyDown
  35651. * @private
  35652. * @default
  35653. */
  35654. this._onKeyDown = null;
  35655. /**
  35656. * @property {function} _onKeyPress
  35657. * @private
  35658. * @default
  35659. */
  35660. this._onKeyPress = null;
  35661. /**
  35662. * @property {function} _onKeyUp
  35663. * @private
  35664. * @default
  35665. */
  35666. this._onKeyUp = null;
  35667. /**
  35668. * @property {number} _i - Internal cache var
  35669. * @private
  35670. */
  35671. this._i = 0;
  35672. /**
  35673. * @property {number} _k - Internal cache var
  35674. * @private
  35675. */
  35676. this._k = 0;
  35677. };
  35678. Phaser.Keyboard.prototype = {
  35679. /**
  35680. * Add callbacks to the Keyboard handler so that each time a key is pressed down or released the callbacks are activated.
  35681. *
  35682. * @method Phaser.Keyboard#addCallbacks
  35683. * @param {object} context - The context under which the callbacks are run.
  35684. * @param {function} [onDown=null] - This callback is invoked every time a key is pressed down.
  35685. * @param {function} [onUp=null] - This callback is invoked every time a key is released.
  35686. * @param {function} [onPress=null] - This callback is invoked every time the onkeypress event is raised.
  35687. */
  35688. addCallbacks: function (context, onDown, onUp, onPress) {
  35689. this.callbackContext = context;
  35690. if (onDown !== undefined && onDown !== null)
  35691. {
  35692. this.onDownCallback = onDown;
  35693. }
  35694. if (onUp !== undefined && onUp !== null)
  35695. {
  35696. this.onUpCallback = onUp;
  35697. }
  35698. if (onPress !== undefined && onPress !== null)
  35699. {
  35700. this.onPressCallback = onPress;
  35701. }
  35702. },
  35703. /**
  35704. * If you need more fine-grained control over a Key you can create a new Phaser.Key object via this method.
  35705. * The Key object can then be polled, have events attached to it, etc.
  35706. *
  35707. * @method Phaser.Keyboard#addKey
  35708. * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key.
  35709. * @return {Phaser.Key} The Key object which you can store locally and reference directly.
  35710. */
  35711. addKey: function (keycode) {
  35712. if (!this._keys[keycode])
  35713. {
  35714. this._keys[keycode] = new Phaser.Key(this.game, keycode);
  35715. this.addKeyCapture(keycode);
  35716. }
  35717. return this._keys[keycode];
  35718. },
  35719. /**
  35720. * A practical way to create an object containing user selected hotkeys.
  35721. *
  35722. * For example,
  35723. *
  35724. * addKeys( { 'up': Phaser.KeyCode.W, 'down': Phaser.KeyCode.S, 'left': Phaser.KeyCode.A, 'right': Phaser.KeyCode.D } );
  35725. *
  35726. * would return an object containing properties (`up`, `down`, `left` and `right`) referring to {@link Phaser.Key} object.
  35727. *
  35728. * @method Phaser.Keyboard#addKeys
  35729. * @param {object} keys - A key mapping object, i.e. `{ 'up': Phaser.KeyCode.W, 'down': Phaser.KeyCode.S }` or `{ 'up': 52, 'down': 53 }`.
  35730. * @return {object} An object containing the properties mapped to {@link Phaser.Key} values.
  35731. */
  35732. addKeys: function (keys) {
  35733. var output = {};
  35734. for (var key in keys)
  35735. {
  35736. output[key] = this.addKey(keys[key]);
  35737. }
  35738. return output;
  35739. },
  35740. /**
  35741. * Removes a Key object from the Keyboard manager.
  35742. *
  35743. * @method Phaser.Keyboard#removeKey
  35744. * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key to remove.
  35745. */
  35746. removeKey: function (keycode) {
  35747. if (this._keys[keycode])
  35748. {
  35749. this._keys[keycode] = null;
  35750. this.removeKeyCapture(keycode);
  35751. }
  35752. },
  35753. /**
  35754. * Creates and returns an object containing 4 hotkeys for Up, Down, Left and Right.
  35755. *
  35756. * @method Phaser.Keyboard#createCursorKeys
  35757. * @return {object} An object containing properties: `up`, `down`, `left` and `right` of {@link Phaser.Key} objects.
  35758. */
  35759. createCursorKeys: function () {
  35760. return this.addKeys({ 'up': Phaser.KeyCode.UP, 'down': Phaser.KeyCode.DOWN, 'left': Phaser.KeyCode.LEFT, 'right': Phaser.KeyCode.RIGHT });
  35761. },
  35762. /**
  35763. * Starts the Keyboard event listeners running (keydown and keyup). They are attached to the window.
  35764. * This is called automatically by Phaser.Input and should not normally be invoked directly.
  35765. *
  35766. * @method Phaser.Keyboard#start
  35767. * @protected
  35768. */
  35769. start: function () {
  35770. if (this.game.device.cocoonJS)
  35771. {
  35772. return;
  35773. }
  35774. if (this._onKeyDown !== null)
  35775. {
  35776. // Avoid setting multiple listeners
  35777. return;
  35778. }
  35779. var _this = this;
  35780. this._onKeyDown = function (event) {
  35781. return _this.processKeyDown(event);
  35782. };
  35783. this._onKeyUp = function (event) {
  35784. return _this.processKeyUp(event);
  35785. };
  35786. this._onKeyPress = function (event) {
  35787. return _this.processKeyPress(event);
  35788. };
  35789. window.addEventListener('keydown', this._onKeyDown, false);
  35790. window.addEventListener('keyup', this._onKeyUp, false);
  35791. window.addEventListener('keypress', this._onKeyPress, false);
  35792. },
  35793. /**
  35794. * Stops the Keyboard event listeners from running (keydown, keyup and keypress). They are removed from the window.
  35795. *
  35796. * @method Phaser.Keyboard#stop
  35797. */
  35798. stop: function () {
  35799. window.removeEventListener('keydown', this._onKeyDown);
  35800. window.removeEventListener('keyup', this._onKeyUp);
  35801. window.removeEventListener('keypress', this._onKeyPress);
  35802. this._onKeyDown = null;
  35803. this._onKeyUp = null;
  35804. this._onKeyPress = null;
  35805. },
  35806. /**
  35807. * Stops the Keyboard event listeners from running (keydown and keyup). They are removed from the window.
  35808. * Also clears all key captures and currently created Key objects.
  35809. *
  35810. * @method Phaser.Keyboard#destroy
  35811. */
  35812. destroy: function () {
  35813. this.stop();
  35814. this.clearCaptures();
  35815. this._keys.length = 0;
  35816. this._i = 0;
  35817. },
  35818. /**
  35819. * By default when a key is pressed Phaser will not stop the event from propagating up to the browser.
  35820. * There are some keys this can be annoying for, like the arrow keys or space bar, which make the browser window scroll.
  35821. *
  35822. * The `addKeyCapture` method enables consuming keyboard event for specific keys so it doesn't bubble up to the the browser
  35823. * and cause the default browser behavior.
  35824. *
  35825. * Pass in either a single keycode or an array/hash of keycodes.
  35826. *
  35827. * @method Phaser.Keyboard#addKeyCapture
  35828. * @param {integer|integer[]|object} keycode - Either a single {@link Phaser.KeyCode keycode} or an array/hash of keycodes such as `[65, 67, 68]`.
  35829. */
  35830. addKeyCapture: function (keycode) {
  35831. if (typeof keycode === 'object')
  35832. {
  35833. for (var key in keycode)
  35834. {
  35835. this._capture[keycode[key]] = true;
  35836. }
  35837. }
  35838. else
  35839. {
  35840. this._capture[keycode] = true;
  35841. }
  35842. },
  35843. /**
  35844. * Removes an existing key capture.
  35845. *
  35846. * @method Phaser.Keyboard#removeKeyCapture
  35847. * @param {integer} keycode - The {@link Phaser.KeyCode keycode} to remove capturing of.
  35848. */
  35849. removeKeyCapture: function (keycode) {
  35850. delete this._capture[keycode];
  35851. },
  35852. /**
  35853. * Clear all set key captures.
  35854. *
  35855. * @method Phaser.Keyboard#clearCaptures
  35856. */
  35857. clearCaptures: function () {
  35858. this._capture = {};
  35859. },
  35860. /**
  35861. * Updates all currently defined keys.
  35862. *
  35863. * @method Phaser.Keyboard#update
  35864. */
  35865. update: function () {
  35866. this._i = this._keys.length;
  35867. while (this._i--)
  35868. {
  35869. if (this._keys[this._i])
  35870. {
  35871. this._keys[this._i].update();
  35872. }
  35873. }
  35874. },
  35875. /**
  35876. * Process the keydown event.
  35877. *
  35878. * @method Phaser.Keyboard#processKeyDown
  35879. * @param {KeyboardEvent} event
  35880. * @protected
  35881. */
  35882. processKeyDown: function (event) {
  35883. this.event = event;
  35884. if (!this.game.input.enabled || !this.enabled)
  35885. {
  35886. return;
  35887. }
  35888. // The event is being captured but another hotkey may need it
  35889. if (this._capture[event.keyCode])
  35890. {
  35891. event.preventDefault();
  35892. }
  35893. if (!this._keys[event.keyCode])
  35894. {
  35895. this._keys[event.keyCode] = new Phaser.Key(this.game, event.keyCode);
  35896. }
  35897. this._keys[event.keyCode].processKeyDown(event);
  35898. this._k = event.keyCode;
  35899. if (this.onDownCallback)
  35900. {
  35901. this.onDownCallback.call(this.callbackContext, event);
  35902. }
  35903. },
  35904. /**
  35905. * Process the keypress event.
  35906. *
  35907. * @method Phaser.Keyboard#processKeyPress
  35908. * @param {KeyboardEvent} event
  35909. * @protected
  35910. */
  35911. processKeyPress: function (event) {
  35912. this.pressEvent = event;
  35913. if (!this.game.input.enabled || !this.enabled)
  35914. {
  35915. return;
  35916. }
  35917. if (this.onPressCallback)
  35918. {
  35919. this.onPressCallback.call(this.callbackContext, String.fromCharCode(event.charCode), event);
  35920. }
  35921. },
  35922. /**
  35923. * Process the keyup event.
  35924. *
  35925. * @method Phaser.Keyboard#processKeyUp
  35926. * @param {KeyboardEvent} event
  35927. * @protected
  35928. */
  35929. processKeyUp: function (event) {
  35930. this.event = event;
  35931. if (!this.game.input.enabled || !this.enabled)
  35932. {
  35933. return;
  35934. }
  35935. if (this._capture[event.keyCode])
  35936. {
  35937. event.preventDefault();
  35938. }
  35939. if (!this._keys[event.keyCode])
  35940. {
  35941. this._keys[event.keyCode] = new Phaser.Key(this.game, event.keyCode);
  35942. }
  35943. this._keys[event.keyCode].processKeyUp(event);
  35944. if (this.onUpCallback)
  35945. {
  35946. this.onUpCallback.call(this.callbackContext, event);
  35947. }
  35948. },
  35949. /**
  35950. * Resets all Keys.
  35951. *
  35952. * @method Phaser.Keyboard#reset
  35953. * @param {boolean} [hard=true] - A soft reset won't reset any events or callbacks that are bound to the Keys. A hard reset will.
  35954. */
  35955. reset: function (hard) {
  35956. if (hard === undefined) { hard = true; }
  35957. this.event = null;
  35958. var i = this._keys.length;
  35959. while (i--)
  35960. {
  35961. if (this._keys[i])
  35962. {
  35963. this._keys[i].reset(hard);
  35964. }
  35965. }
  35966. },
  35967. /**
  35968. * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down,
  35969. * or was pressed down longer ago than then given duration.
  35970. *
  35971. * @method Phaser.Keyboard#downDuration
  35972. * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key to check: i.e. Phaser.KeyCode.UP or Phaser.KeyCode.SPACEBAR.
  35973. * @param {number} [duration=50] - The duration within which the key is considered as being just pressed. Given in ms.
  35974. * @return {boolean} True if the key was pressed down within the given duration, false if not or null if the Key wasn't found.
  35975. */
  35976. downDuration: function (keycode, duration) {
  35977. if (this._keys[keycode])
  35978. {
  35979. return this._keys[keycode].downDuration(duration);
  35980. }
  35981. else
  35982. {
  35983. return null;
  35984. }
  35985. },
  35986. /**
  35987. * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down,
  35988. * or was pressed down longer ago than then given duration.
  35989. *
  35990. * @method Phaser.Keyboard#upDuration
  35991. * @param {Phaser.KeyCode|integer} keycode - The keycode of the key to check, i.e. Phaser.KeyCode.UP or Phaser.KeyCode.SPACEBAR.
  35992. * @param {number} [duration=50] - The duration within which the key is considered as being just released. Given in ms.
  35993. * @return {boolean} True if the key was released within the given duration, false if not or null if the Key wasn't found.
  35994. */
  35995. upDuration: function (keycode, duration) {
  35996. if (this._keys[keycode])
  35997. {
  35998. return this._keys[keycode].upDuration(duration);
  35999. }
  36000. else
  36001. {
  36002. return null;
  36003. }
  36004. },
  36005. /**
  36006. * Returns true of the key is currently pressed down. Note that it can only detect key presses on the web browser.
  36007. *
  36008. * @method Phaser.Keyboard#isDown
  36009. * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key to check: i.e. Phaser.KeyCode.UP or Phaser.KeyCode.SPACEBAR.
  36010. * @return {boolean} True if the key is currently down, false if not or null if the Key wasn't found.
  36011. */
  36012. isDown: function (keycode) {
  36013. if (this._keys[keycode])
  36014. {
  36015. return this._keys[keycode].isDown;
  36016. }
  36017. else
  36018. {
  36019. return null;
  36020. }
  36021. }
  36022. };
  36023. /**
  36024. * Returns the string value of the most recently pressed key.
  36025. * @name Phaser.Keyboard#lastChar
  36026. * @property {string} lastChar - The string value of the most recently pressed key.
  36027. * @readonly
  36028. */
  36029. Object.defineProperty(Phaser.Keyboard.prototype, "lastChar", {
  36030. get: function () {
  36031. if (this.event.charCode === 32)
  36032. {
  36033. return '';
  36034. }
  36035. else
  36036. {
  36037. return String.fromCharCode(this.pressEvent.charCode);
  36038. }
  36039. }
  36040. });
  36041. /**
  36042. * Returns the most recently pressed Key. This is a Phaser.Key object and it changes every time a key is pressed.
  36043. * @name Phaser.Keyboard#lastKey
  36044. * @property {Phaser.Key} lastKey - The most recently pressed Key.
  36045. * @readonly
  36046. */
  36047. Object.defineProperty(Phaser.Keyboard.prototype, "lastKey", {
  36048. get: function () {
  36049. return this._keys[this._k];
  36050. }
  36051. });
  36052. Phaser.Keyboard.prototype.constructor = Phaser.Keyboard;
  36053. /**
  36054. * A key code represents a physical key on a keyboard.
  36055. *
  36056. * The KeyCode class contains commonly supported keyboard key codes which can be used
  36057. * as keycode`-parameters in several {@link Phaser.Keyboard} and {@link Phaser.Key} methods.
  36058. *
  36059. * _Note_: These values should only be used indirectly, eg. as `Phaser.KeyCode.KEY`.
  36060. * Future versions may replace the actual values, such that they remain compatible with `keycode`-parameters.
  36061. * The current implementation maps to the {@link https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode KeyboardEvent.keyCode} property.
  36062. *
  36063. * _Note_: Use `Phaser.KeyCode.KEY` instead of `Phaser.Keyboard.KEY` to refer to a key code;
  36064. * the latter approach is supported for compatibility.
  36065. *
  36066. * @namespace
  36067. */
  36068. Phaser.KeyCode = {
  36069. /** @static */
  36070. A: "A".charCodeAt(0),
  36071. /** @static */
  36072. B: "B".charCodeAt(0),
  36073. /** @static */
  36074. C: "C".charCodeAt(0),
  36075. /** @static */
  36076. D: "D".charCodeAt(0),
  36077. /** @static */
  36078. E: "E".charCodeAt(0),
  36079. /** @static */
  36080. F: "F".charCodeAt(0),
  36081. /** @static */
  36082. G: "G".charCodeAt(0),
  36083. /** @static */
  36084. H: "H".charCodeAt(0),
  36085. /** @static */
  36086. I: "I".charCodeAt(0),
  36087. /** @static */
  36088. J: "J".charCodeAt(0),
  36089. /** @static */
  36090. K: "K".charCodeAt(0),
  36091. /** @static */
  36092. L: "L".charCodeAt(0),
  36093. /** @static */
  36094. M: "M".charCodeAt(0),
  36095. /** @static */
  36096. N: "N".charCodeAt(0),
  36097. /** @static */
  36098. O: "O".charCodeAt(0),
  36099. /** @static */
  36100. P: "P".charCodeAt(0),
  36101. /** @static */
  36102. Q: "Q".charCodeAt(0),
  36103. /** @static */
  36104. R: "R".charCodeAt(0),
  36105. /** @static */
  36106. S: "S".charCodeAt(0),
  36107. /** @static */
  36108. T: "T".charCodeAt(0),
  36109. /** @static */
  36110. U: "U".charCodeAt(0),
  36111. /** @static */
  36112. V: "V".charCodeAt(0),
  36113. /** @static */
  36114. W: "W".charCodeAt(0),
  36115. /** @static */
  36116. X: "X".charCodeAt(0),
  36117. /** @static */
  36118. Y: "Y".charCodeAt(0),
  36119. /** @static */
  36120. Z: "Z".charCodeAt(0),
  36121. /** @static */
  36122. ZERO: "0".charCodeAt(0),
  36123. /** @static */
  36124. ONE: "1".charCodeAt(0),
  36125. /** @static */
  36126. TWO: "2".charCodeAt(0),
  36127. /** @static */
  36128. THREE: "3".charCodeAt(0),
  36129. /** @static */
  36130. FOUR: "4".charCodeAt(0),
  36131. /** @static */
  36132. FIVE: "5".charCodeAt(0),
  36133. /** @static */
  36134. SIX: "6".charCodeAt(0),
  36135. /** @static */
  36136. SEVEN: "7".charCodeAt(0),
  36137. /** @static */
  36138. EIGHT: "8".charCodeAt(0),
  36139. /** @static */
  36140. NINE: "9".charCodeAt(0),
  36141. /** @static */
  36142. NUMPAD_0: 96,
  36143. /** @static */
  36144. NUMPAD_1: 97,
  36145. /** @static */
  36146. NUMPAD_2: 98,
  36147. /** @static */
  36148. NUMPAD_3: 99,
  36149. /** @static */
  36150. NUMPAD_4: 100,
  36151. /** @static */
  36152. NUMPAD_5: 101,
  36153. /** @static */
  36154. NUMPAD_6: 102,
  36155. /** @static */
  36156. NUMPAD_7: 103,
  36157. /** @static */
  36158. NUMPAD_8: 104,
  36159. /** @static */
  36160. NUMPAD_9: 105,
  36161. /** @static */
  36162. NUMPAD_MULTIPLY: 106,
  36163. /** @static */
  36164. NUMPAD_ADD: 107,
  36165. /** @static */
  36166. NUMPAD_ENTER: 108,
  36167. /** @static */
  36168. NUMPAD_SUBTRACT: 109,
  36169. /** @static */
  36170. NUMPAD_DECIMAL: 110,
  36171. /** @static */
  36172. NUMPAD_DIVIDE: 111,
  36173. /** @static */
  36174. F1: 112,
  36175. /** @static */
  36176. F2: 113,
  36177. /** @static */
  36178. F3: 114,
  36179. /** @static */
  36180. F4: 115,
  36181. /** @static */
  36182. F5: 116,
  36183. /** @static */
  36184. F6: 117,
  36185. /** @static */
  36186. F7: 118,
  36187. /** @static */
  36188. F8: 119,
  36189. /** @static */
  36190. F9: 120,
  36191. /** @static */
  36192. F10: 121,
  36193. /** @static */
  36194. F11: 122,
  36195. /** @static */
  36196. F12: 123,
  36197. /** @static */
  36198. F13: 124,
  36199. /** @static */
  36200. F14: 125,
  36201. /** @static */
  36202. F15: 126,
  36203. /** @static */
  36204. COLON: 186,
  36205. /** @static */
  36206. EQUALS: 187,
  36207. /** @static */
  36208. COMMA: 188,
  36209. /** @static */
  36210. UNDERSCORE: 189,
  36211. /** @static */
  36212. PERIOD: 190,
  36213. /** @static */
  36214. QUESTION_MARK: 191,
  36215. /** @static */
  36216. TILDE: 192,
  36217. /** @static */
  36218. OPEN_BRACKET: 219,
  36219. /** @static */
  36220. BACKWARD_SLASH: 220,
  36221. /** @static */
  36222. CLOSED_BRACKET: 221,
  36223. /** @static */
  36224. QUOTES: 222,
  36225. /** @static */
  36226. BACKSPACE: 8,
  36227. /** @static */
  36228. TAB: 9,
  36229. /** @static */
  36230. CLEAR: 12,
  36231. /** @static */
  36232. ENTER: 13,
  36233. /** @static */
  36234. SHIFT: 16,
  36235. /** @static */
  36236. CONTROL: 17,
  36237. /** @static */
  36238. ALT: 18,
  36239. /** @static */
  36240. CAPS_LOCK: 20,
  36241. /** @static */
  36242. ESC: 27,
  36243. /** @static */
  36244. SPACEBAR: 32,
  36245. /** @static */
  36246. PAGE_UP: 33,
  36247. /** @static */
  36248. PAGE_DOWN: 34,
  36249. /** @static */
  36250. END: 35,
  36251. /** @static */
  36252. HOME: 36,
  36253. /** @static */
  36254. LEFT: 37,
  36255. /** @static */
  36256. UP: 38,
  36257. /** @static */
  36258. RIGHT: 39,
  36259. /** @static */
  36260. DOWN: 40,
  36261. /** @static */
  36262. PLUS: 43,
  36263. /** @static */
  36264. MINUS: 44,
  36265. /** @static */
  36266. INSERT: 45,
  36267. /** @static */
  36268. DELETE: 46,
  36269. /** @static */
  36270. HELP: 47,
  36271. /** @static */
  36272. NUM_LOCK: 144
  36273. };
  36274. // Duplicate Phaser.KeyCode values in Phaser.Keyboard for compatibility
  36275. for (var key in Phaser.KeyCode) {
  36276. if (Phaser.KeyCode.hasOwnProperty(key) && !key.match(/[a-z]/)) {
  36277. Phaser.Keyboard[key] = Phaser.KeyCode[key];
  36278. }
  36279. }
  36280. /**
  36281. * @author Richard Davey <rich@photonstorm.com>
  36282. * @copyright 2016 Photon Storm Ltd.
  36283. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  36284. */
  36285. Phaser.Component = function () {};
  36286. /**
  36287. * @author Richard Davey <rich@photonstorm.com>
  36288. * @copyright 2016 Photon Storm Ltd.
  36289. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  36290. */
  36291. /**
  36292. * The Angle Component provides access to an `angle` property; the rotation of a Game Object in degrees.
  36293. *
  36294. * @class
  36295. */
  36296. Phaser.Component.Angle = function () {};
  36297. Phaser.Component.Angle.prototype = {
  36298. /**
  36299. * The angle property is the rotation of the Game Object in *degrees* from its original orientation.
  36300. *
  36301. * Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation.
  36302. *
  36303. * Values outside this range are added to or subtracted from 360 to obtain a value within the range.
  36304. * For example, the statement player.angle = 450 is the same as player.angle = 90.
  36305. *
  36306. * If you wish to work in radians instead of degrees you can use the property `rotation` instead.
  36307. * Working in radians is slightly faster as it doesn't have to perform any calculations.
  36308. *
  36309. * @property {number} angle
  36310. */
  36311. angle: {
  36312. get: function() {
  36313. return Phaser.Math.wrapAngle(Phaser.Math.radToDeg(this.rotation));
  36314. },
  36315. set: function(value) {
  36316. this.rotation = Phaser.Math.degToRad(Phaser.Math.wrapAngle(value));
  36317. }
  36318. }
  36319. };
  36320. /**
  36321. * @author Richard Davey <rich@photonstorm.com>
  36322. * @copyright 2016 Photon Storm Ltd.
  36323. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  36324. */
  36325. /**
  36326. * The Animation Component provides a `play` method, which is a proxy to the `AnimationManager.play` method.
  36327. *
  36328. * @class
  36329. */
  36330. Phaser.Component.Animation = function () {};
  36331. Phaser.Component.Animation.prototype = {
  36332. /**
  36333. * Plays an Animation.
  36334. *
  36335. * The animation should have previously been created via `animations.add`.
  36336. *
  36337. * If the animation is already playing calling this again won't do anything.
  36338. * If you need to reset an already running animation do so directly on the Animation object itself or via `AnimationManager.stop`.
  36339. *
  36340. * @method
  36341. * @param {string} name - The name of the animation to be played, e.g. "fire", "walk", "jump". Must have been previously created via 'AnimationManager.add'.
  36342. * @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.
  36343. * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used.
  36344. * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed.
  36345. * @return {Phaser.Animation} A reference to playing Animation.
  36346. */
  36347. play: function (name, frameRate, loop, killOnComplete) {
  36348. if (this.animations)
  36349. {
  36350. return this.animations.play(name, frameRate, loop, killOnComplete);
  36351. }
  36352. }
  36353. };
  36354. /**
  36355. * @author Richard Davey <rich@photonstorm.com>
  36356. * @copyright 2016 Photon Storm Ltd.
  36357. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  36358. */
  36359. /**
  36360. * The AutoCull Component is responsible for providing methods that check if a Game Object is within the bounds of the World Camera.
  36361. * It is used by the InWorld component.
  36362. *
  36363. * @class
  36364. */
  36365. Phaser.Component.AutoCull = function () {};
  36366. Phaser.Component.AutoCull.prototype = {
  36367. /**
  36368. * A Game Object with `autoCull` set to true will check its bounds against the World Camera every frame.
  36369. * If it is not intersecting the Camera bounds at any point then it has its `renderable` property set to `false`.
  36370. * This keeps the Game Object alive and still processing updates, but forces it to skip the render step entirely.
  36371. *
  36372. * This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required,
  36373. * or you have tested performance and find it acceptable.
  36374. *
  36375. * @property {boolean} autoCull
  36376. * @default
  36377. */
  36378. autoCull: false,
  36379. /**
  36380. * Checks if the Game Objects bounds intersect with the Game Camera bounds.
  36381. * Returns `true` if they do, otherwise `false` if fully outside of the Cameras bounds.
  36382. *
  36383. * @property {boolean} inCamera
  36384. * @readonly
  36385. */
  36386. inCamera: {
  36387. get: function() {
  36388. if (!this.autoCull && !this.checkWorldBounds)
  36389. {
  36390. this._bounds.copyFrom(this.getBounds());
  36391. this._bounds.x += this.game.camera.view.x;
  36392. this._bounds.y += this.game.camera.view.y;
  36393. }
  36394. return this.game.world.camera.view.intersects(this._bounds);
  36395. }
  36396. }
  36397. };
  36398. /**
  36399. * @author Richard Davey <rich@photonstorm.com>
  36400. * @copyright 2016 Photon Storm Ltd.
  36401. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  36402. */
  36403. /**
  36404. * The Bounds component contains properties related to the bounds of the Game Object.
  36405. *
  36406. * @class
  36407. */
  36408. Phaser.Component.Bounds = function () {};
  36409. Phaser.Component.Bounds.prototype = {
  36410. /**
  36411. * The amount the Game Object is visually offset from its x coordinate.
  36412. * This is the same as `width * anchor.x`.
  36413. * It will only be > 0 if anchor.x is not equal to zero.
  36414. *
  36415. * @property {number} offsetX
  36416. * @readOnly
  36417. */
  36418. offsetX: {
  36419. get: function () {
  36420. return this.anchor.x * this.width;
  36421. }
  36422. },
  36423. /**
  36424. * The amount the Game Object is visually offset from its y coordinate.
  36425. * This is the same as `height * anchor.y`.
  36426. * It will only be > 0 if anchor.y is not equal to zero.
  36427. *
  36428. * @property {number} offsetY
  36429. * @readOnly
  36430. */
  36431. offsetY: {
  36432. get: function () {
  36433. return this.anchor.y * this.height;
  36434. }
  36435. },
  36436. /**
  36437. * The left coordinate of the Game Object.
  36438. * This is the same as `x - offsetX`.
  36439. *
  36440. * @property {number} left
  36441. * @readOnly
  36442. */
  36443. left: {
  36444. get: function () {
  36445. return this.x - this.offsetX;
  36446. }
  36447. },
  36448. /**
  36449. * The right coordinate of the Game Object.
  36450. * This is the same as `x + width - offsetX`.
  36451. *
  36452. * @property {number} right
  36453. * @readOnly
  36454. */
  36455. right: {
  36456. get: function () {
  36457. return (this.x + this.width) - this.offsetX;
  36458. }
  36459. },
  36460. /**
  36461. * The y coordinate of the Game Object.
  36462. * This is the same as `y - offsetY`.
  36463. *
  36464. * @property {number} top
  36465. * @readOnly
  36466. */
  36467. top: {
  36468. get: function () {
  36469. return this.y - this.offsetY;
  36470. }
  36471. },
  36472. /**
  36473. * The sum of the y and height properties.
  36474. * This is the same as `y + height - offsetY`.
  36475. *
  36476. * @property {number} bottom
  36477. * @readOnly
  36478. */
  36479. bottom: {
  36480. get: function () {
  36481. return (this.y + this.height) - this.offsetY;
  36482. }
  36483. }
  36484. };
  36485. /**
  36486. * @author Richard Davey <rich@photonstorm.com>
  36487. * @copyright 2016 Photon Storm Ltd.
  36488. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  36489. */
  36490. /**
  36491. * The BringToTop Component features quick access to Group sorting related methods.
  36492. *
  36493. * @class
  36494. */
  36495. Phaser.Component.BringToTop = function () {};
  36496. /**
  36497. * Brings this Game Object to the top of its parents display list.
  36498. * Visually this means it will render over the top of any old child in the same Group.
  36499. *
  36500. * If this Game Object hasn't been added to a custom Group then this method will bring it to the top of the Game World,
  36501. * because the World is the root Group from which all Game Objects descend.
  36502. *
  36503. * @method
  36504. * @return {PIXI.DisplayObject} This instance.
  36505. */
  36506. Phaser.Component.BringToTop.prototype.bringToTop = function() {
  36507. if (this.parent)
  36508. {
  36509. this.parent.bringToTop(this);
  36510. }
  36511. return this;
  36512. };
  36513. /**
  36514. * Sends this Game Object to the bottom of its parents display list.
  36515. * Visually this means it will render below all other children in the same Group.
  36516. *
  36517. * If this Game Object hasn't been added to a custom Group then this method will send it to the bottom of the Game World,
  36518. * because the World is the root Group from which all Game Objects descend.
  36519. *
  36520. * @method
  36521. * @return {PIXI.DisplayObject} This instance.
  36522. */
  36523. Phaser.Component.BringToTop.prototype.sendToBack = function() {
  36524. if (this.parent)
  36525. {
  36526. this.parent.sendToBack(this);
  36527. }
  36528. return this;
  36529. };
  36530. /**
  36531. * Moves this Game Object up one place in its parents display list.
  36532. * This call has no effect if the Game Object is already at the top of the display list.
  36533. *
  36534. * If this Game Object hasn't been added to a custom Group then this method will move it one object up within the Game World,
  36535. * because the World is the root Group from which all Game Objects descend.
  36536. *
  36537. * @method
  36538. * @return {PIXI.DisplayObject} This instance.
  36539. */
  36540. Phaser.Component.BringToTop.prototype.moveUp = function () {
  36541. if (this.parent)
  36542. {
  36543. this.parent.moveUp(this);
  36544. }
  36545. return this;
  36546. };
  36547. /**
  36548. * Moves this Game Object down one place in its parents display list.
  36549. * This call has no effect if the Game Object is already at the bottom of the display list.
  36550. *
  36551. * If this Game Object hasn't been added to a custom Group then this method will move it one object down within the Game World,
  36552. * because the World is the root Group from which all Game Objects descend.
  36553. *
  36554. * @method
  36555. * @return {PIXI.DisplayObject} This instance.
  36556. */
  36557. Phaser.Component.BringToTop.prototype.moveDown = function () {
  36558. if (this.parent)
  36559. {
  36560. this.parent.moveDown(this);
  36561. }
  36562. return this;
  36563. };
  36564. /**
  36565. * @author Richard Davey <rich@photonstorm.com>
  36566. * @copyright 2016 Photon Storm Ltd.
  36567. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  36568. */
  36569. /**
  36570. * Core Component Features.
  36571. *
  36572. * @class
  36573. */
  36574. Phaser.Component.Core = function () {};
  36575. /**
  36576. * Installs / registers mixin components.
  36577. *
  36578. * The `this` context should be that of the applicable object instance or prototype.
  36579. *
  36580. * @method
  36581. * @protected
  36582. */
  36583. Phaser.Component.Core.install = function (components) {
  36584. // Always install 'Core' first
  36585. Phaser.Utils.mixinPrototype(this, Phaser.Component.Core.prototype);
  36586. this.components = {};
  36587. for (var i = 0; i < components.length; i++)
  36588. {
  36589. var id = components[i];
  36590. var replace = false;
  36591. if (id === 'Destroy')
  36592. {
  36593. replace = true;
  36594. }
  36595. Phaser.Utils.mixinPrototype(this, Phaser.Component[id].prototype, replace);
  36596. this.components[id] = true;
  36597. }
  36598. };
  36599. /**
  36600. * Initializes the mixin components.
  36601. *
  36602. * The `this` context should be an instance of the component mixin target.
  36603. *
  36604. * @method
  36605. * @protected
  36606. */
  36607. Phaser.Component.Core.init = function (game, x, y, key, frame) {
  36608. this.game = game;
  36609. this.key = key;
  36610. this.position.set(x, y);
  36611. this.world = new Phaser.Point(x, y);
  36612. this.previousPosition = new Phaser.Point(x, y);
  36613. this.events = new Phaser.Events(this);
  36614. this._bounds = new Phaser.Rectangle();
  36615. if (this.components.PhysicsBody)
  36616. {
  36617. // Enable-body checks for hasOwnProperty; makes sure to lift property from prototype.
  36618. this.body = this.body;
  36619. }
  36620. if (this.components.Animation)
  36621. {
  36622. this.animations = new Phaser.AnimationManager(this);
  36623. }
  36624. if (this.components.LoadTexture && key !== null)
  36625. {
  36626. this.loadTexture(key, frame);
  36627. }
  36628. if (this.components.FixedToCamera)
  36629. {
  36630. this.cameraOffset = new Phaser.Point(x, y);
  36631. }
  36632. };
  36633. Phaser.Component.Core.preUpdate = function () {
  36634. if (this.pendingDestroy)
  36635. {
  36636. this.destroy();
  36637. return;
  36638. }
  36639. this.previousPosition.set(this.world.x, this.world.y);
  36640. this.previousRotation = this.rotation;
  36641. if (!this.exists || !this.parent.exists)
  36642. {
  36643. this.renderOrderID = -1;
  36644. return false;
  36645. }
  36646. this.world.setTo(this.game.camera.x + this.worldTransform.tx, this.game.camera.y + this.worldTransform.ty);
  36647. if (this.visible)
  36648. {
  36649. this.renderOrderID = this.game.stage.currentRenderOrderID++;
  36650. }
  36651. if (this.texture)
  36652. {
  36653. this.texture.requiresReTint = false;
  36654. }
  36655. if (this.animations)
  36656. {
  36657. this.animations.update();
  36658. }
  36659. if (this.body)
  36660. {
  36661. this.body.preUpdate();
  36662. }
  36663. for (var i = 0; i < this.children.length; i++)
  36664. {
  36665. this.children[i].preUpdate();
  36666. }
  36667. return true;
  36668. };
  36669. Phaser.Component.Core.prototype = {
  36670. /**
  36671. * A reference to the currently running Game.
  36672. * @property {Phaser.Game} game
  36673. */
  36674. game: null,
  36675. /**
  36676. * A user defined name given to this Game Object.
  36677. * This value isn't ever used internally by Phaser, it is meant as a game level property.
  36678. * @property {string} name
  36679. * @default
  36680. */
  36681. name: '',
  36682. /**
  36683. * The components this Game Object has installed.
  36684. * @property {object} components
  36685. * @protected
  36686. */
  36687. components: {},
  36688. /**
  36689. * The z depth of this Game Object within its parent Group.
  36690. * No two objects in a Group can have the same z value.
  36691. * This value is adjusted automatically whenever the Group hierarchy changes.
  36692. * If you wish to re-order the layering of a Game Object then see methods like Group.moveUp or Group.bringToTop.
  36693. * @property {number} z
  36694. * @readOnly
  36695. */
  36696. z: 0,
  36697. /**
  36698. * All Phaser Game Objects have an Events class which contains all of the events that are dispatched when certain things happen to this
  36699. * Game Object, or any of its components.
  36700. * @see Phaser.Events
  36701. * @property {Phaser.Events} events
  36702. */
  36703. events: undefined,
  36704. /**
  36705. * If the Game Object is enabled for animation (such as a Phaser.Sprite) this is a reference to its AnimationManager instance.
  36706. * Through it you can create, play, pause and stop animations.
  36707. * @see Phaser.AnimationManager
  36708. * @property {Phaser.AnimationManager} animations
  36709. */
  36710. animations: undefined,
  36711. /**
  36712. * The key of the image or texture used by this Game Object during rendering.
  36713. * If it is a string it's the string used to retrieve the texture from the Phaser Image Cache.
  36714. * It can also be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture.
  36715. * If a Game Object is created without a key it is automatically assigned the key `__default` which is a 32x32 transparent PNG stored within the Cache.
  36716. * If a Game Object is given a key which doesn't exist in the Image Cache it is re-assigned the key `__missing` which is a 32x32 PNG of a green box with a line through it.
  36717. * @property {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} key
  36718. */
  36719. key: '',
  36720. /**
  36721. * The world coordinates of this Game Object in pixels.
  36722. * Depending on where in the display list this Game Object is placed this value can differ from `position`,
  36723. * which contains the x/y coordinates relative to the Game Objects parent.
  36724. * @property {Phaser.Point} world
  36725. */
  36726. world: null,
  36727. /**
  36728. * A debug flag designed for use with `Game.enableStep`.
  36729. * @property {boolean} debug
  36730. * @default
  36731. */
  36732. debug: false,
  36733. /**
  36734. * The position the Game Object was located in the previous frame.
  36735. * @property {Phaser.Point} previousPosition
  36736. * @readOnly
  36737. */
  36738. previousPosition: null,
  36739. /**
  36740. * The rotation the Game Object was in set to in the previous frame. Value is in radians.
  36741. * @property {number} previousRotation
  36742. * @readOnly
  36743. */
  36744. previousRotation: 0,
  36745. /**
  36746. * The render order ID is used internally by the renderer and Input Manager and should not be modified.
  36747. * This property is mostly used internally by the renderers, but is exposed for the use of plugins.
  36748. * @property {number} renderOrderID
  36749. * @readOnly
  36750. */
  36751. renderOrderID: 0,
  36752. /**
  36753. * A Game Object is considered `fresh` if it has just been created or reset and is yet to receive a renderer transform update.
  36754. * This property is mostly used internally by the physics systems, but is exposed for the use of plugins.
  36755. * @property {boolean} fresh
  36756. * @readOnly
  36757. */
  36758. fresh: true,
  36759. /**
  36760. * A Game Object is that is pendingDestroy is flagged to have its destroy method called on the next logic update.
  36761. * You can set it directly to allow you to flag an object to be destroyed on its next update.
  36762. *
  36763. * This is extremely useful if you wish to destroy an object from within one of its own callbacks
  36764. * such as with Buttons or other Input events.
  36765. *
  36766. * @property {boolean} pendingDestroy
  36767. */
  36768. pendingDestroy: false,
  36769. /**
  36770. * @property {Phaser.Rectangle} _bounds - Internal cache var.
  36771. * @private
  36772. */
  36773. _bounds: null,
  36774. /**
  36775. * @property {boolean} _exists - Internal cache var.
  36776. * @private
  36777. */
  36778. _exists: true,
  36779. /**
  36780. * Controls if this Game Object is processed by the core game loop.
  36781. * If this Game Object has a physics body it also controls if its physics body is updated or not.
  36782. * When `exists` is set to `false` it will remove its physics body from the physics world if it has one.
  36783. * It also toggles the `visible` property to false as well.
  36784. *
  36785. * Setting `exists` to true will add its physics body back in to the physics world, if it has one.
  36786. * It will also set the `visible` property to `true`.
  36787. *
  36788. * @property {boolean} exists
  36789. */
  36790. exists: {
  36791. get: function () {
  36792. return this._exists;
  36793. },
  36794. set: function (value) {
  36795. if (value)
  36796. {
  36797. this._exists = true;
  36798. if (this.body && this.body.type === Phaser.Physics.P2JS)
  36799. {
  36800. this.body.addToWorld();
  36801. }
  36802. this.visible = true;
  36803. }
  36804. else
  36805. {
  36806. this._exists = false;
  36807. if (this.body && this.body.type === Phaser.Physics.P2JS)
  36808. {
  36809. this.body.removeFromWorld();
  36810. }
  36811. this.visible = false;
  36812. }
  36813. }
  36814. },
  36815. /**
  36816. * Override this method in your own custom objects to handle any update requirements.
  36817. * It is called immediately after `preUpdate` and before `postUpdate`.
  36818. * Remember if this Game Object has any children you should call update on those too.
  36819. *
  36820. * @method
  36821. */
  36822. update: function() {
  36823. },
  36824. /**
  36825. * Internal method called by the World postUpdate cycle.
  36826. *
  36827. * @method
  36828. * @protected
  36829. */
  36830. postUpdate: function() {
  36831. if (this.customRender)
  36832. {
  36833. this.key.render();
  36834. }
  36835. if (this.components.PhysicsBody)
  36836. {
  36837. Phaser.Component.PhysicsBody.postUpdate.call(this);
  36838. }
  36839. if (this.components.FixedToCamera)
  36840. {
  36841. Phaser.Component.FixedToCamera.postUpdate.call(this);
  36842. }
  36843. for (var i = 0; i < this.children.length; i++)
  36844. {
  36845. this.children[i].postUpdate();
  36846. }
  36847. }
  36848. };
  36849. /**
  36850. * @author Richard Davey <rich@photonstorm.com>
  36851. * @copyright 2016 Photon Storm Ltd.
  36852. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  36853. */
  36854. /**
  36855. * The Crop component provides the ability to crop a texture based Game Object to a defined rectangle,
  36856. * which can be updated in real-time.
  36857. *
  36858. * @class
  36859. */
  36860. Phaser.Component.Crop = function () {};
  36861. Phaser.Component.Crop.prototype = {
  36862. /**
  36863. * The Rectangle used to crop the texture this Game Object uses.
  36864. * Set this property via `crop`.
  36865. * If you modify this property directly you must call `updateCrop` in order to have the change take effect.
  36866. * @property {Phaser.Rectangle} cropRect
  36867. * @default
  36868. */
  36869. cropRect: null,
  36870. /**
  36871. * @property {Phaser.Rectangle} _crop - Internal cache var.
  36872. * @private
  36873. */
  36874. _crop: null,
  36875. /**
  36876. * Crop allows you to crop the texture being used to display this Game Object.
  36877. * Setting a crop rectangle modifies the core texture frame. The Game Object width and height properties will be adjusted accordingly.
  36878. *
  36879. * Cropping takes place from the top-left and can be modified in real-time either by providing an updated rectangle object to this method,
  36880. * or by modifying `cropRect` property directly and then calling `updateCrop`.
  36881. *
  36882. * The rectangle object given to this method can be either a `Phaser.Rectangle` or any other object
  36883. * so long as it has public `x`, `y`, `width`, `height`, `right` and `bottom` properties.
  36884. *
  36885. * A reference to the rectangle is stored in `cropRect` unless the `copy` parameter is `true`,
  36886. * in which case the values are duplicated to a local object.
  36887. *
  36888. * @method
  36889. * @param {Phaser.Rectangle} rect - The Rectangle used during cropping. Pass null or no parameters to clear a previously set crop rectangle.
  36890. * @param {boolean} [copy=false] - If false `cropRect` will be stored as a reference to the given rect. If true it will copy the rect values into a local Phaser Rectangle object stored in cropRect.
  36891. */
  36892. crop: function(rect, copy) {
  36893. if (copy === undefined) { copy = false; }
  36894. if (rect)
  36895. {
  36896. if (copy && this.cropRect !== null)
  36897. {
  36898. this.cropRect.setTo(rect.x, rect.y, rect.width, rect.height);
  36899. }
  36900. else if (copy && this.cropRect === null)
  36901. {
  36902. this.cropRect = new Phaser.Rectangle(rect.x, rect.y, rect.width, rect.height);
  36903. }
  36904. else
  36905. {
  36906. this.cropRect = rect;
  36907. }
  36908. this.updateCrop();
  36909. }
  36910. else
  36911. {
  36912. this._crop = null;
  36913. this.cropRect = null;
  36914. this.resetFrame();
  36915. }
  36916. },
  36917. /**
  36918. * If you have set a crop rectangle on this Game Object via `crop` and since modified the `cropRect` property,
  36919. * or the rectangle it references, then you need to update the crop frame by calling this method.
  36920. *
  36921. * @method
  36922. */
  36923. updateCrop: function() {
  36924. if (!this.cropRect)
  36925. {
  36926. return;
  36927. }
  36928. this._crop = Phaser.Rectangle.clone(this.cropRect, this._crop);
  36929. this._crop.x += this._frame.x;
  36930. this._crop.y += this._frame.y;
  36931. var cx = Math.max(this._frame.x, this._crop.x);
  36932. var cy = Math.max(this._frame.y, this._crop.y);
  36933. var cw = Math.min(this._frame.right, this._crop.right) - cx;
  36934. var ch = Math.min(this._frame.bottom, this._crop.bottom) - cy;
  36935. this.texture.crop.x = cx;
  36936. this.texture.crop.y = cy;
  36937. this.texture.crop.width = cw;
  36938. this.texture.crop.height = ch;
  36939. this.texture.frame.width = Math.min(cw, this.cropRect.width);
  36940. this.texture.frame.height = Math.min(ch, this.cropRect.height);
  36941. this.texture.width = this.texture.frame.width;
  36942. this.texture.height = this.texture.frame.height;
  36943. this.texture._updateUvs();
  36944. }
  36945. };
  36946. /**
  36947. * @author Richard Davey <rich@photonstorm.com>
  36948. * @copyright 2016 Photon Storm Ltd.
  36949. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  36950. */
  36951. /**
  36952. * The Delta component provides access to delta values between the Game Objects current and previous position.
  36953. *
  36954. * @class
  36955. */
  36956. Phaser.Component.Delta = function () {};
  36957. Phaser.Component.Delta.prototype = {
  36958. /**
  36959. * Returns the delta x value. The difference between world.x now and in the previous frame.
  36960. *
  36961. * The value will be positive if the Game Object has moved to the right or negative if to the left.
  36962. *
  36963. * @property {number} deltaX
  36964. * @readonly
  36965. */
  36966. deltaX: {
  36967. get: function() {
  36968. return this.world.x - this.previousPosition.x;
  36969. }
  36970. },
  36971. /**
  36972. * Returns the delta y value. The difference between world.y now and in the previous frame.
  36973. *
  36974. * The value will be positive if the Game Object has moved down or negative if up.
  36975. *
  36976. * @property {number} deltaY
  36977. * @readonly
  36978. */
  36979. deltaY: {
  36980. get: function() {
  36981. return this.world.y - this.previousPosition.y;
  36982. }
  36983. },
  36984. /**
  36985. * Returns the delta z value. The difference between rotation now and in the previous frame.
  36986. *
  36987. * @property {number} deltaZ - The delta value.
  36988. * @readonly
  36989. */
  36990. deltaZ: {
  36991. get: function() {
  36992. return this.rotation - this.previousRotation;
  36993. }
  36994. }
  36995. };
  36996. /**
  36997. * @author Richard Davey <rich@photonstorm.com>
  36998. * @copyright 2016 Photon Storm Ltd.
  36999. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  37000. */
  37001. /**
  37002. * The Destroy component is responsible for destroying a Game Object.
  37003. *
  37004. * @class
  37005. */
  37006. Phaser.Component.Destroy = function () {};
  37007. Phaser.Component.Destroy.prototype = {
  37008. /**
  37009. * As a Game Object runs through its destroy method this flag is set to true,
  37010. * and can be checked in any sub-systems or plugins it is being destroyed from.
  37011. * @property {boolean} destroyPhase
  37012. * @readOnly
  37013. */
  37014. destroyPhase: false,
  37015. /**
  37016. * Destroys the Game Object. This removes it from its parent group, destroys the input, event and animation handlers if present
  37017. * and nulls its reference to `game`, freeing it up for garbage collection.
  37018. *
  37019. * If this Game Object has the Events component it will also dispatch the `onDestroy` event.
  37020. *
  37021. * You can optionally also destroy the BaseTexture this Game Object is using. Be careful if you've
  37022. * more than one Game Object sharing the same BaseTexture.
  37023. *
  37024. * @method
  37025. * @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called as well?
  37026. * @param {boolean} [destroyTexture=false] - Destroy the BaseTexture this Game Object is using? Note that if another Game Object is sharing the same BaseTexture it will invalidate it.
  37027. */
  37028. destroy: function (destroyChildren, destroyTexture) {
  37029. if (this.game === null || this.destroyPhase) { return; }
  37030. if (destroyChildren === undefined) { destroyChildren = true; }
  37031. if (destroyTexture === undefined) { destroyTexture = false; }
  37032. this.destroyPhase = true;
  37033. if (this.events)
  37034. {
  37035. this.events.onDestroy$dispatch(this);
  37036. }
  37037. if (this.parent)
  37038. {
  37039. if (this.parent instanceof Phaser.Group)
  37040. {
  37041. this.parent.remove(this);
  37042. }
  37043. else
  37044. {
  37045. this.parent.removeChild(this);
  37046. }
  37047. }
  37048. if (this.input)
  37049. {
  37050. this.input.destroy();
  37051. }
  37052. if (this.animations)
  37053. {
  37054. this.animations.destroy();
  37055. }
  37056. if (this.body)
  37057. {
  37058. this.body.destroy();
  37059. }
  37060. if (this.events)
  37061. {
  37062. this.events.destroy();
  37063. }
  37064. this.game.tweens.removeFrom(this);
  37065. var i = this.children.length;
  37066. if (destroyChildren)
  37067. {
  37068. while (i--)
  37069. {
  37070. this.children[i].destroy(destroyChildren);
  37071. }
  37072. }
  37073. else
  37074. {
  37075. while (i--)
  37076. {
  37077. this.removeChild(this.children[i]);
  37078. }
  37079. }
  37080. if (this._crop)
  37081. {
  37082. this._crop = null;
  37083. }
  37084. if (this._frame)
  37085. {
  37086. this._frame = null;
  37087. }
  37088. if (Phaser.Video && this.key instanceof Phaser.Video)
  37089. {
  37090. this.key.onChangeSource.remove(this.resizeFrame, this);
  37091. }
  37092. if (Phaser.BitmapText && this._glyphs)
  37093. {
  37094. this._glyphs = [];
  37095. }
  37096. this.alive = false;
  37097. this.exists = false;
  37098. this.visible = false;
  37099. this.filters = null;
  37100. this.mask = null;
  37101. this.game = null;
  37102. // In case Pixi is still going to try and render it even though destroyed
  37103. this.renderable = false;
  37104. if (this.transformCallback)
  37105. {
  37106. this.transformCallback = null;
  37107. this.transformCallbackContext = null;
  37108. }
  37109. // Pixi level DisplayObject destroy
  37110. this.hitArea = null;
  37111. this.parent = null;
  37112. this.stage = null;
  37113. this.worldTransform = null;
  37114. this.filterArea = null;
  37115. this._bounds = null;
  37116. this._currentBounds = null;
  37117. this._mask = null;
  37118. this._destroyCachedSprite();
  37119. // Texture?
  37120. if (destroyTexture)
  37121. {
  37122. this.texture.destroy(true);
  37123. }
  37124. this.destroyPhase = false;
  37125. this.pendingDestroy = false;
  37126. }
  37127. };
  37128. /**
  37129. * @author Richard Davey <rich@photonstorm.com>
  37130. * @copyright 2016 Photon Storm Ltd.
  37131. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  37132. */
  37133. /**
  37134. * The Events component is a collection of events fired by the parent game object.
  37135. *
  37136. * For example to tell when a Sprite has been added to a new group:
  37137. *
  37138. * `sprite.events.onAddedToGroup.add(yourFunction, this);`
  37139. *
  37140. * Where `yourFunction` is the function you want called when this event occurs.
  37141. *
  37142. * The Input-related events will only be dispatched if the Sprite has had `inputEnabled` set to `true`
  37143. * and the Animation-related events only apply to game objects with animations like {@link Phaser.Sprite}.
  37144. *
  37145. * @class Phaser.Events
  37146. * @constructor
  37147. * @param {Phaser.Sprite} sprite - A reference to the game object / Sprite that owns this Events object.
  37148. */
  37149. Phaser.Events = function (sprite) {
  37150. /**
  37151. * @property {Phaser.Sprite} parent - The Sprite that owns these events.
  37152. */
  37153. this.parent = sprite;
  37154. // The signals are automatically added by the corresponding proxy properties
  37155. };
  37156. Phaser.Events.prototype = {
  37157. /**
  37158. * Removes all events.
  37159. *
  37160. * @method Phaser.Events#destroy
  37161. */
  37162. destroy: function () {
  37163. this._parent = null;
  37164. if (this._onDestroy) { this._onDestroy.dispose(); }
  37165. if (this._onAddedToGroup) { this._onAddedToGroup.dispose(); }
  37166. if (this._onRemovedFromGroup) { this._onRemovedFromGroup.dispose(); }
  37167. if (this._onRemovedFromWorld) { this._onRemovedFromWorld.dispose(); }
  37168. if (this._onKilled) { this._onKilled.dispose(); }
  37169. if (this._onRevived) { this._onRevived.dispose(); }
  37170. if (this._onEnterBounds) { this._onEnterBounds.dispose(); }
  37171. if (this._onOutOfBounds) { this._onOutOfBounds.dispose(); }
  37172. if (this._onInputOver) { this._onInputOver.dispose(); }
  37173. if (this._onInputOut) { this._onInputOut.dispose(); }
  37174. if (this._onInputDown) { this._onInputDown.dispose(); }
  37175. if (this._onInputUp) { this._onInputUp.dispose(); }
  37176. if (this._onDragStart) { this._onDragStart.dispose(); }
  37177. if (this._onDragUpdate) { this._onDragUpdate.dispose(); }
  37178. if (this._onDragStop) { this._onDragStop.dispose(); }
  37179. if (this._onAnimationStart) { this._onAnimationStart.dispose(); }
  37180. if (this._onAnimationComplete) { this._onAnimationComplete.dispose(); }
  37181. if (this._onAnimationLoop) { this._onAnimationLoop.dispose(); }
  37182. },
  37183. // The following properties are sentinels that will be replaced with getters
  37184. /**
  37185. * @property {Phaser.Signal} onAddedToGroup - This signal is dispatched when the parent is added to a new Group.
  37186. */
  37187. onAddedToGroup: null,
  37188. /**
  37189. * @property {Phaser.Signal} onRemovedFromGroup - This signal is dispatched when the parent is removed from a Group.
  37190. */
  37191. onRemovedFromGroup: null,
  37192. /**
  37193. * @property {Phaser.Signal} onRemovedFromWorld - This signal is dispatched if this item or any of its parents are removed from the game world.
  37194. */
  37195. onRemovedFromWorld: null,
  37196. /**
  37197. * @property {Phaser.Signal} onDestroy - This signal is dispatched when the parent is destroyed.
  37198. */
  37199. onDestroy: null,
  37200. /**
  37201. * @property {Phaser.Signal} onKilled - This signal is dispatched when the parent is killed.
  37202. */
  37203. onKilled: null,
  37204. /**
  37205. * @property {Phaser.Signal} onRevived - This signal is dispatched when the parent is revived.
  37206. */
  37207. onRevived: null,
  37208. /**
  37209. * @property {Phaser.Signal} onOutOfBounds - This signal is dispatched when the parent leaves the world bounds (only if Sprite.checkWorldBounds is true).
  37210. */
  37211. onOutOfBounds: null,
  37212. /**
  37213. * @property {Phaser.Signal} onEnterBounds - This signal is dispatched when the parent returns within the world bounds (only if Sprite.checkWorldBounds is true).
  37214. */
  37215. onEnterBounds: null,
  37216. /**
  37217. * @property {Phaser.Signal} onInputOver - This signal is dispatched if the parent is inputEnabled and receives an over event from a Pointer.
  37218. */
  37219. onInputOver: null,
  37220. /**
  37221. * @property {Phaser.Signal} onInputOut - This signal is dispatched if the parent is inputEnabled and receives an out event from a Pointer.
  37222. */
  37223. onInputOut: null,
  37224. /**
  37225. * @property {Phaser.Signal} onInputDown - This signal is dispatched if the parent is inputEnabled and receives a down event from a Pointer.
  37226. */
  37227. onInputDown: null,
  37228. /**
  37229. * @property {Phaser.Signal} onInputUp - This signal is dispatched if the parent is inputEnabled and receives an up event from a Pointer.
  37230. */
  37231. onInputUp: null,
  37232. /**
  37233. * @property {Phaser.Signal} onDragStart - This signal is dispatched if the parent is inputEnabled and receives a drag start event from a Pointer.
  37234. */
  37235. onDragStart: null,
  37236. /**
  37237. * @property {Phaser.Signal} onDragUpdate - This signal is dispatched if the parent is inputEnabled and receives a drag update event from a Pointer.
  37238. */
  37239. onDragUpdate: null,
  37240. /**
  37241. * @property {Phaser.Signal} onDragStop - This signal is dispatched if the parent is inputEnabled and receives a drag stop event from a Pointer.
  37242. */
  37243. onDragStop: null,
  37244. /**
  37245. * @property {Phaser.Signal} onAnimationStart - This signal is dispatched when the parent has an animation that is played.
  37246. */
  37247. onAnimationStart: null,
  37248. /**
  37249. * @property {Phaser.Signal} onAnimationComplete - This signal is dispatched when the parent has an animation that finishes playing.
  37250. */
  37251. onAnimationComplete: null,
  37252. /**
  37253. * @property {Phaser.Signal} onAnimationLoop - This signal is dispatched when the parent has an animation that loops playback.
  37254. */
  37255. onAnimationLoop: null
  37256. };
  37257. Phaser.Events.prototype.constructor = Phaser.Events;
  37258. // Create an auto-create proxy getter and dispatch method for all events.
  37259. // The backing property is the same as the event name, prefixed with '_'
  37260. // and the dispatch method is the same as the event name postfixed with '$dispatch'.
  37261. for (var prop in Phaser.Events.prototype)
  37262. {
  37263. if (!Phaser.Events.prototype.hasOwnProperty(prop) ||
  37264. prop.indexOf('on') !== 0 ||
  37265. Phaser.Events.prototype[prop] !== null)
  37266. {
  37267. continue;
  37268. }
  37269. (function (prop, backing) {
  37270. 'use strict';
  37271. // The accessor creates a new Signal; and so it should only be used from user-code.
  37272. Object.defineProperty(Phaser.Events.prototype, prop, {
  37273. get: function () {
  37274. return this[backing] || (this[backing] = new Phaser.Signal());
  37275. }
  37276. });
  37277. // The dispatcher will only broadcast on an already-created signal; call this internally.
  37278. Phaser.Events.prototype[prop + '$dispatch'] = function () {
  37279. return this[backing] ? this[backing].dispatch.apply(this[backing], arguments) : null;
  37280. };
  37281. })(prop, '_' + prop);
  37282. }
  37283. /**
  37284. * @author Richard Davey <rich@photonstorm.com>
  37285. * @copyright 2016 Photon Storm Ltd.
  37286. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  37287. */
  37288. /**
  37289. * The FixedToCamera component enables a Game Object to be rendered relative to the game camera coordinates, regardless
  37290. * of where in the world the camera is. This is used for things like sticking game UI to the camera that scrolls as it moves around the world.
  37291. *
  37292. * @class
  37293. */
  37294. Phaser.Component.FixedToCamera = function () {};
  37295. /**
  37296. * The FixedToCamera component postUpdate handler.
  37297. * Called automatically by the Game Object.
  37298. *
  37299. * @method
  37300. */
  37301. Phaser.Component.FixedToCamera.postUpdate = function () {
  37302. if (this.fixedToCamera)
  37303. {
  37304. this.position.x = (this.game.camera.view.x + this.cameraOffset.x) / this.game.camera.scale.x;
  37305. this.position.y = (this.game.camera.view.y + this.cameraOffset.y) / this.game.camera.scale.y;
  37306. }
  37307. };
  37308. Phaser.Component.FixedToCamera.prototype = {
  37309. /**
  37310. * @property {boolean} _fixedToCamera
  37311. * @private
  37312. */
  37313. _fixedToCamera: false,
  37314. /**
  37315. * A Game Object that is "fixed" to the camera uses its x/y coordinates as offsets from the top left of the camera during rendering.
  37316. *
  37317. * The values are adjusted at the rendering stage, overriding the Game Objects actual world position.
  37318. *
  37319. * The end result is that the Game Object will appear to be 'fixed' to the camera, regardless of where in the game world
  37320. * the camera is viewing. This is useful if for example this Game Object is a UI item that you wish to be visible at all times
  37321. * regardless where in the world the camera is.
  37322. *
  37323. * The offsets are stored in the `cameraOffset` property.
  37324. *
  37325. * Note that the `cameraOffset` values are in addition to any parent of this Game Object on the display list.
  37326. *
  37327. * Be careful not to set `fixedToCamera` on Game Objects which are in Groups that already have `fixedToCamera` enabled on them.
  37328. *
  37329. * @property {boolean} fixedToCamera
  37330. */
  37331. fixedToCamera: {
  37332. get: function () {
  37333. return this._fixedToCamera;
  37334. },
  37335. set: function (value) {
  37336. if (value)
  37337. {
  37338. this._fixedToCamera = true;
  37339. this.cameraOffset.set(this.x, this.y);
  37340. }
  37341. else
  37342. {
  37343. this._fixedToCamera = false;
  37344. }
  37345. }
  37346. },
  37347. /**
  37348. * The x/y coordinate offset applied to the top-left of the camera that this Game Object will be drawn at if `fixedToCamera` is true.
  37349. *
  37350. * The values are relative to the top-left of the camera view and in addition to any parent of the Game Object on the display list.
  37351. * @property {Phaser.Point} cameraOffset
  37352. */
  37353. cameraOffset: new Phaser.Point()
  37354. };
  37355. /**
  37356. * @author Richard Davey <rich@photonstorm.com>
  37357. * @copyright 2016 Photon Storm Ltd.
  37358. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  37359. */
  37360. /**
  37361. * The Health component provides the ability for Game Objects to have a `health` property
  37362. * that can be damaged and reset through game code.
  37363. * Requires the LifeSpan component.
  37364. *
  37365. * @class
  37366. */
  37367. Phaser.Component.Health = function () {};
  37368. Phaser.Component.Health.prototype = {
  37369. /**
  37370. * The Game Objects health value. This is a handy property for setting and manipulating health on a Game Object.
  37371. *
  37372. * It can be used in combination with the `damage` method or modified directly.
  37373. *
  37374. * @property {number} health
  37375. * @default
  37376. */
  37377. health: 1,
  37378. /**
  37379. * The Game Objects maximum health value. This works in combination with the `heal` method to ensure
  37380. * the health value never exceeds the maximum.
  37381. *
  37382. * @property {number} maxHealth
  37383. * @default
  37384. */
  37385. maxHealth: 100,
  37386. /**
  37387. * Damages the Game Object. This removes the given amount of health from the `health` property.
  37388. *
  37389. * If health is taken below or is equal to zero then the `kill` method is called.
  37390. *
  37391. * @member
  37392. * @param {number} amount - The amount to subtract from the current `health` value.
  37393. * @return {Phaser.Sprite} This instance.
  37394. */
  37395. damage: function (amount) {
  37396. if (this.alive)
  37397. {
  37398. this.health -= amount;
  37399. if (this.health <= 0)
  37400. {
  37401. this.kill();
  37402. }
  37403. }
  37404. return this;
  37405. },
  37406. /**
  37407. * Sets the health property of the Game Object to the given amount.
  37408. * Will never exceed the `maxHealth` value.
  37409. *
  37410. * @member
  37411. * @param {number} amount - The amount to set the `health` value to. The total will never exceed `maxHealth`.
  37412. * @return {Phaser.Sprite} This instance.
  37413. */
  37414. setHealth: function (amount) {
  37415. this.health = amount;
  37416. if (this.health > this.maxHealth)
  37417. {
  37418. this.health = this.maxHealth;
  37419. }
  37420. return this;
  37421. },
  37422. /**
  37423. * Heal the Game Object. This adds the given amount of health to the `health` property.
  37424. *
  37425. * @member
  37426. * @param {number} amount - The amount to add to the current `health` value. The total will never exceed `maxHealth`.
  37427. * @return {Phaser.Sprite} This instance.
  37428. */
  37429. heal: function (amount) {
  37430. if (this.alive)
  37431. {
  37432. this.health += amount;
  37433. if (this.health > this.maxHealth)
  37434. {
  37435. this.health = this.maxHealth;
  37436. }
  37437. }
  37438. return this;
  37439. }
  37440. };
  37441. /**
  37442. * @author Richard Davey <rich@photonstorm.com>
  37443. * @copyright 2016 Photon Storm Ltd.
  37444. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  37445. */
  37446. /**
  37447. * The InCamera component checks if the Game Object intersects with the Game Camera.
  37448. *
  37449. * @class
  37450. */
  37451. Phaser.Component.InCamera = function () {};
  37452. Phaser.Component.InCamera.prototype = {
  37453. /**
  37454. * Checks if this Game Objects bounds intersects with the Game Cameras bounds.
  37455. *
  37456. * It will be `true` if they intersect, or `false` if the Game Object is fully outside of the Cameras bounds.
  37457. *
  37458. * An object outside the bounds can be considered for camera culling if it has the AutoCull component.
  37459. *
  37460. * @property {boolean} inCamera
  37461. * @readonly
  37462. */
  37463. inCamera: {
  37464. get: function() {
  37465. return this.game.world.camera.view.intersects(this._bounds);
  37466. }
  37467. }
  37468. };
  37469. /**
  37470. * @author Richard Davey <rich@photonstorm.com>
  37471. * @copyright 2016 Photon Storm Ltd.
  37472. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  37473. */
  37474. /**
  37475. * The InputEnabled component allows a Game Object to have its own InputHandler and process input related events.
  37476. *
  37477. * @class
  37478. */
  37479. Phaser.Component.InputEnabled = function () {};
  37480. Phaser.Component.InputEnabled.prototype = {
  37481. /**
  37482. * The Input Handler for this Game Object.
  37483. *
  37484. * By default it is disabled. If you wish this Game Object to process input events you should enable it with: `inputEnabled = true`.
  37485. *
  37486. * After you have done this, this property will be a reference to the Phaser InputHandler.
  37487. * @property {Phaser.InputHandler|null} input
  37488. */
  37489. input: null,
  37490. /**
  37491. * By default a Game Object won't process any input events. By setting `inputEnabled` to true a Phaser.InputHandler is created
  37492. * for this Game Object and it will then start to process click / touch events and more.
  37493. *
  37494. * You can then access the Input Handler via `this.input`.
  37495. *
  37496. * Note that Input related events are dispatched from `this.events`, i.e.: `events.onInputDown`.
  37497. *
  37498. * If you set this property to false it will stop the Input Handler from processing any more input events.
  37499. *
  37500. * @property {boolean} inputEnabled
  37501. */
  37502. inputEnabled: {
  37503. get: function () {
  37504. return (this.input && this.input.enabled);
  37505. },
  37506. set: function (value) {
  37507. if (value)
  37508. {
  37509. if (this.input === null)
  37510. {
  37511. this.input = new Phaser.InputHandler(this);
  37512. this.input.start();
  37513. }
  37514. else if (this.input && !this.input.enabled)
  37515. {
  37516. this.input.start();
  37517. }
  37518. }
  37519. else
  37520. {
  37521. if (this.input && this.input.enabled)
  37522. {
  37523. this.input.stop();
  37524. }
  37525. }
  37526. }
  37527. }
  37528. };
  37529. /**
  37530. * @author Richard Davey <rich@photonstorm.com>
  37531. * @copyright 2016 Photon Storm Ltd.
  37532. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  37533. */
  37534. /**
  37535. * The InWorld component checks if a Game Object is within the Game World Bounds.
  37536. * An object is considered as being "in bounds" so long as its own bounds intersects at any point with the World bounds.
  37537. * If the AutoCull component is enabled on the Game Object then it will check the Game Object against the Camera bounds as well.
  37538. *
  37539. * @class
  37540. */
  37541. Phaser.Component.InWorld = function () {};
  37542. /**
  37543. * The InWorld component preUpdate handler.
  37544. * Called automatically by the Game Object.
  37545. *
  37546. * @method
  37547. */
  37548. Phaser.Component.InWorld.preUpdate = function () {
  37549. // Cache the bounds if we need it
  37550. if (this.autoCull || this.checkWorldBounds)
  37551. {
  37552. this._bounds.copyFrom(this.getBounds());
  37553. this._bounds.x += this.game.camera.view.x;
  37554. this._bounds.y += this.game.camera.view.y;
  37555. if (this.autoCull)
  37556. {
  37557. // Won't get rendered but will still get its transform updated
  37558. if (this.game.world.camera.view.intersects(this._bounds))
  37559. {
  37560. this.renderable = true;
  37561. this.game.world.camera.totalInView++;
  37562. }
  37563. else
  37564. {
  37565. this.renderable = false;
  37566. if (this.outOfCameraBoundsKill)
  37567. {
  37568. this.kill();
  37569. return false;
  37570. }
  37571. }
  37572. }
  37573. if (this.checkWorldBounds)
  37574. {
  37575. // The Sprite is already out of the world bounds, so let's check to see if it has come back again
  37576. if (this._outOfBoundsFired && this.game.world.bounds.intersects(this._bounds))
  37577. {
  37578. this._outOfBoundsFired = false;
  37579. this.events.onEnterBounds$dispatch(this);
  37580. }
  37581. else if (!this._outOfBoundsFired && !this.game.world.bounds.intersects(this._bounds))
  37582. {
  37583. // The Sprite WAS in the screen, but has now left.
  37584. this._outOfBoundsFired = true;
  37585. this.events.onOutOfBounds$dispatch(this);
  37586. if (this.outOfBoundsKill)
  37587. {
  37588. this.kill();
  37589. return false;
  37590. }
  37591. }
  37592. }
  37593. }
  37594. return true;
  37595. };
  37596. Phaser.Component.InWorld.prototype = {
  37597. /**
  37598. * If this is set to `true` the Game Object checks if it is within the World bounds each frame.
  37599. *
  37600. * When it is no longer intersecting the world bounds it dispatches the `onOutOfBounds` event.
  37601. *
  37602. * If it was *previously* out of bounds but is now intersecting the world bounds again it dispatches the `onEnterBounds` event.
  37603. *
  37604. * It also optionally kills the Game Object if `outOfBoundsKill` is `true`.
  37605. *
  37606. * When `checkWorldBounds` is enabled it forces the Game Object to calculate its full bounds every frame.
  37607. *
  37608. * This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required,
  37609. * or you have tested performance and find it acceptable.
  37610. *
  37611. * @property {boolean} checkWorldBounds
  37612. * @default
  37613. */
  37614. checkWorldBounds: false,
  37615. /**
  37616. * If this and the `checkWorldBounds` property are both set to `true` then the `kill` method is called as soon as `inWorld` returns false.
  37617. *
  37618. * @property {boolean} outOfBoundsKill
  37619. * @default
  37620. */
  37621. outOfBoundsKill: false,
  37622. /**
  37623. * If this and the `autoCull` property are both set to `true`, then the `kill` method
  37624. * is called as soon as the Game Object leaves the camera bounds.
  37625. *
  37626. * @property {boolean} outOfCameraBoundsKill
  37627. * @default
  37628. */
  37629. outOfCameraBoundsKill: false,
  37630. /**
  37631. * @property {boolean} _outOfBoundsFired - Internal state var.
  37632. * @private
  37633. */
  37634. _outOfBoundsFired: false,
  37635. /**
  37636. * Checks if the Game Objects bounds are within, or intersect at any point with the Game World bounds.
  37637. *
  37638. * @property {boolean} inWorld
  37639. * @readonly
  37640. */
  37641. inWorld: {
  37642. get: function () {
  37643. return this.game.world.bounds.intersects(this.getBounds());
  37644. }
  37645. }
  37646. };
  37647. /**
  37648. * @author Richard Davey <rich@photonstorm.com>
  37649. * @copyright 2016 Photon Storm Ltd.
  37650. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  37651. */
  37652. /**
  37653. * LifeSpan Component Features.
  37654. *
  37655. * @class
  37656. */
  37657. Phaser.Component.LifeSpan = function () {};
  37658. /**
  37659. * The LifeSpan component preUpdate handler.
  37660. * Called automatically by the Game Object.
  37661. *
  37662. * @method
  37663. */
  37664. Phaser.Component.LifeSpan.preUpdate = function () {
  37665. if (this.lifespan > 0)
  37666. {
  37667. this.lifespan -= this.game.time.physicsElapsedMS;
  37668. if (this.lifespan <= 0)
  37669. {
  37670. this.kill();
  37671. return false;
  37672. }
  37673. }
  37674. return true;
  37675. };
  37676. Phaser.Component.LifeSpan.prototype = {
  37677. /**
  37678. * A useful flag to control if the Game Object is alive or dead.
  37679. *
  37680. * This is set automatically by the Health components `damage` method should the object run out of health.
  37681. * Or you can toggle it via your game code.
  37682. *
  37683. * This property is mostly just provided to be used by your game - it doesn't effect rendering or logic updates.
  37684. * However you can use `Group.getFirstAlive` in conjunction with this property for fast object pooling and recycling.
  37685. * @property {boolean} alive
  37686. * @default
  37687. */
  37688. alive: true,
  37689. /**
  37690. * The lifespan allows you to give a Game Object a lifespan in milliseconds.
  37691. *
  37692. * Once the Game Object is 'born' you can set this to a positive value.
  37693. *
  37694. * It is automatically decremented by the millisecond equivalent of `game.time.physicsElapsed` each frame.
  37695. * When it reaches zero it will call the `kill` method.
  37696. *
  37697. * Very handy for particles, bullets, collectibles, or any other short-lived entity.
  37698. *
  37699. * @property {number} lifespan
  37700. * @default
  37701. */
  37702. lifespan: 0,
  37703. /**
  37704. * Brings a 'dead' Game Object back to life, optionally resetting its health value in the process.
  37705. *
  37706. * A resurrected Game Object has its `alive`, `exists` and `visible` properties all set to true.
  37707. *
  37708. * It will dispatch the `onRevived` event. Listen to `events.onRevived` for the signal.
  37709. *
  37710. * @method
  37711. * @param {number} [health=100] - The health to give the Game Object. Only set if the GameObject has the Health component.
  37712. * @return {PIXI.DisplayObject} This instance.
  37713. */
  37714. revive: function (health) {
  37715. if (health === undefined) { health = 100; }
  37716. this.alive = true;
  37717. this.exists = true;
  37718. this.visible = true;
  37719. if (typeof this.setHealth === 'function')
  37720. {
  37721. this.setHealth(health);
  37722. }
  37723. if (this.events)
  37724. {
  37725. this.events.onRevived$dispatch(this);
  37726. }
  37727. return this;
  37728. },
  37729. /**
  37730. * Kills a Game Object. A killed Game Object has its `alive`, `exists` and `visible` properties all set to false.
  37731. *
  37732. * It will dispatch the `onKilled` event. You can listen to `events.onKilled` for the signal.
  37733. *
  37734. * Note that killing a Game Object is a way for you to quickly recycle it in an object pool,
  37735. * it doesn't destroy the object or free it up from memory.
  37736. *
  37737. * If you don't need this Game Object any more you should call `destroy` instead.
  37738. *
  37739. * @method
  37740. * @return {PIXI.DisplayObject} This instance.
  37741. */
  37742. kill: function () {
  37743. this.alive = false;
  37744. this.exists = false;
  37745. this.visible = false;
  37746. if (this.events)
  37747. {
  37748. this.events.onKilled$dispatch(this);
  37749. }
  37750. return this;
  37751. }
  37752. };
  37753. /**
  37754. * @author Richard Davey <rich@photonstorm.com>
  37755. * @copyright 2016 Photon Storm Ltd.
  37756. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  37757. */
  37758. /**
  37759. * The LoadTexture component manages the loading of a texture into the Game Object and the changing of frames.
  37760. *
  37761. * @class
  37762. */
  37763. Phaser.Component.LoadTexture = function () {};
  37764. Phaser.Component.LoadTexture.prototype = {
  37765. /**
  37766. * @property {boolean} customRender - Does this texture require a custom render call? (as set by BitmapData, Video, etc)
  37767. * @private
  37768. */
  37769. customRender: false,
  37770. /**
  37771. * @property {Phaser.Rectangle} _frame - Internal cache var.
  37772. * @private
  37773. */
  37774. _frame: null,
  37775. /**
  37776. * Changes the base texture the Game Object is using. The old texture is removed and the new one is referenced or fetched from the Cache.
  37777. *
  37778. * If your Game Object is using a frame from a texture atlas and you just wish to change to another frame, then see the `frame` or `frameName` properties instead.
  37779. *
  37780. * You should only use `loadTexture` if you want to replace the base texture entirely.
  37781. *
  37782. * Calling this method causes a WebGL texture update, so use sparingly or in low-intensity portions of your game, or if you know the new texture is already on the GPU.
  37783. *
  37784. * You can use the new const `Phaser.PENDING_ATLAS` as the texture key for any sprite.
  37785. * Doing this then sets the key to be the `frame` argument (the frame is set to zero).
  37786. *
  37787. * This allows you to create sprites using `load.image` during development, and then change them
  37788. * to use a Texture Atlas later in development by simply searching your code for 'PENDING_ATLAS'
  37789. * and swapping it to be the key of the atlas data.
  37790. *
  37791. * Note: You cannot use a RenderTexture as a texture for a TileSprite.
  37792. *
  37793. * @method
  37794. * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|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 Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture.
  37795. * @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.
  37796. * @param {boolean} [stopAnimation=true] - If an animation is already playing on this Sprite you can choose to stop it or let it carry on playing.
  37797. */
  37798. loadTexture: function (key, frame, stopAnimation) {
  37799. if (key === Phaser.PENDING_ATLAS)
  37800. {
  37801. key = frame;
  37802. frame = 0;
  37803. }
  37804. else
  37805. {
  37806. frame = frame || 0;
  37807. }
  37808. if ((stopAnimation || stopAnimation === undefined) && this.animations)
  37809. {
  37810. this.animations.stop();
  37811. }
  37812. this.key = key;
  37813. this.customRender = false;
  37814. var cache = this.game.cache;
  37815. var setFrame = true;
  37816. var smoothed = !this.texture.baseTexture.scaleMode;
  37817. if (Phaser.RenderTexture && key instanceof Phaser.RenderTexture)
  37818. {
  37819. this.key = key.key;
  37820. this.setTexture(key);
  37821. }
  37822. else if (Phaser.BitmapData && key instanceof Phaser.BitmapData)
  37823. {
  37824. this.customRender = true;
  37825. this.setTexture(key.texture);
  37826. if (cache.hasFrameData(key.key, Phaser.Cache.BITMAPDATA))
  37827. {
  37828. setFrame = !this.animations.loadFrameData(cache.getFrameData(key.key, Phaser.Cache.BITMAPDATA), frame);
  37829. }
  37830. else
  37831. {
  37832. setFrame = !this.animations.loadFrameData(key.frameData, 0);
  37833. }
  37834. }
  37835. else if (Phaser.Video && key instanceof Phaser.Video)
  37836. {
  37837. this.customRender = true;
  37838. // This works from a reference, which probably isn't what we need here
  37839. var valid = key.texture.valid;
  37840. this.setTexture(key.texture);
  37841. this.setFrame(key.texture.frame.clone());
  37842. key.onChangeSource.add(this.resizeFrame, this);
  37843. this.texture.valid = valid;
  37844. }
  37845. else if (Phaser.Tilemap && key instanceof Phaser.TilemapLayer)
  37846. {
  37847. // this.customRender = true;
  37848. this.setTexture(PIXI.Texture.fromCanvas(key.canvas));
  37849. }
  37850. else if (key instanceof PIXI.Texture)
  37851. {
  37852. this.setTexture(key);
  37853. }
  37854. else
  37855. {
  37856. var img = cache.getImage(key, true);
  37857. this.key = img.key;
  37858. this.setTexture(new PIXI.Texture(img.base));
  37859. if (key === '__default')
  37860. {
  37861. this.texture.baseTexture.skipRender = true;
  37862. }
  37863. else
  37864. {
  37865. this.texture.baseTexture.skipRender = false;
  37866. }
  37867. setFrame = !this.animations.loadFrameData(img.frameData, frame);
  37868. }
  37869. if (setFrame)
  37870. {
  37871. this._frame = Phaser.Rectangle.clone(this.texture.frame);
  37872. }
  37873. if (!smoothed)
  37874. {
  37875. this.texture.baseTexture.scaleMode = 1;
  37876. }
  37877. },
  37878. /**
  37879. * Sets the texture frame the Game Object uses for rendering.
  37880. *
  37881. * This is primarily an internal method used by `loadTexture`, but is exposed for the use of plugins and custom classes.
  37882. *
  37883. * @method
  37884. * @param {Phaser.Frame} frame - The Frame to be used by the texture.
  37885. */
  37886. setFrame: function (frame) {
  37887. this._frame = frame;
  37888. this.texture.frame.x = frame.x;
  37889. this.texture.frame.y = frame.y;
  37890. this.texture.frame.width = frame.width;
  37891. this.texture.frame.height = frame.height;
  37892. this.texture.crop.x = frame.x;
  37893. this.texture.crop.y = frame.y;
  37894. this.texture.crop.width = frame.width;
  37895. this.texture.crop.height = frame.height;
  37896. if (frame.trimmed)
  37897. {
  37898. if (this.texture.trim)
  37899. {
  37900. this.texture.trim.x = frame.spriteSourceSizeX;
  37901. this.texture.trim.y = frame.spriteSourceSizeY;
  37902. this.texture.trim.width = frame.sourceSizeW;
  37903. this.texture.trim.height = frame.sourceSizeH;
  37904. }
  37905. else
  37906. {
  37907. this.texture.trim = { x: frame.spriteSourceSizeX, y: frame.spriteSourceSizeY, width: frame.sourceSizeW, height: frame.sourceSizeH };
  37908. }
  37909. this.texture.width = frame.sourceSizeW;
  37910. this.texture.height = frame.sourceSizeH;
  37911. this.texture.frame.width = frame.sourceSizeW;
  37912. this.texture.frame.height = frame.sourceSizeH;
  37913. }
  37914. else if (!frame.trimmed && this.texture.trim)
  37915. {
  37916. this.texture.trim = null;
  37917. }
  37918. if (this.cropRect)
  37919. {
  37920. this.updateCrop();
  37921. }
  37922. this.texture.requiresReTint = true;
  37923. this.texture._updateUvs();
  37924. if (this.tilingTexture)
  37925. {
  37926. this.refreshTexture = true;
  37927. }
  37928. },
  37929. /**
  37930. * Resizes the Frame dimensions that the Game Object uses for rendering.
  37931. *
  37932. * You shouldn't normally need to ever call this, but in the case of special texture types such as Video or BitmapData
  37933. * it can be useful to adjust the dimensions directly in this way.
  37934. *
  37935. * @method
  37936. * @param {object} parent - The parent texture object that caused the resize, i.e. a Phaser.Video object.
  37937. * @param {integer} width - The new width of the texture.
  37938. * @param {integer} height - The new height of the texture.
  37939. */
  37940. resizeFrame: function (parent, width, height) {
  37941. this.texture.frame.resize(width, height);
  37942. this.texture.setFrame(this.texture.frame);
  37943. },
  37944. /**
  37945. * Resets the texture frame dimensions that the Game Object uses for rendering.
  37946. *
  37947. * @method
  37948. */
  37949. resetFrame: function () {
  37950. if (this._frame)
  37951. {
  37952. this.setFrame(this._frame);
  37953. }
  37954. },
  37955. /**
  37956. * Gets or sets the current frame index of the texture being used to render this Game Object.
  37957. *
  37958. * To change the frame set `frame` to the index of the new frame in the sprite sheet you wish this Game Object to use,
  37959. * for example: `player.frame = 4`.
  37960. *
  37961. * If the frame index given doesn't exist it will revert to the first frame found in the texture.
  37962. *
  37963. * If you are using a texture atlas then you should use the `frameName` property instead.
  37964. *
  37965. * If you wish to fully replace the texture being used see `loadTexture`.
  37966. * @property {integer} frame
  37967. */
  37968. frame: {
  37969. get: function () {
  37970. return this.animations.frame;
  37971. },
  37972. set: function (value) {
  37973. this.animations.frame = value;
  37974. }
  37975. },
  37976. /**
  37977. * Gets or sets the current frame name of the texture being used to render this Game Object.
  37978. *
  37979. * To change the frame set `frameName` to the name of the new frame in the texture atlas you wish this Game Object to use,
  37980. * for example: `player.frameName = "idle"`.
  37981. *
  37982. * If the frame name given doesn't exist it will revert to the first frame found in the texture and throw a console warning.
  37983. *
  37984. * If you are using a sprite sheet then you should use the `frame` property instead.
  37985. *
  37986. * If you wish to fully replace the texture being used see `loadTexture`.
  37987. * @property {string} frameName
  37988. */
  37989. frameName: {
  37990. get: function () {
  37991. return this.animations.frameName;
  37992. },
  37993. set: function (value) {
  37994. this.animations.frameName = value;
  37995. }
  37996. }
  37997. };
  37998. /**
  37999. * @author Richard Davey <rich@photonstorm.com>
  38000. * @copyright 2016 Photon Storm Ltd.
  38001. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  38002. */
  38003. /**
  38004. * The Overlap component allows a Game Object to check if it overlaps with the bounds of another Game Object.
  38005. *
  38006. * @class
  38007. */
  38008. Phaser.Component.Overlap = function () {};
  38009. Phaser.Component.Overlap.prototype = {
  38010. /**
  38011. * Checks to see if the bounds of this Game Object overlaps with the bounds of the given Display Object,
  38012. * which can be a Sprite, Image, TileSprite or anything that extends those such as Button or provides a `getBounds` method and result.
  38013. *
  38014. * This check ignores the `hitArea` property if set and runs a `getBounds` comparison on both objects to determine the result.
  38015. *
  38016. * Therefore it's relatively expensive to use in large quantities, i.e. with lots of Sprites at a high frequency.
  38017. * It should be fine for low-volume testing where physics isn't required.
  38018. *
  38019. * @method
  38020. * @param {Phaser.Sprite|Phaser.Image|Phaser.TileSprite|Phaser.Button|PIXI.DisplayObject} displayObject - The display object to check against.
  38021. * @return {boolean} True if the bounds of this Game Object intersects at any point with the bounds of the given display object.
  38022. */
  38023. overlap: function (displayObject) {
  38024. return Phaser.Rectangle.intersects(this.getBounds(), displayObject.getBounds());
  38025. }
  38026. };
  38027. /**
  38028. * @author Richard Davey <rich@photonstorm.com>
  38029. * @copyright 2016 Photon Storm Ltd.
  38030. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  38031. */
  38032. /**
  38033. * The PhysicsBody component manages the Game Objects physics body and physics enabling.
  38034. * It also overrides the x and y properties, ensuring that any manual adjustment of them is reflected in the physics body itself.
  38035. *
  38036. * @class
  38037. */
  38038. Phaser.Component.PhysicsBody = function () {};
  38039. /**
  38040. * The PhysicsBody component preUpdate handler.
  38041. * Called automatically by the Game Object.
  38042. *
  38043. * @method
  38044. */
  38045. Phaser.Component.PhysicsBody.preUpdate = function () {
  38046. if (this.fresh && this.exists)
  38047. {
  38048. this.world.setTo(this.parent.position.x + this.position.x, this.parent.position.y + this.position.y);
  38049. this.worldTransform.tx = this.world.x;
  38050. this.worldTransform.ty = this.world.y;
  38051. this.previousPosition.set(this.world.x, this.world.y);
  38052. this.previousRotation = this.rotation;
  38053. if (this.body)
  38054. {
  38055. this.body.preUpdate();
  38056. }
  38057. this.fresh = false;
  38058. return false;
  38059. }
  38060. this.previousPosition.set(this.world.x, this.world.y);
  38061. this.previousRotation = this.rotation;
  38062. if (!this._exists || !this.parent.exists)
  38063. {
  38064. this.renderOrderID = -1;
  38065. return false;
  38066. }
  38067. return true;
  38068. };
  38069. /**
  38070. * The PhysicsBody component postUpdate handler.
  38071. * Called automatically by the Game Object.
  38072. *
  38073. * @method
  38074. */
  38075. Phaser.Component.PhysicsBody.postUpdate = function () {
  38076. if (this.exists && this.body)
  38077. {
  38078. this.body.postUpdate();
  38079. }
  38080. };
  38081. Phaser.Component.PhysicsBody.prototype = {
  38082. /**
  38083. * `body` is the Game Objects physics body. Once a Game Object is enabled for physics you access all associated
  38084. * properties and methods via it.
  38085. *
  38086. * By default Game Objects won't add themselves to any physics system and their `body` property will be `null`.
  38087. *
  38088. * To enable this Game Object for physics you need to call `game.physics.enable(object, system)` where `object` is this object
  38089. * and `system` is the Physics system you are using. If none is given it defaults to `Phaser.Physics.Arcade`.
  38090. *
  38091. * You can alternatively call `game.physics.arcade.enable(object)`, or add this Game Object to a physics enabled Group.
  38092. *
  38093. * Important: Enabling a Game Object for P2 or Ninja physics will automatically set its `anchor` property to 0.5,
  38094. * so the physics body is centered on the Game Object.
  38095. *
  38096. * If you need a different result then adjust or re-create the Body shape offsets manually or reset the anchor after enabling physics.
  38097. *
  38098. * @property {Phaser.Physics.Arcade.Body|Phaser.Physics.P2.Body|Phaser.Physics.Ninja.Body|null} body
  38099. * @default
  38100. */
  38101. body: null,
  38102. /**
  38103. * The position of the Game Object on the x axis relative to the local coordinates of the parent.
  38104. *
  38105. * @property {number} x
  38106. */
  38107. x: {
  38108. get: function () {
  38109. return this.position.x;
  38110. },
  38111. set: function (value) {
  38112. this.position.x = value;
  38113. if (this.body && !this.body.dirty)
  38114. {
  38115. this.body._reset = true;
  38116. }
  38117. }
  38118. },
  38119. /**
  38120. * The position of the Game Object on the y axis relative to the local coordinates of the parent.
  38121. *
  38122. * @property {number} y
  38123. */
  38124. y: {
  38125. get: function () {
  38126. return this.position.y;
  38127. },
  38128. set: function (value) {
  38129. this.position.y = value;
  38130. if (this.body && !this.body.dirty)
  38131. {
  38132. this.body._reset = true;
  38133. }
  38134. }
  38135. }
  38136. };
  38137. /**
  38138. * @author Richard Davey <rich@photonstorm.com>
  38139. * @copyright 2016 Photon Storm Ltd.
  38140. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  38141. */
  38142. /**
  38143. * The Reset component allows a Game Object to be reset and repositioned to a new location.
  38144. *
  38145. * @class
  38146. */
  38147. Phaser.Component.Reset = function () {};
  38148. /**
  38149. * Resets the Game Object.
  38150. *
  38151. * This moves the Game Object to the given x/y world coordinates and sets `fresh`, `exists`,
  38152. * `visible` and `renderable` to true.
  38153. *
  38154. * If this Game Object has the LifeSpan component it will also set `alive` to true and `health` to the given value.
  38155. *
  38156. * If this Game Object has a Physics Body it will reset the Body.
  38157. *
  38158. * @method
  38159. * @param {number} x - The x coordinate (in world space) to position the Game Object at.
  38160. * @param {number} y - The y coordinate (in world space) to position the Game Object at.
  38161. * @param {number} [health=1] - The health to give the Game Object if it has the Health component.
  38162. * @return {PIXI.DisplayObject} This instance.
  38163. */
  38164. Phaser.Component.Reset.prototype.reset = function (x, y, health) {
  38165. if (health === undefined) { health = 1; }
  38166. this.world.set(x, y);
  38167. this.position.set(x, y);
  38168. this.fresh = true;
  38169. this.exists = true;
  38170. this.visible = true;
  38171. this.renderable = true;
  38172. if (this.components.InWorld)
  38173. {
  38174. this._outOfBoundsFired = false;
  38175. }
  38176. if (this.components.LifeSpan)
  38177. {
  38178. this.alive = true;
  38179. this.health = health;
  38180. }
  38181. if (this.components.PhysicsBody)
  38182. {
  38183. if (this.body)
  38184. {
  38185. this.body.reset(x, y, false, false);
  38186. }
  38187. }
  38188. return this;
  38189. };
  38190. /**
  38191. * @author Richard Davey <rich@photonstorm.com>
  38192. * @copyright 2016 Photon Storm Ltd.
  38193. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  38194. */
  38195. /**
  38196. * The ScaleMinMax component allows a Game Object to limit how far it can be scaled by its parent.
  38197. *
  38198. * @class
  38199. */
  38200. Phaser.Component.ScaleMinMax = function () {};
  38201. Phaser.Component.ScaleMinMax.prototype = {
  38202. /**
  38203. * The callback that will apply any scale limiting to the worldTransform.
  38204. * @property {function} transformCallback
  38205. */
  38206. transformCallback: null,
  38207. /**
  38208. * The context under which `transformCallback` is called.
  38209. * @property {object} transformCallbackContext
  38210. */
  38211. transformCallbackContext: this,
  38212. /**
  38213. * The minimum scale this Game Object will scale down to.
  38214. *
  38215. * It allows you to prevent a parent from scaling this Game Object lower than the given value.
  38216. *
  38217. * Set it to `null` to remove the limit.
  38218. * @property {Phaser.Point} scaleMin
  38219. */
  38220. scaleMin: null,
  38221. /**
  38222. * The maximum scale this Game Object will scale up to.
  38223. *
  38224. * It allows you to prevent a parent from scaling this Game Object higher than the given value.
  38225. *
  38226. * Set it to `null` to remove the limit.
  38227. * @property {Phaser.Point} scaleMax
  38228. */
  38229. scaleMax: null,
  38230. /**
  38231. * Adjust scaling limits, if set, to this Game Object.
  38232. *
  38233. * @method
  38234. * @private
  38235. * @param {PIXI.Matrix} wt - The updated worldTransform matrix.
  38236. */
  38237. checkTransform: function (wt) {
  38238. if (this.scaleMin)
  38239. {
  38240. if (wt.a < this.scaleMin.x)
  38241. {
  38242. wt.a = this.scaleMin.x;
  38243. }
  38244. if (wt.d < this.scaleMin.y)
  38245. {
  38246. wt.d = this.scaleMin.y;
  38247. }
  38248. }
  38249. if (this.scaleMax)
  38250. {
  38251. if (wt.a > this.scaleMax.x)
  38252. {
  38253. wt.a = this.scaleMax.x;
  38254. }
  38255. if (wt.d > this.scaleMax.y)
  38256. {
  38257. wt.d = this.scaleMax.y;
  38258. }
  38259. }
  38260. },
  38261. /**
  38262. * Sets the scaleMin and scaleMax values. These values are used to limit how far this Game Object will scale based on its parent.
  38263. *
  38264. * For example if this Game Object has a `minScale` value of 1 and its parent has a `scale` value of 0.5, the 0.5 will be ignored
  38265. * and the scale value of 1 will be used, as the parents scale is lower than the minimum scale this Game Object should adhere to.
  38266. *
  38267. * By setting these values you can carefully control how Game Objects deal with responsive scaling.
  38268. *
  38269. * If only one parameter is given then that value will be used for both scaleMin and scaleMax:
  38270. * `setScaleMinMax(1)` = scaleMin.x, scaleMin.y, scaleMax.x and scaleMax.y all = 1
  38271. *
  38272. * If only two parameters are given the first is set as scaleMin.x and y and the second as scaleMax.x and y:
  38273. * `setScaleMinMax(0.5, 2)` = scaleMin.x and y = 0.5 and scaleMax.x and y = 2
  38274. *
  38275. * If you wish to set `scaleMin` with different values for x and y then either modify Game Object.scaleMin directly,
  38276. * or pass `null` for the `maxX` and `maxY` parameters.
  38277. *
  38278. * Call `setScaleMinMax(null)` to clear all previously set values.
  38279. *
  38280. * @method
  38281. * @param {number|null} minX - The minimum horizontal scale value this Game Object can scale down to.
  38282. * @param {number|null} minY - The minimum vertical scale value this Game Object can scale down to.
  38283. * @param {number|null} maxX - The maximum horizontal scale value this Game Object can scale up to.
  38284. * @param {number|null} maxY - The maximum vertical scale value this Game Object can scale up to.
  38285. */
  38286. setScaleMinMax: function (minX, minY, maxX, maxY) {
  38287. if (minY === undefined)
  38288. {
  38289. // 1 parameter, set all to it
  38290. minY = maxX = maxY = minX;
  38291. }
  38292. else if (maxX === undefined)
  38293. {
  38294. // 2 parameters, the first is min, the second max
  38295. maxX = maxY = minY;
  38296. minY = minX;
  38297. }
  38298. if (minX === null)
  38299. {
  38300. this.scaleMin = null;
  38301. }
  38302. else
  38303. {
  38304. if (this.scaleMin)
  38305. {
  38306. this.scaleMin.set(minX, minY);
  38307. }
  38308. else
  38309. {
  38310. this.scaleMin = new Phaser.Point(minX, minY);
  38311. }
  38312. }
  38313. if (maxX === null)
  38314. {
  38315. this.scaleMax = null;
  38316. }
  38317. else
  38318. {
  38319. if (this.scaleMax)
  38320. {
  38321. this.scaleMax.set(maxX, maxY);
  38322. }
  38323. else
  38324. {
  38325. this.scaleMax = new Phaser.Point(maxX, maxY);
  38326. }
  38327. }
  38328. if (this.scaleMin === null)
  38329. {
  38330. this.transformCallback = null;
  38331. }
  38332. else
  38333. {
  38334. this.transformCallback = this.checkTransform;
  38335. this.transformCallbackContext = this;
  38336. }
  38337. }
  38338. };
  38339. /**
  38340. * @author Richard Davey <rich@photonstorm.com>
  38341. * @copyright 2016 Photon Storm Ltd.
  38342. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  38343. */
  38344. /**
  38345. * The Smoothed component allows a Game Object to control anti-aliasing of an image based texture.
  38346. *
  38347. * @class
  38348. */
  38349. Phaser.Component.Smoothed = function () {};
  38350. Phaser.Component.Smoothed.prototype = {
  38351. /**
  38352. * Enable or disable texture smoothing for this Game Object.
  38353. *
  38354. * It only takes effect if the Game Object is using an image based texture.
  38355. *
  38356. * Smoothing is enabled by default.
  38357. *
  38358. * @property {boolean} smoothed
  38359. */
  38360. smoothed: {
  38361. get: function () {
  38362. return !this.texture.baseTexture.scaleMode;
  38363. },
  38364. set: function (value) {
  38365. if (value)
  38366. {
  38367. if (this.texture)
  38368. {
  38369. this.texture.baseTexture.scaleMode = 0;
  38370. }
  38371. }
  38372. else
  38373. {
  38374. if (this.texture)
  38375. {
  38376. this.texture.baseTexture.scaleMode = 1;
  38377. }
  38378. }
  38379. }
  38380. }
  38381. };
  38382. /**
  38383. * @author Richard Davey <rich@photonstorm.com>
  38384. * @copyright 2016 Photon Storm Ltd.
  38385. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  38386. */
  38387. /**
  38388. * The GameObjectFactory is a quick way to create many common game objects
  38389. * using {@linkcode Phaser.Game#add `game.add`}.
  38390. *
  38391. * Created objects are _automatically added_ to the appropriate Manager, World, or manually specified parent Group.
  38392. *
  38393. * @class Phaser.GameObjectFactory
  38394. * @constructor
  38395. * @param {Phaser.Game} game - A reference to the currently running game.
  38396. */
  38397. Phaser.GameObjectFactory = function (game) {
  38398. /**
  38399. * @property {Phaser.Game} game - A reference to the currently running Game.
  38400. * @protected
  38401. */
  38402. this.game = game;
  38403. /**
  38404. * @property {Phaser.World} world - A reference to the game world.
  38405. * @protected
  38406. */
  38407. this.world = this.game.world;
  38408. };
  38409. Phaser.GameObjectFactory.prototype = {
  38410. /**
  38411. * Adds an existing display object to the game world.
  38412. *
  38413. * @method Phaser.GameObjectFactory#existing
  38414. * @param {any} object - An instance of Phaser.Sprite, Phaser.Button or any other display object.
  38415. * @return {any} The child that was added to the World.
  38416. */
  38417. existing: function (object) {
  38418. return this.world.add(object);
  38419. },
  38420. /**
  38421. * Create a new `Image` object.
  38422. *
  38423. * An Image is a light-weight object you can use to display anything that doesn't need physics or animation.
  38424. *
  38425. * It can still rotate, scale, crop and receive input events.
  38426. * This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics.
  38427. *
  38428. * @method Phaser.GameObjectFactory#image
  38429. * @param {number} [x=0] - The x coordinate of the Image. The coordinate is relative to any parent container this Image may be in.
  38430. * @param {number} [y=0] - The y coordinate of the Image. The coordinate is relative to any parent container this Image may be in.
  38431. * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by this display object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture.
  38432. * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name.
  38433. * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
  38434. * @returns {Phaser.Image} The newly created Image object.
  38435. */
  38436. image: function (x, y, key, frame, group) {
  38437. if (group === undefined) { group = this.world; }
  38438. return group.add(new Phaser.Image(this.game, x, y, key, frame));
  38439. },
  38440. /**
  38441. * Create a new Sprite with specific position and sprite sheet key.
  38442. *
  38443. * At its most basic a Sprite consists of a set of coordinates and a texture that is used when rendered.
  38444. * They also contain additional properties allowing for physics motion (via Sprite.body), input handling (via Sprite.input),
  38445. * events (via Sprite.events), animation (via Sprite.animations), camera culling and more. Please see the Examples for use cases.
  38446. *
  38447. * @method Phaser.GameObjectFactory#sprite
  38448. * @param {number} [x=0] - The x coordinate of the sprite. The coordinate is relative to any parent container this sprite may be in.
  38449. * @param {number} [y=0] - The y coordinate of the sprite. The coordinate is relative to any parent container this sprite may be in.
  38450. * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by this display object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture.
  38451. * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name.
  38452. * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
  38453. * @returns {Phaser.Sprite} The newly created Sprite object.
  38454. */
  38455. sprite: function (x, y, key, frame, group) {
  38456. if (group === undefined) { group = this.world; }
  38457. return group.create(x, y, key, frame);
  38458. },
  38459. /**
  38460. * Create a new Creature Animation object.
  38461. *
  38462. * Creature is a custom Game Object used in conjunction with the Creature Runtime libraries by Kestrel Moon Studios.
  38463. *
  38464. * It allows you to display animated Game Objects that were created with the [Creature Automated Animation Tool](http://www.kestrelmoon.com/creature/).
  38465. *
  38466. * Note 1: You can only use Phaser.Creature objects in WebGL enabled games. They do not work in Canvas mode games.
  38467. *
  38468. * Note 2: You must use a build of Phaser that includes the CreatureMeshBone.js runtime and gl-matrix.js, or have them
  38469. * loaded before your Phaser game boots.
  38470. *
  38471. * See the Phaser custom build process for more details.
  38472. *
  38473. * @method Phaser.GameObjectFactory#creature
  38474. * @param {number} [x=0] - The x coordinate of the creature. The coordinate is relative to any parent container this creature may be in.
  38475. * @param {number} [y=0] - The y coordinate of the creature. The coordinate is relative to any parent container this creature may be in.
  38476. * @param {string|PIXI.Texture} [key] - The image used as a texture by this creature object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a PIXI.Texture.
  38477. * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
  38478. * @returns {Phaser.Creature} The newly created Sprite object.
  38479. */
  38480. creature: function (x, y, key, mesh, group) {
  38481. if (group === undefined) { group = this.world; }
  38482. var obj = new Phaser.Creature(this.game, x, y, key, mesh);
  38483. group.add(obj);
  38484. return obj;
  38485. },
  38486. /**
  38487. * Create a tween on a specific object.
  38488. *
  38489. * The object can be any JavaScript object or Phaser object such as Sprite.
  38490. *
  38491. * @method Phaser.GameObjectFactory#tween
  38492. * @param {object} object - Object the tween will be run on.
  38493. * @return {Phaser.Tween} The newly created Phaser.Tween object.
  38494. */
  38495. tween: function (object) {
  38496. return this.game.tweens.create(object);
  38497. },
  38498. /**
  38499. * A Group is a container for display objects that allows for fast pooling, recycling and collision checks.
  38500. *
  38501. * @method Phaser.GameObjectFactory#group
  38502. * @param {any} [parent] - The parent Group or DisplayObjectContainer that will hold this group, if any. If set to null the Group won't be added to the display list. If undefined it will be added to World by default.
  38503. * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging.
  38504. * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World.
  38505. * @param {boolean} [enableBody=false] - If true all Sprites created with `Group.create` or `Group.createMulitple` will have a physics body created on them. Change the body type with physicsBodyType.
  38506. * @param {number} [physicsBodyType=0] - If enableBody is true this is the type of physics body that is created on new Sprites. Phaser.Physics.ARCADE, Phaser.Physics.P2, Phaser.Physics.NINJA, etc.
  38507. * @return {Phaser.Group} The newly created Group.
  38508. */
  38509. group: function (parent, name, addToStage, enableBody, physicsBodyType) {
  38510. return new Phaser.Group(this.game, parent, name, addToStage, enableBody, physicsBodyType);
  38511. },
  38512. /**
  38513. * A Group is a container for display objects that allows for fast pooling, recycling and collision checks.
  38514. *
  38515. * A Physics Group is the same as an ordinary Group except that is has enableBody turned on by default, so any Sprites it creates
  38516. * are automatically given a physics body.
  38517. *
  38518. * @method Phaser.GameObjectFactory#physicsGroup
  38519. * @param {number} [physicsBodyType=Phaser.Physics.ARCADE] - If enableBody is true this is the type of physics body that is created on new Sprites. Phaser.Physics.ARCADE, Phaser.Physics.P2JS, Phaser.Physics.NINJA, etc.
  38520. * @param {any} [parent] - The parent Group or DisplayObjectContainer that will hold this group, if any. If set to null the Group won't be added to the display list. If undefined it will be added to World by default.
  38521. * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging.
  38522. * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World.
  38523. * @return {Phaser.Group} The newly created Group.
  38524. */
  38525. physicsGroup: function (physicsBodyType, parent, name, addToStage) {
  38526. return new Phaser.Group(this.game, parent, name, addToStage, true, physicsBodyType);
  38527. },
  38528. /**
  38529. * A SpriteBatch is a really fast version of a Phaser Group built solely for speed.
  38530. * Use when you need a lot of sprites or particles all sharing the same texture.
  38531. * The speed gains are specifically for WebGL. In Canvas mode you won't see any real difference.
  38532. *
  38533. * @method Phaser.GameObjectFactory#spriteBatch
  38534. * @param {Phaser.Group|null} parent - The parent Group that will hold this Sprite Batch. Set to `undefined` or `null` to add directly to game.world.
  38535. * @param {string} [name='group'] - A name for this Sprite Batch. Not used internally but useful for debugging.
  38536. * @param {boolean} [addToStage=false] - If set to true this Sprite Batch will be added directly to the Game.Stage instead of the parent.
  38537. * @return {Phaser.SpriteBatch} The newly created Sprite Batch.
  38538. */
  38539. spriteBatch: function (parent, name, addToStage) {
  38540. if (parent === undefined) { parent = null; }
  38541. if (name === undefined) { name = 'group'; }
  38542. if (addToStage === undefined) { addToStage = false; }
  38543. return new Phaser.SpriteBatch(this.game, parent, name, addToStage);
  38544. },
  38545. /**
  38546. * Creates a new Sound object.
  38547. *
  38548. * @method Phaser.GameObjectFactory#audio
  38549. * @param {string} key - The Game.cache key of the sound that this object will use.
  38550. * @param {number} [volume=1] - The volume at which the sound will be played.
  38551. * @param {boolean} [loop=false] - Whether or not the sound will loop.
  38552. * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio.
  38553. * @return {Phaser.Sound} The newly created sound object.
  38554. */
  38555. audio: function (key, volume, loop, connect) {
  38556. return this.game.sound.add(key, volume, loop, connect);
  38557. },
  38558. /**
  38559. * Creates a new Sound object.
  38560. *
  38561. * @method Phaser.GameObjectFactory#sound
  38562. * @param {string} key - The Game.cache key of the sound that this object will use.
  38563. * @param {number} [volume=1] - The volume at which the sound will be played.
  38564. * @param {boolean} [loop=false] - Whether or not the sound will loop.
  38565. * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio.
  38566. * @return {Phaser.Sound} The newly created sound object.
  38567. */
  38568. sound: function (key, volume, loop, connect) {
  38569. return this.game.sound.add(key, volume, loop, connect);
  38570. },
  38571. /**
  38572. * Creates a new AudioSprite object.
  38573. *
  38574. * @method Phaser.GameObjectFactory#audioSprite
  38575. * @param {string} key - The Game.cache key of the sound that this object will use.
  38576. * @return {Phaser.AudioSprite} The newly created AudioSprite object.
  38577. */
  38578. audioSprite: function (key) {
  38579. return this.game.sound.addSprite(key);
  38580. },
  38581. /**
  38582. * Creates a new TileSprite object.
  38583. *
  38584. * @method Phaser.GameObjectFactory#tileSprite
  38585. * @param {number} x - The x coordinate of the TileSprite. The coordinate is relative to any parent container this TileSprite may be in.
  38586. * @param {number} y - The y coordinate of the TileSprite. The coordinate is relative to any parent container this TileSprite may be in.
  38587. * @param {number} width - The width of the TileSprite.
  38588. * @param {number} height - The height of the TileSprite.
  38589. * @param {string|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Phaser Image Cache entry, or an instance of a PIXI.Texture or BitmapData.
  38590. * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name.
  38591. * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
  38592. * @return {Phaser.TileSprite} The newly created TileSprite object.
  38593. */
  38594. tileSprite: function (x, y, width, height, key, frame, group) {
  38595. if (group === undefined) { group = this.world; }
  38596. return group.add(new Phaser.TileSprite(this.game, x, y, width, height, key, frame));
  38597. },
  38598. /**
  38599. * Creates a new Rope object.
  38600. *
  38601. * Example usage: https://github.com/codevinsky/phaser-rope-demo/blob/master/dist/demo.js
  38602. *
  38603. * @method Phaser.GameObjectFactory#rope
  38604. * @param {number} [x=0] - The x coordinate of the Rope. The coordinate is relative to any parent container this rope may be in.
  38605. * @param {number} [y=0] - The y coordinate of the Rope. The coordinate is relative to any parent container this rope may be in.
  38606. * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by this display object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture.
  38607. * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name.
  38608. * @param {Array} points - An array of {Phaser.Point}.
  38609. * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
  38610. * @return {Phaser.Rope} The newly created Rope object.
  38611. */
  38612. rope: function (x, y, key, frame, points, group) {
  38613. if (group === undefined) { group = this.world; }
  38614. return group.add(new Phaser.Rope(this.game, x, y, key, frame, points));
  38615. },
  38616. /**
  38617. * Creates a new Text object.
  38618. *
  38619. * @method Phaser.GameObjectFactory#text
  38620. * @param {number} [x=0] - The x coordinate of the Text. The coordinate is relative to any parent container this text may be in.
  38621. * @param {number} [y=0] - The y coordinate of the Text. The coordinate is relative to any parent container this text may be in.
  38622. * @param {string} [text=''] - The text string that will be displayed.
  38623. * @param {object} [style] - The style object containing style attributes like font, font size , etc.
  38624. * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
  38625. * @return {Phaser.Text} The newly created text object.
  38626. */
  38627. text: function (x, y, text, style, group) {
  38628. if (group === undefined) { group = this.world; }
  38629. return group.add(new Phaser.Text(this.game, x, y, text, style));
  38630. },
  38631. /**
  38632. * Creates a new Button object.
  38633. *
  38634. * @method Phaser.GameObjectFactory#button
  38635. * @param {number} [x=0] - The x coordinate of the Button. The coordinate is relative to any parent container this button may be in.
  38636. * @param {number} [y=0] - The y coordinate of the Button. The coordinate is relative to any parent container this button may be in.
  38637. * @param {string} [key] - The image key as defined in the Game.Cache to use as the texture for this button.
  38638. * @param {function} [callback] - The function to call when this button is pressed
  38639. * @param {object} [callbackContext] - The context in which the callback will be called (usually 'this')
  38640. * @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.
  38641. * @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.
  38642. * @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.
  38643. * @param {string|number} [upFrame] - This is the frame or frameName that will be set when this button is in an up state. Give either a number to use a frame ID or a string for a frame name.
  38644. * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
  38645. * @return {Phaser.Button} The newly created Button object.
  38646. */
  38647. button: function (x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame, group) {
  38648. if (group === undefined) { group = this.world; }
  38649. return group.add(new Phaser.Button(this.game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame));
  38650. },
  38651. /**
  38652. * Creates a new Graphics object.
  38653. *
  38654. * @method Phaser.GameObjectFactory#graphics
  38655. * @param {number} [x=0] - The x coordinate of the Graphic. The coordinate is relative to any parent container this object may be in.
  38656. * @param {number} [y=0] - The y coordinate of the Graphic. The coordinate is relative to any parent container this object may be in.
  38657. * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
  38658. * @return {Phaser.Graphics} The newly created graphics object.
  38659. */
  38660. graphics: function (x, y, group) {
  38661. if (group === undefined) { group = this.world; }
  38662. return group.add(new Phaser.Graphics(this.game, x, y));
  38663. },
  38664. /**
  38665. * Create a new Emitter.
  38666. *
  38667. * A particle emitter can be used for one-time explosions or for
  38668. * continuous effects like rain and fire. All it really does is launch Particle objects out
  38669. * at set intervals, and fixes their positions and velocities accordingly.
  38670. *
  38671. * @method Phaser.GameObjectFactory#emitter
  38672. * @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from.
  38673. * @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from.
  38674. * @param {number} [maxParticles=50] - The total number of particles in this emitter.
  38675. * @return {Phaser.Particles.Arcade.Emitter} The newly created emitter object.
  38676. */
  38677. emitter: function (x, y, maxParticles) {
  38678. return this.game.particles.add(new Phaser.Particles.Arcade.Emitter(this.game, x, y, maxParticles));
  38679. },
  38680. /**
  38681. * Create a new RetroFont object.
  38682. *
  38683. * A RetroFont can be used as a texture for an Image or Sprite and optionally add it to the Cache.
  38684. * A RetroFont uses a bitmap which contains fixed with characters for the font set. You use character spacing to define the set.
  38685. * If you need variable width character support then use a BitmapText object instead. The main difference between a RetroFont and a BitmapText
  38686. * is that a RetroFont creates a single texture that you can apply to a game object, where-as a BitmapText creates one Sprite object per letter of text.
  38687. * The texture can be asssigned or one or multiple images/sprites, but note that the text the RetroFont uses will be shared across them all,
  38688. * i.e. if you need each Image to have different text in it, then you need to create multiple RetroFont objects.
  38689. *
  38690. * @method Phaser.GameObjectFactory#retroFont
  38691. * @param {string} font - The key of the image in the Game.Cache that the RetroFont will use.
  38692. * @param {number} characterWidth - The width of each character in the font set.
  38693. * @param {number} characterHeight - The height of each character in the font set.
  38694. * @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements.
  38695. * @param {number} charsPerRow - The number of characters per row in the font set.
  38696. * @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here.
  38697. * @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here.
  38698. * @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here.
  38699. * @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here.
  38700. * @return {Phaser.RetroFont} The newly created RetroFont texture which can be applied to an Image or Sprite.
  38701. */
  38702. retroFont: function (font, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset) {
  38703. return new Phaser.RetroFont(this.game, font, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset);
  38704. },
  38705. /**
  38706. * Create a new BitmapText object.
  38707. *
  38708. * BitmapText objects work by taking a texture file and an XML file that describes the font structure.
  38709. * It then generates a new Sprite object for each letter of the text, proportionally spaced out and aligned to
  38710. * match the font structure.
  38711. *
  38712. * BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability
  38713. * to use Web Fonts. However you trade this flexibility for pure rendering speed. You can also create visually compelling BitmapTexts by
  38714. * processing the font texture in an image editor first, applying fills and any other effects required.
  38715. *
  38716. * To create multi-line text insert \r, \n or \r\n escape codes into the text string.
  38717. *
  38718. * To create a BitmapText data files you can use:
  38719. *
  38720. * BMFont (Windows, free): http://www.angelcode.com/products/bmfont/
  38721. * Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner
  38722. * Littera (Web-based, free): http://kvazars.com/littera/
  38723. *
  38724. * @method Phaser.GameObjectFactory#bitmapText
  38725. * @param {number} x - X coordinate to display the BitmapText object at.
  38726. * @param {number} y - Y coordinate to display the BitmapText object at.
  38727. * @param {string} font - The key of the BitmapText as stored in Phaser.Cache.
  38728. * @param {string} [text=''] - The text that will be rendered. This can also be set later via BitmapText.text.
  38729. * @param {number} [size=32] - The size the font will be rendered at in pixels.
  38730. * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
  38731. * @return {Phaser.BitmapText} The newly created bitmapText object.
  38732. */
  38733. bitmapText: function (x, y, font, text, size, group) {
  38734. if (group === undefined) { group = this.world; }
  38735. return group.add(new Phaser.BitmapText(this.game, x, y, font, text, size));
  38736. },
  38737. /**
  38738. * Creates a new Phaser.Tilemap object.
  38739. *
  38740. * The map can either be populated with data from a Tiled JSON file or from a CSV file.
  38741. * To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key.
  38742. * When using CSV data you must provide the key and the tileWidth and tileHeight parameters.
  38743. * If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here.
  38744. * Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it.
  38745. *
  38746. * @method Phaser.GameObjectFactory#tilemap
  38747. * @param {string} [key] - The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`.
  38748. * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
  38749. * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
  38750. * @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this.
  38751. * @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this.
  38752. * @return {Phaser.Tilemap} The newly created tilemap object.
  38753. */
  38754. tilemap: function (key, tileWidth, tileHeight, width, height) {
  38755. return new Phaser.Tilemap(this.game, key, tileWidth, tileHeight, width, height);
  38756. },
  38757. /**
  38758. * A dynamic initially blank canvas to which images can be drawn.
  38759. *
  38760. * @method Phaser.GameObjectFactory#renderTexture
  38761. * @param {number} [width=100] - the width of the RenderTexture.
  38762. * @param {number} [height=100] - the height of the RenderTexture.
  38763. * @param {string} [key=''] - Asset key for the RenderTexture when stored in the Cache (see addToCache parameter).
  38764. * @param {boolean} [addToCache=false] - Should this RenderTexture be added to the Game.Cache? If so you can retrieve it with Cache.getTexture(key)
  38765. * @return {Phaser.RenderTexture} The newly created RenderTexture object.
  38766. */
  38767. renderTexture: function (width, height, key, addToCache) {
  38768. if (key === undefined || key === '') { key = this.game.rnd.uuid(); }
  38769. if (addToCache === undefined) { addToCache = false; }
  38770. var texture = new Phaser.RenderTexture(this.game, width, height, key);
  38771. if (addToCache)
  38772. {
  38773. this.game.cache.addRenderTexture(key, texture);
  38774. }
  38775. return texture;
  38776. },
  38777. /**
  38778. * Create a Video object.
  38779. *
  38780. * This will return a Phaser.Video object which you can pass to a Sprite to be used as a texture.
  38781. *
  38782. * @method Phaser.GameObjectFactory#video
  38783. * @param {string|null} [key=null] - The key of the video file in the Phaser.Cache that this Video object will play. Set to `null` or leave undefined if you wish to use a webcam as the source. See `startMediaStream` to start webcam capture.
  38784. * @param {string|null} [url=null] - If the video hasn't been loaded then you can provide a full URL to the file here (make sure to set key to null)
  38785. * @return {Phaser.Video} The newly created Video object.
  38786. */
  38787. video: function (key, url) {
  38788. return new Phaser.Video(this.game, key, url);
  38789. },
  38790. /**
  38791. * Create a BitmapData object.
  38792. *
  38793. * A BitmapData object can be manipulated and drawn to like a traditional Canvas object and used to texture Sprites.
  38794. *
  38795. * @method Phaser.GameObjectFactory#bitmapData
  38796. * @param {number} [width=256] - The width of the BitmapData in pixels.
  38797. * @param {number} [height=256] - The height of the BitmapData in pixels.
  38798. * @param {string} [key=''] - Asset key for the BitmapData when stored in the Cache (see addToCache parameter).
  38799. * @param {boolean} [addToCache=false] - Should this BitmapData be added to the Game.Cache? If so you can retrieve it with Cache.getBitmapData(key)
  38800. * @return {Phaser.BitmapData} The newly created BitmapData object.
  38801. */
  38802. bitmapData: function (width, height, key, addToCache) {
  38803. if (addToCache === undefined) { addToCache = false; }
  38804. if (key === undefined || key === '') { key = this.game.rnd.uuid(); }
  38805. var texture = new Phaser.BitmapData(this.game, key, width, height);
  38806. if (addToCache)
  38807. {
  38808. this.game.cache.addBitmapData(key, texture);
  38809. }
  38810. return texture;
  38811. },
  38812. /**
  38813. * A WebGL shader/filter that can be applied to Sprites.
  38814. *
  38815. * @method Phaser.GameObjectFactory#filter
  38816. * @param {string} filter - The name of the filter you wish to create, for example HueRotate or SineWave.
  38817. * @param {any} - Whatever parameters are needed to be passed to the filter init function.
  38818. * @return {Phaser.Filter} The newly created Phaser.Filter object.
  38819. */
  38820. filter: function (filter) {
  38821. var args = Array.prototype.slice.call(arguments, 1);
  38822. var filter = new Phaser.Filter[filter](this.game);
  38823. filter.init.apply(filter, args);
  38824. return filter;
  38825. },
  38826. /**
  38827. * Add a new Plugin into the PluginManager.
  38828. *
  38829. * The Plugin must have 2 properties: `game` and `parent`. Plugin.game is set to the game reference the PluginManager uses, and parent is set to the PluginManager.
  38830. *
  38831. * @method Phaser.GameObjectFactory#plugin
  38832. * @param {object|Phaser.Plugin} plugin - The Plugin to add into the PluginManager. This can be a function or an existing object.
  38833. * @param {...*} parameter - Additional parameters that will be passed to the Plugin.init method.
  38834. * @return {Phaser.Plugin} The Plugin that was added to the manager.
  38835. */
  38836. plugin: function (plugin) {
  38837. return this.game.plugins.add(plugin);
  38838. }
  38839. };
  38840. Phaser.GameObjectFactory.prototype.constructor = Phaser.GameObjectFactory;
  38841. /**
  38842. * @author Richard Davey <rich@photonstorm.com>
  38843. * @copyright 2016 Photon Storm Ltd.
  38844. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  38845. */
  38846. /**
  38847. * The GameObjectCreator is a quick way to create common game objects _without_ adding them to the game world.
  38848. * The object creator can be accessed with {@linkcode Phaser.Game#make `game.make`}.
  38849. *
  38850. * @class Phaser.GameObjectCreator
  38851. * @constructor
  38852. * @param {Phaser.Game} game - A reference to the currently running game.
  38853. */
  38854. Phaser.GameObjectCreator = function (game) {
  38855. /**
  38856. * @property {Phaser.Game} game - A reference to the currently running Game.
  38857. * @protected
  38858. */
  38859. this.game = game;
  38860. /**
  38861. * @property {Phaser.World} world - A reference to the game world.
  38862. * @protected
  38863. */
  38864. this.world = this.game.world;
  38865. };
  38866. Phaser.GameObjectCreator.prototype = {
  38867. /**
  38868. * Create a new Image object.
  38869. *
  38870. * An Image is a light-weight object you can use to display anything that doesn't need physics or animation.
  38871. * It can still rotate, scale, crop and receive input events. This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics.
  38872. *
  38873. * @method Phaser.GameObjectCreator#image
  38874. * @param {number} x - X position of the image.
  38875. * @param {number} y - Y position of the image.
  38876. * @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.
  38877. * @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.
  38878. * @returns {Phaser.Image} the newly created sprite object.
  38879. */
  38880. image: function (x, y, key, frame) {
  38881. return new Phaser.Image(this.game, x, y, key, frame);
  38882. },
  38883. /**
  38884. * Create a new Sprite with specific position and sprite sheet key.
  38885. *
  38886. * @method Phaser.GameObjectCreator#sprite
  38887. * @param {number} x - X position of the new sprite.
  38888. * @param {number} y - Y position of the new sprite.
  38889. * @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.
  38890. * @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.
  38891. * @returns {Phaser.Sprite} the newly created sprite object.
  38892. */
  38893. sprite: function (x, y, key, frame) {
  38894. return new Phaser.Sprite(this.game, x, y, key, frame);
  38895. },
  38896. /**
  38897. * Create a tween object for a specific object.
  38898. *
  38899. * The object can be any JavaScript object or Phaser object such as Sprite.
  38900. *
  38901. * @method Phaser.GameObjectCreator#tween
  38902. * @param {object} obj - Object the tween will be run on.
  38903. * @return {Phaser.Tween} The Tween object.
  38904. */
  38905. tween: function (obj) {
  38906. return new Phaser.Tween(obj, this.game, this.game.tweens);
  38907. },
  38908. /**
  38909. * A Group is a container for display objects that allows for fast pooling, recycling and collision checks.
  38910. *
  38911. * @method Phaser.GameObjectCreator#group
  38912. * @param {any} parent - The parent Group or DisplayObjectContainer that will hold this group, if any.
  38913. * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging.
  38914. * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World.
  38915. * @param {boolean} [enableBody=false] - If true all Sprites created with `Group.create` or `Group.createMulitple` will have a physics body created on them. Change the body type with physicsBodyType.
  38916. * @param {number} [physicsBodyType=0] - If enableBody is true this is the type of physics body that is created on new Sprites. Phaser.Physics.ARCADE, Phaser.Physics.P2, Phaser.Physics.NINJA, etc.
  38917. * @return {Phaser.Group} The newly created Group.
  38918. */
  38919. group: function (parent, name, addToStage, enableBody, physicsBodyType) {
  38920. return new Phaser.Group(this.game, parent, name, addToStage, enableBody, physicsBodyType);
  38921. },
  38922. /**
  38923. * Create a new SpriteBatch.
  38924. *
  38925. * @method Phaser.GameObjectCreator#spriteBatch
  38926. * @param {any} parent - The parent Group or DisplayObjectContainer that will hold this group, if any.
  38927. * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging.
  38928. * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World.
  38929. * @return {Phaser.SpriteBatch} The newly created group.
  38930. */
  38931. spriteBatch: function (parent, name, addToStage) {
  38932. if (name === undefined) { name = 'group'; }
  38933. if (addToStage === undefined) { addToStage = false; }
  38934. return new Phaser.SpriteBatch(this.game, parent, name, addToStage);
  38935. },
  38936. /**
  38937. * Creates a new Sound object.
  38938. *
  38939. * @method Phaser.GameObjectCreator#audio
  38940. * @param {string} key - The Game.cache key of the sound that this object will use.
  38941. * @param {number} [volume=1] - The volume at which the sound will be played.
  38942. * @param {boolean} [loop=false] - Whether or not the sound will loop.
  38943. * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio.
  38944. * @return {Phaser.Sound} The newly created text object.
  38945. */
  38946. audio: function (key, volume, loop, connect) {
  38947. return this.game.sound.add(key, volume, loop, connect);
  38948. },
  38949. /**
  38950. * Creates a new AudioSprite object.
  38951. *
  38952. * @method Phaser.GameObjectCreator#audioSprite
  38953. * @param {string} key - The Game.cache key of the sound that this object will use.
  38954. * @return {Phaser.AudioSprite} The newly created AudioSprite object.
  38955. */
  38956. audioSprite: function (key) {
  38957. return this.game.sound.addSprite(key);
  38958. },
  38959. /**
  38960. * Creates a new Sound object.
  38961. *
  38962. * @method Phaser.GameObjectCreator#sound
  38963. * @param {string} key - The Game.cache key of the sound that this object will use.
  38964. * @param {number} [volume=1] - The volume at which the sound will be played.
  38965. * @param {boolean} [loop=false] - Whether or not the sound will loop.
  38966. * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio.
  38967. * @return {Phaser.Sound} The newly created text object.
  38968. */
  38969. sound: function (key, volume, loop, connect) {
  38970. return this.game.sound.add(key, volume, loop, connect);
  38971. },
  38972. /**
  38973. * Creates a new TileSprite object.
  38974. *
  38975. * @method Phaser.GameObjectCreator#tileSprite
  38976. * @param {number} x - The x coordinate (in world space) to position the TileSprite at.
  38977. * @param {number} y - The y coordinate (in world space) to position the TileSprite at.
  38978. * @param {number} width - The width of the TileSprite.
  38979. * @param {number} height - The height of the TileSprite.
  38980. * @param {string|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Phaser Image Cache entry, or an instance of a PIXI.Texture or BitmapData.
  38981. * @param {string|number} frame - If this TileSprite 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.
  38982. * @return {Phaser.TileSprite} The newly created tileSprite object.
  38983. */
  38984. tileSprite: function (x, y, width, height, key, frame) {
  38985. return new Phaser.TileSprite(this.game, x, y, width, height, key, frame);
  38986. },
  38987. /**
  38988. * Creates a new Rope object.
  38989. *
  38990. * @method Phaser.GameObjectCreator#rope
  38991. * @param {number} x - The x coordinate (in world space) to position the Rope at.
  38992. * @param {number} y - The y coordinate (in world space) to position the Rope at.
  38993. * @param {number} width - The width of the Rope.
  38994. * @param {number} height - The height of the Rope.
  38995. * @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture.
  38996. * @param {string|number} frame - If this Rope 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.
  38997. * @return {Phaser.Rope} The newly created rope object.
  38998. */
  38999. rope: function (x, y, key, frame, points) {
  39000. return new Phaser.Rope(this.game, x, y, key, frame, points);
  39001. },
  39002. /**
  39003. * Creates a new Text object.
  39004. *
  39005. * @method Phaser.GameObjectCreator#text
  39006. * @param {number} x - X position of the new text object.
  39007. * @param {number} y - Y position of the new text object.
  39008. * @param {string} text - The actual text that will be written.
  39009. * @param {object} style - The style object containing style attributes like font, font size , etc.
  39010. * @return {Phaser.Text} The newly created text object.
  39011. */
  39012. text: function (x, y, text, style) {
  39013. return new Phaser.Text(this.game, x, y, text, style);
  39014. },
  39015. /**
  39016. * Creates a new Button object.
  39017. *
  39018. * @method Phaser.GameObjectCreator#button
  39019. * @param {number} [x] X position of the new button object.
  39020. * @param {number} [y] Y position of the new button object.
  39021. * @param {string} [key] The image key as defined in the Game.Cache to use as the texture for this button.
  39022. * @param {function} [callback] The function to call when this button is pressed
  39023. * @param {object} [callbackContext] The context in which the callback will be called (usually 'this')
  39024. * @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.
  39025. * @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.
  39026. * @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.
  39027. * @param {string|number} [upFrame] This is the frame or frameName that will be set when this button is in an up state. Give either a number to use a frame ID or a string for a frame name.
  39028. * @return {Phaser.Button} The newly created button object.
  39029. */
  39030. button: function (x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame) {
  39031. return new Phaser.Button(this.game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame);
  39032. },
  39033. /**
  39034. * Creates a new Graphics object.
  39035. *
  39036. * @method Phaser.GameObjectCreator#graphics
  39037. * @param {number} [x=0] - X position of the new graphics object.
  39038. * @param {number} [y=0] - Y position of the new graphics object.
  39039. * @return {Phaser.Graphics} The newly created graphics object.
  39040. */
  39041. graphics: function (x, y) {
  39042. return new Phaser.Graphics(this.game, x, y);
  39043. },
  39044. /**
  39045. * Creat a new Emitter.
  39046. *
  39047. * An Emitter is a lightweight particle emitter. It can be used for one-time explosions or for
  39048. * continuous effects like rain and fire. All it really does is launch Particle objects out
  39049. * at set intervals, and fixes their positions and velocities accorindgly.
  39050. *
  39051. * @method Phaser.GameObjectCreator#emitter
  39052. * @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from.
  39053. * @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from.
  39054. * @param {number} [maxParticles=50] - The total number of particles in this emitter.
  39055. * @return {Phaser.Emitter} The newly created emitter object.
  39056. */
  39057. emitter: function (x, y, maxParticles) {
  39058. return new Phaser.Particles.Arcade.Emitter(this.game, x, y, maxParticles);
  39059. },
  39060. /**
  39061. * Create a new RetroFont object.
  39062. *
  39063. * A RetroFont can be used as a texture for an Image or Sprite and optionally add it to the Cache.
  39064. * A RetroFont uses a bitmap which contains fixed with characters for the font set. You use character spacing to define the set.
  39065. * If you need variable width character support then use a BitmapText object instead. The main difference between a RetroFont and a BitmapText
  39066. * is that a RetroFont creates a single texture that you can apply to a game object, where-as a BitmapText creates one Sprite object per letter of text.
  39067. * The texture can be asssigned or one or multiple images/sprites, but note that the text the RetroFont uses will be shared across them all,
  39068. * i.e. if you need each Image to have different text in it, then you need to create multiple RetroFont objects.
  39069. *
  39070. * @method Phaser.GameObjectCreator#retroFont
  39071. * @param {string} font - The key of the image in the Game.Cache that the RetroFont will use.
  39072. * @param {number} characterWidth - The width of each character in the font set.
  39073. * @param {number} characterHeight - The height of each character in the font set.
  39074. * @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements.
  39075. * @param {number} charsPerRow - The number of characters per row in the font set.
  39076. * @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here.
  39077. * @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here.
  39078. * @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here.
  39079. * @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here.
  39080. * @return {Phaser.RetroFont} The newly created RetroFont texture which can be applied to an Image or Sprite.
  39081. */
  39082. retroFont: function (font, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset) {
  39083. return new Phaser.RetroFont(this.game, font, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset);
  39084. },
  39085. /**
  39086. * Create a new BitmapText object.
  39087. *
  39088. * BitmapText objects work by taking a texture file and an XML file that describes the font structure.
  39089. * It then generates a new Sprite object for each letter of the text, proportionally spaced out and aligned to
  39090. * match the font structure.
  39091. *
  39092. * BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability
  39093. * to use Web Fonts. However you trade this flexibility for pure rendering speed. You can also create visually compelling BitmapTexts by
  39094. * processing the font texture in an image editor first, applying fills and any other effects required.
  39095. *
  39096. * To create multi-line text insert \r, \n or \r\n escape codes into the text string.
  39097. *
  39098. * To create a BitmapText data files you can use:
  39099. *
  39100. * BMFont (Windows, free): http://www.angelcode.com/products/bmfont/
  39101. * Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner
  39102. * Littera (Web-based, free): http://kvazars.com/littera/
  39103. *
  39104. * @method Phaser.GameObjectCreator#bitmapText
  39105. * @param {number} x - X coordinate to display the BitmapText object at.
  39106. * @param {number} y - Y coordinate to display the BitmapText object at.
  39107. * @param {string} font - The key of the BitmapText as stored in Phaser.Cache.
  39108. * @param {string} [text=''] - The text that will be rendered. This can also be set later via BitmapText.text.
  39109. * @param {number} [size=32] - The size the font will be rendered at in pixels.
  39110. * @param {string} [align='left'] - The alignment of multi-line text. Has no effect if there is only one line of text.
  39111. * @return {Phaser.BitmapText} The newly created bitmapText object.
  39112. */
  39113. bitmapText: function (x, y, font, text, size, align) {
  39114. return new Phaser.BitmapText(this.game, x, y, font, text, size, align);
  39115. },
  39116. /**
  39117. * Creates a new Phaser.Tilemap object.
  39118. *
  39119. * The map can either be populated with data from a Tiled JSON file or from a CSV file.
  39120. * To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key.
  39121. * When using CSV data you must provide the key and the tileWidth and tileHeight parameters.
  39122. * If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here.
  39123. * Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it.
  39124. *
  39125. * @method Phaser.GameObjectCreator#tilemap
  39126. * @param {string} [key] - The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`.
  39127. * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
  39128. * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
  39129. * @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this.
  39130. * @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this.
  39131. */
  39132. tilemap: function (key, tileWidth, tileHeight, width, height) {
  39133. return new Phaser.Tilemap(this.game, key, tileWidth, tileHeight, width, height);
  39134. },
  39135. /**
  39136. * A dynamic initially blank canvas to which images can be drawn.
  39137. *
  39138. * @method Phaser.GameObjectCreator#renderTexture
  39139. * @param {number} [width=100] - the width of the RenderTexture.
  39140. * @param {number} [height=100] - the height of the RenderTexture.
  39141. * @param {string} [key=''] - Asset key for the RenderTexture when stored in the Cache (see addToCache parameter).
  39142. * @param {boolean} [addToCache=false] - Should this RenderTexture be added to the Game.Cache? If so you can retrieve it with Cache.getTexture(key)
  39143. * @return {Phaser.RenderTexture} The newly created RenderTexture object.
  39144. */
  39145. renderTexture: function (width, height, key, addToCache) {
  39146. if (key === undefined || key === '') { key = this.game.rnd.uuid(); }
  39147. if (addToCache === undefined) { addToCache = false; }
  39148. var texture = new Phaser.RenderTexture(this.game, width, height, key);
  39149. if (addToCache)
  39150. {
  39151. this.game.cache.addRenderTexture(key, texture);
  39152. }
  39153. return texture;
  39154. },
  39155. /**
  39156. * Create a BitmpaData object.
  39157. *
  39158. * A BitmapData object can be manipulated and drawn to like a traditional Canvas object and used to texture Sprites.
  39159. *
  39160. * @method Phaser.GameObjectCreator#bitmapData
  39161. * @param {number} [width=256] - The width of the BitmapData in pixels.
  39162. * @param {number} [height=256] - The height of the BitmapData in pixels.
  39163. * @param {string} [key=''] - Asset key for the BitmapData when stored in the Cache (see addToCache parameter).
  39164. * @param {boolean} [addToCache=false] - Should this BitmapData be added to the Game.Cache? If so you can retrieve it with Cache.getBitmapData(key)
  39165. * @return {Phaser.BitmapData} The newly created BitmapData object.
  39166. */
  39167. bitmapData: function (width, height, key, addToCache) {
  39168. if (addToCache === undefined) { addToCache = false; }
  39169. if (key === undefined || key === '') { key = this.game.rnd.uuid(); }
  39170. var texture = new Phaser.BitmapData(this.game, key, width, height);
  39171. if (addToCache)
  39172. {
  39173. this.game.cache.addBitmapData(key, texture);
  39174. }
  39175. return texture;
  39176. },
  39177. /**
  39178. * A WebGL shader/filter that can be applied to Sprites.
  39179. *
  39180. * @method Phaser.GameObjectCreator#filter
  39181. * @param {string} filter - The name of the filter you wish to create, for example HueRotate or SineWave.
  39182. * @param {any} - Whatever parameters are needed to be passed to the filter init function.
  39183. * @return {Phaser.Filter} The newly created Phaser.Filter object.
  39184. */
  39185. filter: function (filter) {
  39186. var args = Array.prototype.slice.call(arguments, 1);
  39187. var filter = new Phaser.Filter[filter](this.game);
  39188. filter.init.apply(filter, args);
  39189. return filter;
  39190. }
  39191. };
  39192. Phaser.GameObjectCreator.prototype.constructor = Phaser.GameObjectCreator;
  39193. /**
  39194. * @author Richard Davey <rich@photonstorm.com>
  39195. * @copyright 2016 Photon Storm Ltd.
  39196. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  39197. */
  39198. /**
  39199. * Sprites are the lifeblood of your game, used for nearly everything visual.
  39200. *
  39201. * At its most basic a Sprite consists of a set of coordinates and a texture that is rendered to the canvas.
  39202. * They also contain additional properties allowing for physics motion (via Sprite.body), input handling (via Sprite.input),
  39203. * events (via Sprite.events), animation (via Sprite.animations), camera culling and more. Please see the Examples for use cases.
  39204. *
  39205. * @class Phaser.Sprite
  39206. * @constructor
  39207. * @extends PIXI.Sprite
  39208. * @extends Phaser.Component.Core
  39209. * @extends Phaser.Component.Angle
  39210. * @extends Phaser.Component.Animation
  39211. * @extends Phaser.Component.AutoCull
  39212. * @extends Phaser.Component.Bounds
  39213. * @extends Phaser.Component.BringToTop
  39214. * @extends Phaser.Component.Crop
  39215. * @extends Phaser.Component.Delta
  39216. * @extends Phaser.Component.Destroy
  39217. * @extends Phaser.Component.FixedToCamera
  39218. * @extends Phaser.Component.Health
  39219. * @extends Phaser.Component.InCamera
  39220. * @extends Phaser.Component.InputEnabled
  39221. * @extends Phaser.Component.InWorld
  39222. * @extends Phaser.Component.LifeSpan
  39223. * @extends Phaser.Component.LoadTexture
  39224. * @extends Phaser.Component.Overlap
  39225. * @extends Phaser.Component.PhysicsBody
  39226. * @extends Phaser.Component.Reset
  39227. * @extends Phaser.Component.ScaleMinMax
  39228. * @extends Phaser.Component.Smoothed
  39229. * @param {Phaser.Game} game - A reference to the currently running game.
  39230. * @param {number} x - The x coordinate (in world space) to position the Sprite at.
  39231. * @param {number} y - The y coordinate (in world space) to position the Sprite at.
  39232. * @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.
  39233. * @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.
  39234. */
  39235. Phaser.Sprite = function (game, x, y, key, frame) {
  39236. x = x || 0;
  39237. y = y || 0;
  39238. key = key || null;
  39239. frame = frame || null;
  39240. /**
  39241. * @property {number} type - The const type of this object.
  39242. * @readonly
  39243. */
  39244. this.type = Phaser.SPRITE;
  39245. /**
  39246. * @property {number} physicsType - The const physics body type of this object.
  39247. * @readonly
  39248. */
  39249. this.physicsType = Phaser.SPRITE;
  39250. PIXI.Sprite.call(this, PIXI.TextureCache['__default']);
  39251. Phaser.Component.Core.init.call(this, game, x, y, key, frame);
  39252. };
  39253. Phaser.Sprite.prototype = Object.create(PIXI.Sprite.prototype);
  39254. Phaser.Sprite.prototype.constructor = Phaser.Sprite;
  39255. Phaser.Component.Core.install.call(Phaser.Sprite.prototype, [
  39256. 'Angle',
  39257. 'Animation',
  39258. 'AutoCull',
  39259. 'Bounds',
  39260. 'BringToTop',
  39261. 'Crop',
  39262. 'Delta',
  39263. 'Destroy',
  39264. 'FixedToCamera',
  39265. 'Health',
  39266. 'InCamera',
  39267. 'InputEnabled',
  39268. 'InWorld',
  39269. 'LifeSpan',
  39270. 'LoadTexture',
  39271. 'Overlap',
  39272. 'PhysicsBody',
  39273. 'Reset',
  39274. 'ScaleMinMax',
  39275. 'Smoothed'
  39276. ]);
  39277. Phaser.Sprite.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate;
  39278. Phaser.Sprite.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate;
  39279. Phaser.Sprite.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate;
  39280. Phaser.Sprite.prototype.preUpdateCore = Phaser.Component.Core.preUpdate;
  39281. /**
  39282. * Automatically called by World.preUpdate.
  39283. *
  39284. * @method
  39285. * @memberof Phaser.Sprite
  39286. * @return {boolean} True if the Sprite was rendered, otherwise false.
  39287. */
  39288. Phaser.Sprite.prototype.preUpdate = function() {
  39289. if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld())
  39290. {
  39291. return false;
  39292. }
  39293. return this.preUpdateCore();
  39294. };
  39295. /**
  39296. * @author Richard Davey <rich@photonstorm.com>
  39297. * @copyright 2016 Photon Storm Ltd.
  39298. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  39299. */
  39300. /**
  39301. * An Image is a light-weight object you can use to display anything that doesn't need physics or animation.
  39302. * It can still rotate, scale, crop and receive input events. This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics.
  39303. *
  39304. * @class Phaser.Image
  39305. * @extends PIXI.Sprite
  39306. * @extends Phaser.Component.Core
  39307. * @extends Phaser.Component.Angle
  39308. * @extends Phaser.Component.Animation
  39309. * @extends Phaser.Component.AutoCull
  39310. * @extends Phaser.Component.Bounds
  39311. * @extends Phaser.Component.BringToTop
  39312. * @extends Phaser.Component.Crop
  39313. * @extends Phaser.Component.Destroy
  39314. * @extends Phaser.Component.FixedToCamera
  39315. * @extends Phaser.Component.InputEnabled
  39316. * @extends Phaser.Component.LifeSpan
  39317. * @extends Phaser.Component.LoadTexture
  39318. * @extends Phaser.Component.Overlap
  39319. * @extends Phaser.Component.Reset
  39320. * @extends Phaser.Component.Smoothed
  39321. * @constructor
  39322. * @param {Phaser.Game} game - A reference to the currently running game.
  39323. * @param {number} [x=0] - The x coordinate of the Image. The coordinate is relative to any parent container this Image may be in.
  39324. * @param {number} [y=0] - The y coordinate of the Image. The coordinate is relative to any parent container this Image may be in.
  39325. * @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} [key] - The texture used by the Image 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.
  39326. * @param {string|number} [frame] - If this Image 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.
  39327. */
  39328. Phaser.Image = function (game, x, y, key, frame) {
  39329. x = x || 0;
  39330. y = y || 0;
  39331. key = key || null;
  39332. frame = frame || null;
  39333. /**
  39334. * @property {number} type - The const type of this object.
  39335. * @readonly
  39336. */
  39337. this.type = Phaser.IMAGE;
  39338. PIXI.Sprite.call(this, PIXI.TextureCache['__default']);
  39339. Phaser.Component.Core.init.call(this, game, x, y, key, frame);
  39340. };
  39341. Phaser.Image.prototype = Object.create(PIXI.Sprite.prototype);
  39342. Phaser.Image.prototype.constructor = Phaser.Image;
  39343. Phaser.Component.Core.install.call(Phaser.Image.prototype, [
  39344. 'Angle',
  39345. 'Animation',
  39346. 'AutoCull',
  39347. 'Bounds',
  39348. 'BringToTop',
  39349. 'Crop',
  39350. 'Destroy',
  39351. 'FixedToCamera',
  39352. 'InputEnabled',
  39353. 'LifeSpan',
  39354. 'LoadTexture',
  39355. 'Overlap',
  39356. 'Reset',
  39357. 'Smoothed'
  39358. ]);
  39359. Phaser.Image.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate;
  39360. Phaser.Image.prototype.preUpdateCore = Phaser.Component.Core.preUpdate;
  39361. /**
  39362. * Automatically called by World.preUpdate.
  39363. *
  39364. * @method Phaser.Image#preUpdate
  39365. * @memberof Phaser.Image
  39366. */
  39367. Phaser.Image.prototype.preUpdate = function() {
  39368. if (!this.preUpdateInWorld())
  39369. {
  39370. return false;
  39371. }
  39372. return this.preUpdateCore();
  39373. };
  39374. /**
  39375. * @author Richard Davey <rich@photonstorm.com>
  39376. * @copyright 2016 Photon Storm Ltd.
  39377. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  39378. */
  39379. /**
  39380. * Create a new `Button` object. A Button is a special type of Sprite that is set-up to handle Pointer events automatically.
  39381. *
  39382. * The four states a Button responds to are:
  39383. *
  39384. * * 'Over' - when the Pointer moves over the Button. This is also commonly known as 'hover'.
  39385. * * 'Out' - when the Pointer that was previously over the Button moves out of it.
  39386. * * 'Down' - when the Pointer is pressed down on the Button. I.e. touched on a touch enabled device or clicked with the mouse.
  39387. * * 'Up' - when the Pointer that was pressed down on the Button is released again.
  39388. *
  39389. * A different texture/frame and activation sound can be specified for any of the states.
  39390. *
  39391. * Frames can be specified as either an integer (the frame ID) or a string (the frame name); the same values that can be used with a Sprite constructor.
  39392. *
  39393. * @class Phaser.Button
  39394. * @constructor
  39395. * @extends Phaser.Image
  39396. * @param {Phaser.Game} game Current game instance.
  39397. * @param {number} [x=0] - X position of the Button.
  39398. * @param {number} [y=0] - Y position of the Button.
  39399. * @param {string} [key] - The image key (in the Game.Cache) to use as the texture for this Button.
  39400. * @param {function} [callback] - The function to call when this Button is pressed.
  39401. * @param {object} [callbackContext] - The context in which the callback will be called (usually 'this').
  39402. * @param {string|integer} [overFrame] - The frame / frameName when the button is in the Over state.
  39403. * @param {string|integer} [outFrame] - The frame / frameName when the button is in the Out state.
  39404. * @param {string|integer} [downFrame] - The frame / frameName when the button is in the Down state.
  39405. * @param {string|integer} [upFrame] - The frame / frameName when the button is in the Up state.
  39406. */
  39407. Phaser.Button = function (game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame) {
  39408. x = x || 0;
  39409. y = y || 0;
  39410. key = key || null;
  39411. callback = callback || null;
  39412. callbackContext = callbackContext || this;
  39413. Phaser.Image.call(this, game, x, y, key, outFrame);
  39414. /**
  39415. * The Phaser Object Type.
  39416. * @property {number} type
  39417. * @readonly
  39418. */
  39419. this.type = Phaser.BUTTON;
  39420. /**
  39421. * @property {number} physicsType - The const physics body type of this object.
  39422. * @readonly
  39423. */
  39424. this.physicsType = Phaser.SPRITE;
  39425. /**
  39426. * The name or ID of the Over state frame.
  39427. * @property {string|integer} onOverFrame
  39428. * @private
  39429. */
  39430. this._onOverFrame = null;
  39431. /**
  39432. * The name or ID of the Out state frame.
  39433. * @property {string|integer} onOutFrame
  39434. * @private
  39435. */
  39436. this._onOutFrame = null;
  39437. /**
  39438. * The name or ID of the Down state frame.
  39439. * @property {string|integer} onDownFrame
  39440. * @private
  39441. */
  39442. this._onDownFrame = null;
  39443. /**
  39444. * The name or ID of the Up state frame.
  39445. * @property {string|integer} onUpFrame
  39446. * @private
  39447. */
  39448. this._onUpFrame = null;
  39449. /**
  39450. * The Sound to be played when this Buttons Over state is activated.
  39451. * @property {Phaser.Sound|Phaser.AudioSprite|null} onOverSound
  39452. * @readonly
  39453. */
  39454. this.onOverSound = null;
  39455. /**
  39456. * The Sound to be played when this Buttons Out state is activated.
  39457. * @property {Phaser.Sound|Phaser.AudioSprite|null} onOutSound
  39458. * @readonly
  39459. */
  39460. this.onOutSound = null;
  39461. /**
  39462. * The Sound to be played when this Buttons Down state is activated.
  39463. * @property {Phaser.Sound|Phaser.AudioSprite|null} onDownSound
  39464. * @readonly
  39465. */
  39466. this.onDownSound = null;
  39467. /**
  39468. * The Sound to be played when this Buttons Up state is activated.
  39469. * @property {Phaser.Sound|Phaser.AudioSprite|null} onUpSound
  39470. * @readonly
  39471. */
  39472. this.onUpSound = null;
  39473. /**
  39474. * The Sound Marker used in conjunction with the onOverSound.
  39475. * @property {string} onOverSoundMarker
  39476. * @readonly
  39477. */
  39478. this.onOverSoundMarker = '';
  39479. /**
  39480. * The Sound Marker used in conjunction with the onOutSound.
  39481. * @property {string} onOutSoundMarker
  39482. * @readonly
  39483. */
  39484. this.onOutSoundMarker = '';
  39485. /**
  39486. * The Sound Marker used in conjunction with the onDownSound.
  39487. * @property {string} onDownSoundMarker
  39488. * @readonly
  39489. */
  39490. this.onDownSoundMarker = '';
  39491. /**
  39492. * The Sound Marker used in conjunction with the onUpSound.
  39493. * @property {string} onUpSoundMarker
  39494. * @readonly
  39495. */
  39496. this.onUpSoundMarker = '';
  39497. /**
  39498. * The Signal (or event) dispatched when this Button is in an Over state.
  39499. * @property {Phaser.Signal} onInputOver
  39500. */
  39501. this.onInputOver = new Phaser.Signal();
  39502. /**
  39503. * The Signal (or event) dispatched when this Button is in an Out state.
  39504. * @property {Phaser.Signal} onInputOut
  39505. */
  39506. this.onInputOut = new Phaser.Signal();
  39507. /**
  39508. * The Signal (or event) dispatched when this Button is in an Down state.
  39509. * @property {Phaser.Signal} onInputDown
  39510. */
  39511. this.onInputDown = new Phaser.Signal();
  39512. /**
  39513. * The Signal (or event) dispatched when this Button is in an Up state.
  39514. * @property {Phaser.Signal} onInputUp
  39515. */
  39516. this.onInputUp = new Phaser.Signal();
  39517. /**
  39518. * If true then onOver events (such as onOverSound) will only be triggered if the Pointer object causing them was the Mouse Pointer.
  39519. * The frame will still be changed as applicable.
  39520. *
  39521. * @property {boolean} onOverMouseOnly
  39522. * @default
  39523. */
  39524. this.onOverMouseOnly = true;
  39525. /**
  39526. * Suppresse the over event if a pointer was just released and it matches the given {@link Phaser.PointerModer pointer mode bitmask}.
  39527. *
  39528. * This behavior was introduced in Phaser 2.3.1; this property is a soft-revert of the change.
  39529. *
  39530. * @property {Phaser.PointerMode?} justReleasedPreventsOver=ACTIVE_CURSOR
  39531. */
  39532. this.justReleasedPreventsOver = Phaser.PointerMode.TOUCH;
  39533. /**
  39534. * When true the the texture frame will not be automatically switched on up/down/over/out events.
  39535. * @property {boolean} freezeFrames
  39536. * @default
  39537. */
  39538. this.freezeFrames = false;
  39539. /**
  39540. * When the Button is touched / clicked and then released you can force it to enter a state of "out" instead of "up".
  39541. *
  39542. * This can also accept a {@link Phaser.PointerModer pointer mode bitmask} for more refined control.
  39543. *
  39544. * @property {boolean|Phaser.PointerMode} forceOut=false
  39545. * @default
  39546. */
  39547. this.forceOut = false;
  39548. this.inputEnabled = true;
  39549. this.input.start(0, true);
  39550. this.input.useHandCursor = true;
  39551. this.setFrames(overFrame, outFrame, downFrame, upFrame);
  39552. if (callback !== null)
  39553. {
  39554. this.onInputUp.add(callback, callbackContext);
  39555. }
  39556. // Redirect the input events to here so we can handle animation updates, etc
  39557. this.events.onInputOver.add(this.onInputOverHandler, this);
  39558. this.events.onInputOut.add(this.onInputOutHandler, this);
  39559. this.events.onInputDown.add(this.onInputDownHandler, this);
  39560. this.events.onInputUp.add(this.onInputUpHandler, this);
  39561. this.events.onRemovedFromWorld.add(this.removedFromWorld, this);
  39562. };
  39563. Phaser.Button.prototype = Object.create(Phaser.Image.prototype);
  39564. Phaser.Button.prototype.constructor = Phaser.Button;
  39565. // State constants; local only. These are tied to property names in Phaser.Button.
  39566. var STATE_OVER = 'Over';
  39567. var STATE_OUT = 'Out';
  39568. var STATE_DOWN = 'Down';
  39569. var STATE_UP = 'Up';
  39570. /**
  39571. * Clears all of the frames set on this Button.
  39572. *
  39573. * @method Phaser.Button#clearFrames
  39574. */
  39575. Phaser.Button.prototype.clearFrames = function () {
  39576. this.setFrames(null, null, null, null);
  39577. };
  39578. /**
  39579. * Called when this Button is removed from the World.
  39580. *
  39581. * @method Phaser.Button#removedFromWorld
  39582. * @protected
  39583. */
  39584. Phaser.Button.prototype.removedFromWorld = function () {
  39585. this.inputEnabled = false;
  39586. };
  39587. /**
  39588. * Set the frame name/ID for the given state.
  39589. *
  39590. * @method Phaser.Button#setStateFrame
  39591. * @private
  39592. * @param {object} state - See `STATE_*`
  39593. * @param {number|string} frame - The number or string representing the frame.
  39594. * @param {boolean} switchImmediately - Immediately switch to the frame if it was set - and this is true.
  39595. */
  39596. Phaser.Button.prototype.setStateFrame = function (state, frame, switchImmediately)
  39597. {
  39598. var frameKey = '_on' + state + 'Frame';
  39599. if (frame !== null) // not null or undefined
  39600. {
  39601. this[frameKey] = frame;
  39602. if (switchImmediately)
  39603. {
  39604. this.changeStateFrame(state);
  39605. }
  39606. }
  39607. else
  39608. {
  39609. this[frameKey] = null;
  39610. }
  39611. };
  39612. /**
  39613. * Change the frame to that of the given state, _if_ the state has a frame assigned _and_ if the frames are not currently "frozen".
  39614. *
  39615. * @method Phaser.Button#changeStateFrame
  39616. * @private
  39617. * @param {object} state - See `STATE_*`
  39618. * @return {boolean} True only if the frame was assigned a value, possibly the same one it already had.
  39619. */
  39620. Phaser.Button.prototype.changeStateFrame = function (state) {
  39621. if (this.freezeFrames)
  39622. {
  39623. return false;
  39624. }
  39625. var frameKey = '_on' + state + 'Frame';
  39626. var frame = this[frameKey];
  39627. if (typeof frame === 'string')
  39628. {
  39629. this.frameName = frame;
  39630. return true;
  39631. }
  39632. else if (typeof frame === 'number')
  39633. {
  39634. this.frame = frame;
  39635. return true;
  39636. }
  39637. else
  39638. {
  39639. return false;
  39640. }
  39641. };
  39642. /**
  39643. * Used to manually set the frames that will be used for the different states of the Button.
  39644. *
  39645. * Frames can be specified as either an integer (the frame ID) or a string (the frame name); these are the same values that can be used with a Sprite constructor.
  39646. *
  39647. * @method Phaser.Button#setFrames
  39648. * @public
  39649. * @param {string|integer} [overFrame] - The frame / frameName when the button is in the Over state.
  39650. * @param {string|integer} [outFrame] - The frame / frameName when the button is in the Out state.
  39651. * @param {string|integer} [downFrame] - The frame / frameName when the button is in the Down state.
  39652. * @param {string|integer} [upFrame] - The frame / frameName when the button is in the Up state.
  39653. */
  39654. Phaser.Button.prototype.setFrames = function (overFrame, outFrame, downFrame, upFrame) {
  39655. this.setStateFrame(STATE_OVER, overFrame, this.input.pointerOver());
  39656. this.setStateFrame(STATE_OUT, outFrame, !this.input.pointerOver());
  39657. this.setStateFrame(STATE_DOWN, downFrame, this.input.pointerDown());
  39658. this.setStateFrame(STATE_UP, upFrame, this.input.pointerUp());
  39659. };
  39660. /**
  39661. * Set the sound/marker for the given state.
  39662. *
  39663. * @method Phaser.Button#setStateSound
  39664. * @private
  39665. * @param {object} state - See `STATE_*`
  39666. * @param {Phaser.Sound|Phaser.AudioSprite} [sound] - Sound.
  39667. * @param {string} [marker=''] - Sound marker.
  39668. */
  39669. Phaser.Button.prototype.setStateSound = function (state, sound, marker) {
  39670. var soundKey = 'on' + state + 'Sound';
  39671. var markerKey = 'on' + state + 'SoundMarker';
  39672. if (sound instanceof Phaser.Sound || sound instanceof Phaser.AudioSprite)
  39673. {
  39674. this[soundKey] = sound;
  39675. this[markerKey] = typeof marker === 'string' ? marker : '';
  39676. }
  39677. else
  39678. {
  39679. this[soundKey] = null;
  39680. this[markerKey] = '';
  39681. }
  39682. };
  39683. /**
  39684. * Play the sound for the given state, _if_ the state has a sound assigned.
  39685. *
  39686. * @method Phaser.Button#playStateSound
  39687. * @private
  39688. * @param {object} state - See `STATE_*`
  39689. * @return {boolean} True only if a sound was played.
  39690. */
  39691. Phaser.Button.prototype.playStateSound = function (state) {
  39692. var soundKey = 'on' + state + 'Sound';
  39693. var sound = this[soundKey];
  39694. if (sound)
  39695. {
  39696. var markerKey = 'on' + state + 'SoundMarker';
  39697. var marker = this[markerKey];
  39698. sound.play(marker);
  39699. return true;
  39700. }
  39701. else
  39702. {
  39703. return false;
  39704. }
  39705. };
  39706. /**
  39707. * 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.
  39708. * The most common forms of sounds are 'hover' effects and 'click' effects, which is why the order of the parameters is overSound then downSound.
  39709. *
  39710. * Call this function with no parameters to reset all sounds on this Button.
  39711. *
  39712. * @method Phaser.Button#setSounds
  39713. * @public
  39714. * @param {Phaser.Sound|Phaser.AudioSprite} [overSound] - Over Button Sound.
  39715. * @param {string} [overMarker] - Over Button Sound Marker.
  39716. * @param {Phaser.Sound|Phaser.AudioSprite} [downSound] - Down Button Sound.
  39717. * @param {string} [downMarker] - Down Button Sound Marker.
  39718. * @param {Phaser.Sound|Phaser.AudioSprite} [outSound] - Out Button Sound.
  39719. * @param {string} [outMarker] - Out Button Sound Marker.
  39720. * @param {Phaser.Sound|Phaser.AudioSprite} [upSound] - Up Button Sound.
  39721. * @param {string} [upMarker] - Up Button Sound Marker.
  39722. */
  39723. Phaser.Button.prototype.setSounds = function (overSound, overMarker, downSound, downMarker, outSound, outMarker, upSound, upMarker) {
  39724. this.setStateSound(STATE_OVER, overSound, overMarker);
  39725. this.setStateSound(STATE_OUT, outSound, outMarker);
  39726. this.setStateSound(STATE_DOWN, downSound, downMarker);
  39727. this.setStateSound(STATE_UP, upSound, upMarker);
  39728. };
  39729. /**
  39730. * The Sound to be played when a Pointer moves over this Button.
  39731. *
  39732. * @method Phaser.Button#setOverSound
  39733. * @public
  39734. * @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played.
  39735. * @param {string} [marker] - A Sound Marker that will be used in the playback.
  39736. */
  39737. Phaser.Button.prototype.setOverSound = function (sound, marker) {
  39738. this.setStateSound(STATE_OVER, sound, marker);
  39739. };
  39740. /**
  39741. * The Sound to be played when a Pointer moves out of this Button.
  39742. *
  39743. * @method Phaser.Button#setOutSound
  39744. * @public
  39745. * @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played.
  39746. * @param {string} [marker] - A Sound Marker that will be used in the playback.
  39747. */
  39748. Phaser.Button.prototype.setOutSound = function (sound, marker) {
  39749. this.setStateSound(STATE_OUT, sound, marker);
  39750. };
  39751. /**
  39752. * The Sound to be played when a Pointer presses down on this Button.
  39753. *
  39754. * @method Phaser.Button#setDownSound
  39755. * @public
  39756. * @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played.
  39757. * @param {string} [marker] - A Sound Marker that will be used in the playback.
  39758. */
  39759. Phaser.Button.prototype.setDownSound = function (sound, marker) {
  39760. this.setStateSound(STATE_DOWN, sound, marker);
  39761. };
  39762. /**
  39763. * The Sound to be played when a Pointer has pressed down and is released from this Button.
  39764. *
  39765. * @method Phaser.Button#setUpSound
  39766. * @public
  39767. * @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played.
  39768. * @param {string} [marker] - A Sound Marker that will be used in the playback.
  39769. */
  39770. Phaser.Button.prototype.setUpSound = function (sound, marker) {
  39771. this.setStateSound(STATE_UP, sound, marker);
  39772. };
  39773. /**
  39774. * Internal function that handles input events.
  39775. *
  39776. * @method Phaser.Button#onInputOverHandler
  39777. * @protected
  39778. * @param {Phaser.Button} sprite - The Button that the event occurred on.
  39779. * @param {Phaser.Pointer} pointer - The Pointer that activated the Button.
  39780. */
  39781. Phaser.Button.prototype.onInputOverHandler = function (sprite, pointer) {
  39782. if (pointer.justReleased() &&
  39783. (this.justReleasedPreventsOver & pointer.pointerMode) === pointer.pointerMode)
  39784. {
  39785. // If the Pointer was only just released then we don't fire an over event
  39786. return;
  39787. }
  39788. this.changeStateFrame(STATE_OVER);
  39789. if (this.onOverMouseOnly && !pointer.isMouse)
  39790. {
  39791. return;
  39792. }
  39793. this.playStateSound(STATE_OVER);
  39794. if (this.onInputOver)
  39795. {
  39796. this.onInputOver.dispatch(this, pointer);
  39797. }
  39798. };
  39799. /**
  39800. * Internal function that handles input events.
  39801. *
  39802. * @method Phaser.Button#onInputOutHandler
  39803. * @protected
  39804. * @param {Phaser.Button} sprite - The Button that the event occurred on.
  39805. * @param {Phaser.Pointer} pointer - The Pointer that activated the Button.
  39806. */
  39807. Phaser.Button.prototype.onInputOutHandler = function (sprite, pointer) {
  39808. this.changeStateFrame(STATE_OUT);
  39809. this.playStateSound(STATE_OUT);
  39810. if (this.onInputOut)
  39811. {
  39812. this.onInputOut.dispatch(this, pointer);
  39813. }
  39814. };
  39815. /**
  39816. * Internal function that handles input events.
  39817. *
  39818. * @method Phaser.Button#onInputDownHandler
  39819. * @protected
  39820. * @param {Phaser.Button} sprite - The Button that the event occurred on.
  39821. * @param {Phaser.Pointer} pointer - The Pointer that activated the Button.
  39822. */
  39823. Phaser.Button.prototype.onInputDownHandler = function (sprite, pointer) {
  39824. this.changeStateFrame(STATE_DOWN);
  39825. this.playStateSound(STATE_DOWN);
  39826. if (this.onInputDown)
  39827. {
  39828. this.onInputDown.dispatch(this, pointer);
  39829. }
  39830. };
  39831. /**
  39832. * Internal function that handles input events.
  39833. *
  39834. * @method Phaser.Button#onInputUpHandler
  39835. * @protected
  39836. * @param {Phaser.Button} sprite - The Button that the event occurred on.
  39837. * @param {Phaser.Pointer} pointer - The Pointer that activated the Button.
  39838. */
  39839. Phaser.Button.prototype.onInputUpHandler = function (sprite, pointer, isOver) {
  39840. this.playStateSound(STATE_UP);
  39841. // Input dispatched early, before state change (but after sound)
  39842. if (this.onInputUp)
  39843. {
  39844. this.onInputUp.dispatch(this, pointer, isOver);
  39845. }
  39846. if (this.freezeFrames)
  39847. {
  39848. return;
  39849. }
  39850. if (this.forceOut === true || (this.forceOut & pointer.pointerMode) === pointer.pointerMode)
  39851. {
  39852. this.changeStateFrame(STATE_OUT);
  39853. }
  39854. else
  39855. {
  39856. var changedUp = this.changeStateFrame(STATE_UP);
  39857. if (!changedUp)
  39858. {
  39859. // No Up frame to show..
  39860. if (isOver)
  39861. {
  39862. this.changeStateFrame(STATE_OVER);
  39863. }
  39864. else
  39865. {
  39866. this.changeStateFrame(STATE_OUT);
  39867. }
  39868. }
  39869. }
  39870. };
  39871. /**
  39872. * @author Richard Davey <rich@photonstorm.com>
  39873. * @copyright 2016 Photon Storm Ltd.
  39874. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  39875. */
  39876. /**
  39877. * The SpriteBatch class is a really fast version of the DisplayObjectContainer built purely for speed, so use when you need a lot of sprites or particles.
  39878. * It's worth mentioning that by default sprite batches are used through-out the renderer, so you only really need to use a SpriteBatch if you have over
  39879. * 1000 sprites that all share the same texture (or texture atlas). It's also useful if running in Canvas mode and you have a lot of un-rotated or un-scaled
  39880. * Sprites as it skips all of the Canvas setTransform calls, which helps performance, especially on mobile devices.
  39881. *
  39882. * Please note that any Sprite that is part of a SpriteBatch will not have its bounds updated, so will fail checks such as outOfBounds.
  39883. *
  39884. * @class Phaser.SpriteBatch
  39885. * @extends Phaser.Group
  39886. * @constructor
  39887. * @param {Phaser.Game} game - A reference to the currently running game.
  39888. * @param {Phaser.Group|Phaser.Sprite|null} parent - The parent Group, DisplayObject or DisplayObjectContainer that this Group will be added to. If `undefined` or `null` it will use game.world.
  39889. * @param {string} [name=group] - A name for this Group. Not used internally but useful for debugging.
  39890. * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World.
  39891. */
  39892. Phaser.SpriteBatch = function (game, parent, name, addToStage) {
  39893. if (parent === undefined || parent === null) { parent = game.world; }
  39894. PIXI.SpriteBatch.call(this);
  39895. Phaser.Group.call(this, game, parent, name, addToStage);
  39896. /**
  39897. * @property {number} type - Internal Phaser Type value.
  39898. * @protected
  39899. */
  39900. this.type = Phaser.SPRITEBATCH;
  39901. };
  39902. Phaser.SpriteBatch.prototype = Phaser.Utils.extend(true, Phaser.SpriteBatch.prototype, PIXI.SpriteBatch.prototype, Phaser.Group.prototype);
  39903. Phaser.SpriteBatch.prototype.constructor = Phaser.SpriteBatch;
  39904. /**
  39905. * @author Richard Davey <rich@photonstorm.com>
  39906. * @copyright 2016 Photon Storm Ltd.
  39907. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  39908. */
  39909. /**
  39910. * A BitmapData object contains a Canvas element to which you can draw anything you like via normal Canvas context operations.
  39911. * A single BitmapData can be used as the texture for one or many Images / Sprites.
  39912. * So if you need to dynamically create a Sprite texture then they are a good choice.
  39913. *
  39914. * Important note: Every BitmapData creates its own Canvas element. Because BitmapData's are now Game Objects themselves, and don't
  39915. * live on the display list, they are NOT automatically cleared when you change State. Therefore you _must_ call BitmapData.destroy
  39916. * in your State's shutdown method if you wish to free-up the resources the BitmapData used, it will not happen for you.
  39917. *
  39918. * @class Phaser.BitmapData
  39919. * @constructor
  39920. * @param {Phaser.Game} game - A reference to the currently running game.
  39921. * @param {string} key - Internal Phaser reference key for the BitmapData.
  39922. * @param {number} [width=256] - The width of the BitmapData in pixels. If undefined or zero it's set to a default value.
  39923. * @param {number} [height=256] - The height of the BitmapData in pixels. If undefined or zero it's set to a default value.
  39924. */
  39925. Phaser.BitmapData = function (game, key, width, height) {
  39926. if (width === undefined || width === 0) { width = 256; }
  39927. if (height === undefined || height === 0) { height = 256; }
  39928. /**
  39929. * @property {Phaser.Game} game - A reference to the currently running game.
  39930. */
  39931. this.game = game;
  39932. /**
  39933. * @property {string} key - The key of the BitmapData in the Cache, if stored there.
  39934. */
  39935. this.key = key;
  39936. /**
  39937. * @property {number} width - The width of the BitmapData in pixels.
  39938. */
  39939. this.width = width;
  39940. /**
  39941. * @property {number} height - The height of the BitmapData in pixels.
  39942. */
  39943. this.height = height;
  39944. /**
  39945. * @property {HTMLCanvasElement} canvas - The canvas to which this BitmapData draws.
  39946. * @default
  39947. */
  39948. this.canvas = PIXI.CanvasPool.create(this, width, height);
  39949. /**
  39950. * @property {CanvasRenderingContext2D} context - The 2d context of the canvas.
  39951. * @default
  39952. */
  39953. this.context = this.canvas.getContext('2d', { alpha: true });
  39954. /**
  39955. * @property {CanvasRenderingContext2D} ctx - A reference to BitmapData.context.
  39956. */
  39957. this.ctx = this.context;
  39958. /**
  39959. * @property {ImageData} imageData - The context image data.
  39960. * Please note that a call to BitmapData.draw() or BitmapData.copy() does not update immediately this property for performance reason. Use BitmapData.update() to do so.
  39961. * This property is updated automatically after the first game loop, according to the dirty flag property.
  39962. */
  39963. this.imageData = this.context.getImageData(0, 0, width, height);
  39964. /**
  39965. * A Uint8ClampedArray view into BitmapData.buffer.
  39966. * Note that this is unavailable in some browsers (such as Epic Browser due to its security restrictions)
  39967. * @property {Uint8ClampedArray} data
  39968. */
  39969. this.data = null;
  39970. if (this.imageData)
  39971. {
  39972. this.data = this.imageData.data;
  39973. }
  39974. /**
  39975. * @property {Uint32Array} pixels - An Uint32Array view into BitmapData.buffer.
  39976. */
  39977. this.pixels = null;
  39978. /**
  39979. * @property {ArrayBuffer} buffer - An ArrayBuffer the same size as the context ImageData.
  39980. */
  39981. if (this.data)
  39982. {
  39983. if (this.imageData.data.buffer)
  39984. {
  39985. this.buffer = this.imageData.data.buffer;
  39986. this.pixels = new Uint32Array(this.buffer);
  39987. }
  39988. else
  39989. {
  39990. if (window['ArrayBuffer'])
  39991. {
  39992. this.buffer = new ArrayBuffer(this.imageData.data.length);
  39993. this.pixels = new Uint32Array(this.buffer);
  39994. }
  39995. else
  39996. {
  39997. this.pixels = this.imageData.data;
  39998. }
  39999. }
  40000. }
  40001. /**
  40002. * @property {PIXI.BaseTexture} baseTexture - The PIXI.BaseTexture.
  40003. * @default
  40004. */
  40005. this.baseTexture = new PIXI.BaseTexture(this.canvas);
  40006. /**
  40007. * @property {PIXI.Texture} texture - The PIXI.Texture.
  40008. * @default
  40009. */
  40010. this.texture = new PIXI.Texture(this.baseTexture);
  40011. /**
  40012. * @property {Phaser.FrameData} frameData - The FrameData container this BitmapData uses for rendering.
  40013. */
  40014. this.frameData = new Phaser.FrameData();
  40015. /**
  40016. * @property {Phaser.Frame} textureFrame - The Frame this BitmapData uses for rendering.
  40017. * @default
  40018. */
  40019. this.textureFrame = this.frameData.addFrame(new Phaser.Frame(0, 0, 0, width, height, 'bitmapData'));
  40020. this.texture.frame = this.textureFrame;
  40021. /**
  40022. * @property {number} type - The const type of this object.
  40023. * @default
  40024. */
  40025. this.type = Phaser.BITMAPDATA;
  40026. /**
  40027. * @property {boolean} disableTextureUpload - If disableTextureUpload is true this BitmapData will never send its image data to the GPU when its dirty flag is true.
  40028. */
  40029. this.disableTextureUpload = false;
  40030. /**
  40031. * @property {boolean} dirty - If dirty this BitmapData will be re-rendered.
  40032. */
  40033. this.dirty = false;
  40034. // Aliases
  40035. this.cls = this.clear;
  40036. /**
  40037. * @property {number} _image - Internal cache var.
  40038. * @private
  40039. */
  40040. this._image = null;
  40041. /**
  40042. * @property {Phaser.Point} _pos - Internal cache var.
  40043. * @private
  40044. */
  40045. this._pos = new Phaser.Point();
  40046. /**
  40047. * @property {Phaser.Point} _size - Internal cache var.
  40048. * @private
  40049. */
  40050. this._size = new Phaser.Point();
  40051. /**
  40052. * @property {Phaser.Point} _scale - Internal cache var.
  40053. * @private
  40054. */
  40055. this._scale = new Phaser.Point();
  40056. /**
  40057. * @property {number} _rotate - Internal cache var.
  40058. * @private
  40059. */
  40060. this._rotate = 0;
  40061. /**
  40062. * @property {object} _alpha - Internal cache var.
  40063. * @private
  40064. */
  40065. this._alpha = { prev: 1, current: 1 };
  40066. /**
  40067. * @property {Phaser.Point} _anchor - Internal cache var.
  40068. * @private
  40069. */
  40070. this._anchor = new Phaser.Point();
  40071. /**
  40072. * @property {number} _tempR - Internal cache var.
  40073. * @private
  40074. */
  40075. this._tempR = 0;
  40076. /**
  40077. * @property {number} _tempG - Internal cache var.
  40078. * @private
  40079. */
  40080. this._tempG = 0;
  40081. /**
  40082. * @property {number} _tempB - Internal cache var.
  40083. * @private
  40084. */
  40085. this._tempB = 0;
  40086. /**
  40087. * @property {Phaser.Circle} _circle - Internal cache var.
  40088. * @private
  40089. */
  40090. this._circle = new Phaser.Circle();
  40091. /**
  40092. * @property {HTMLCanvasElement} _swapCanvas - A swap canvas. Used by moveH and moveV, created in those methods.
  40093. * @private
  40094. */
  40095. this._swapCanvas = undefined;
  40096. };
  40097. Phaser.BitmapData.prototype = {
  40098. /**
  40099. * Shifts the contents of this BitmapData by the distances given.
  40100. *
  40101. * The image will wrap-around the edges on all sides if the wrap argument is true (the default).
  40102. *
  40103. * @method Phaser.BitmapData#move
  40104. * @param {integer} x - The amount of pixels to horizontally shift the canvas by. Use a negative value to shift to the left, positive to the right.
  40105. * @param {integer} y - The amount of pixels to vertically shift the canvas by. Use a negative value to shift up, positive to shift down.
  40106. * @param {boolean} [wrap=true] - Wrap the content of the BitmapData.
  40107. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  40108. */
  40109. move: function (x, y, wrap) {
  40110. if (x !== 0)
  40111. {
  40112. this.moveH(x, wrap);
  40113. }
  40114. if (y !== 0)
  40115. {
  40116. this.moveV(y, wrap);
  40117. }
  40118. return this;
  40119. },
  40120. /**
  40121. * Shifts the contents of this BitmapData horizontally.
  40122. *
  40123. * The image will wrap-around the sides if the wrap argument is true (the default).
  40124. *
  40125. * @method Phaser.BitmapData#moveH
  40126. * @param {integer} distance - The amount of pixels to horizontally shift the canvas by. Use a negative value to shift to the left, positive to the right.
  40127. * @param {boolean} [wrap=true] - Wrap the content of the BitmapData.
  40128. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  40129. */
  40130. moveH: function (distance, wrap) {
  40131. if (wrap === undefined) { wrap = true; }
  40132. if (this._swapCanvas === undefined)
  40133. {
  40134. this._swapCanvas = PIXI.CanvasPool.create(this, this.width, this.height);
  40135. }
  40136. var c = this._swapCanvas;
  40137. var ctx = c.getContext('2d');
  40138. var h = this.height;
  40139. var src = this.canvas;
  40140. ctx.clearRect(0, 0, this.width, this.height);
  40141. if (distance < 0)
  40142. {
  40143. distance = Math.abs(distance);
  40144. // Moving to the left
  40145. var w = this.width - distance;
  40146. // Left-hand chunk
  40147. if (wrap)
  40148. {
  40149. ctx.drawImage(src, 0, 0, distance, h, w, 0, distance, h);
  40150. }
  40151. // Rest of the image
  40152. ctx.drawImage(src, distance, 0, w, h, 0, 0, w, h);
  40153. }
  40154. else
  40155. {
  40156. // Moving to the right
  40157. var w = this.width - distance;
  40158. // Right-hand chunk
  40159. if (wrap)
  40160. {
  40161. ctx.drawImage(src, w, 0, distance, h, 0, 0, distance, h);
  40162. }
  40163. // Rest of the image
  40164. ctx.drawImage(src, 0, 0, w, h, distance, 0, w, h);
  40165. }
  40166. this.clear();
  40167. return this.copy(this._swapCanvas);
  40168. },
  40169. /**
  40170. * Shifts the contents of this BitmapData vertically.
  40171. *
  40172. * The image will wrap-around the sides if the wrap argument is true (the default).
  40173. *
  40174. * @method Phaser.BitmapData#moveV
  40175. * @param {integer} distance - The amount of pixels to vertically shift the canvas by. Use a negative value to shift up, positive to shift down.
  40176. * @param {boolean} [wrap=true] - Wrap the content of the BitmapData.
  40177. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  40178. */
  40179. moveV: function (distance, wrap) {
  40180. if (wrap === undefined) { wrap = true; }
  40181. if (this._swapCanvas === undefined)
  40182. {
  40183. this._swapCanvas = PIXI.CanvasPool.create(this, this.width, this.height);
  40184. }
  40185. var c = this._swapCanvas;
  40186. var ctx = c.getContext('2d');
  40187. var w = this.width;
  40188. var src = this.canvas;
  40189. ctx.clearRect(0, 0, this.width, this.height);
  40190. if (distance < 0)
  40191. {
  40192. distance = Math.abs(distance);
  40193. // Moving up
  40194. var h = this.height - distance;
  40195. // Top chunk
  40196. if (wrap)
  40197. {
  40198. ctx.drawImage(src, 0, 0, w, distance, 0, h, w, distance);
  40199. }
  40200. // Rest of the image
  40201. ctx.drawImage(src, 0, distance, w, h, 0, 0, w, h);
  40202. }
  40203. else
  40204. {
  40205. // Moving down
  40206. var h = this.height - distance;
  40207. // Bottom chunk
  40208. if (wrap)
  40209. {
  40210. ctx.drawImage(src, 0, h, w, distance, 0, 0, w, distance);
  40211. }
  40212. // Rest of the image
  40213. ctx.drawImage(src, 0, 0, w, h, 0, distance, w, h);
  40214. }
  40215. this.clear();
  40216. return this.copy(this._swapCanvas);
  40217. },
  40218. /**
  40219. * Updates the given objects so that they use this BitmapData as their texture.
  40220. * This will replace any texture they will currently have set.
  40221. *
  40222. * @method Phaser.BitmapData#add
  40223. * @param {Phaser.Sprite|Phaser.Sprite[]|Phaser.Image|Phaser.Image[]} object - Either a single Sprite/Image or an Array of Sprites/Images.
  40224. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  40225. */
  40226. add: function (object) {
  40227. if (Array.isArray(object))
  40228. {
  40229. for (var i = 0; i < object.length; i++)
  40230. {
  40231. if (object[i]['loadTexture'])
  40232. {
  40233. object[i].loadTexture(this);
  40234. }
  40235. }
  40236. }
  40237. else
  40238. {
  40239. object.loadTexture(this);
  40240. }
  40241. return this;
  40242. },
  40243. /**
  40244. * Takes the given Game Object, resizes this BitmapData to match it and then draws it into this BitmapDatas canvas, ready for further processing.
  40245. * The source game object is not modified by this operation.
  40246. * If the source object uses a texture as part of a Texture Atlas or Sprite Sheet, only the current frame will be used for sizing.
  40247. * If a string is given it will assume it's a cache key and look in Phaser.Cache for an image key matching the string.
  40248. *
  40249. * @method Phaser.BitmapData#load
  40250. * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Image|HTMLCanvasElement|string} source - The object that will be used to populate this BitmapData. If you give a string it will try and find the Image in the Game.Cache first.
  40251. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  40252. */
  40253. load: function (source) {
  40254. if (typeof source === 'string')
  40255. {
  40256. source = this.game.cache.getImage(source);
  40257. }
  40258. if (source)
  40259. {
  40260. this.resize(source.width, source.height);
  40261. this.cls();
  40262. }
  40263. else
  40264. {
  40265. return;
  40266. }
  40267. this.draw(source);
  40268. this.update();
  40269. return this;
  40270. },
  40271. /**
  40272. * Clears the BitmapData context using a clearRect.
  40273. *
  40274. * @method Phaser.BitmapData#cls
  40275. */
  40276. /**
  40277. * Clears the BitmapData context using a clearRect.
  40278. *
  40279. * You can optionally define the area to clear.
  40280. * If the arguments are left empty it will clear the entire canvas.
  40281. *
  40282. * You may need to call BitmapData.update after this in order to clear out the pixel data,
  40283. * but Phaser will not do this automatically for you.
  40284. *
  40285. * @method Phaser.BitmapData#clear
  40286. * @param {number} [x=0] - The x coordinate of the top-left of the area to clear.
  40287. * @param {number} [y=0] - The y coordinate of the top-left of the area to clear.
  40288. * @param {number} [width] - The width of the area to clear. If undefined it will use BitmapData.width.
  40289. * @param {number} [height] - The height of the area to clear. If undefined it will use BitmapData.height.
  40290. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  40291. */
  40292. clear: function (x, y, width, height) {
  40293. if (x === undefined) { x = 0; }
  40294. if (y === undefined) { y = 0; }
  40295. if (width === undefined) { width = this.width; }
  40296. if (height === undefined) { height = this.height; }
  40297. this.context.clearRect(x, y, width, height);
  40298. this.dirty = true;
  40299. return this;
  40300. },
  40301. /**
  40302. * Fills the BitmapData with the given color.
  40303. *
  40304. * @method Phaser.BitmapData#fill
  40305. * @param {number} r - The red color value, between 0 and 0xFF (255).
  40306. * @param {number} g - The green color value, between 0 and 0xFF (255).
  40307. * @param {number} b - The blue color value, between 0 and 0xFF (255).
  40308. * @param {number} [a=1] - The alpha color value, between 0 and 1.
  40309. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  40310. */
  40311. fill: function (r, g, b, a) {
  40312. if (a === undefined) { a = 1; }
  40313. this.context.fillStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
  40314. this.context.fillRect(0, 0, this.width, this.height);
  40315. this.dirty = true;
  40316. return this;
  40317. },
  40318. /**
  40319. * Creates a new Image element by converting this BitmapDatas canvas into a dataURL.
  40320. *
  40321. * The image is then stored in the image Cache using the key given.
  40322. *
  40323. * Finally a PIXI.Texture is created based on the image and returned.
  40324. *
  40325. * You can apply the texture to a sprite or any other supporting object by using either the
  40326. * key or the texture. First call generateTexture:
  40327. *
  40328. * `var texture = bitmapdata.generateTexture('ball');`
  40329. *
  40330. * Then you can either apply the texture to a sprite:
  40331. *
  40332. * `game.add.sprite(0, 0, texture);`
  40333. *
  40334. * or by using the string based key:
  40335. *
  40336. * `game.add.sprite(0, 0, 'ball');`
  40337. *
  40338. * @method Phaser.BitmapData#generateTexture
  40339. * @param {string} key - The key which will be used to store the image in the Cache.
  40340. * @return {PIXI.Texture} The newly generated texture.
  40341. */
  40342. generateTexture: function (key) {
  40343. var image = new Image();
  40344. image.src = this.canvas.toDataURL("image/png");
  40345. var obj = this.game.cache.addImage(key, '', image);
  40346. return new PIXI.Texture(obj.base);
  40347. },
  40348. /**
  40349. * Resizes the BitmapData. This changes the size of the underlying canvas and refreshes the buffer.
  40350. *
  40351. * @method Phaser.BitmapData#resize
  40352. * @param {integer} width - The new width of the BitmapData.
  40353. * @param {integer} height - The new height of the BitmapData.
  40354. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  40355. */
  40356. resize: function (width, height) {
  40357. if (width !== this.width || height !== this.height)
  40358. {
  40359. this.width = width;
  40360. this.height = height;
  40361. this.canvas.width = width;
  40362. this.canvas.height = height;
  40363. if (this._swapCanvas !== undefined)
  40364. {
  40365. this._swapCanvas.width = width;
  40366. this._swapCanvas.height = height;
  40367. }
  40368. this.baseTexture.width = width;
  40369. this.baseTexture.height = height;
  40370. this.textureFrame.width = width;
  40371. this.textureFrame.height = height;
  40372. this.texture.width = width;
  40373. this.texture.height = height;
  40374. this.texture.crop.width = width;
  40375. this.texture.crop.height = height;
  40376. this.update();
  40377. this.dirty = true;
  40378. }
  40379. return this;
  40380. },
  40381. /**
  40382. * This re-creates the BitmapData.imageData from the current context.
  40383. * It then re-builds the ArrayBuffer, the data Uint8ClampedArray reference and the pixels Int32Array.
  40384. * If not given the dimensions defaults to the full size of the context.
  40385. *
  40386. * Warning: This is a very expensive operation, so use it sparingly.
  40387. *
  40388. * @method Phaser.BitmapData#update
  40389. * @param {number} [x=0] - The x coordinate of the top-left of the image data area to grab from.
  40390. * @param {number} [y=0] - The y coordinate of the top-left of the image data area to grab from.
  40391. * @param {number} [width=1] - The width of the image data area.
  40392. * @param {number} [height=1] - The height of the image data area.
  40393. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  40394. */
  40395. update: function (x, y, width, height) {
  40396. if (x === undefined) { x = 0; }
  40397. if (y === undefined) { y = 0; }
  40398. if (width === undefined) { width = Math.max(1, this.width); }
  40399. if (height === undefined) { height = Math.max(1, this.height); }
  40400. this.imageData = this.context.getImageData(x, y, width, height);
  40401. this.data = this.imageData.data;
  40402. if (this.imageData.data.buffer)
  40403. {
  40404. this.buffer = this.imageData.data.buffer;
  40405. this.pixels = new Uint32Array(this.buffer);
  40406. }
  40407. else
  40408. {
  40409. if (window['ArrayBuffer'])
  40410. {
  40411. this.buffer = new ArrayBuffer(this.imageData.data.length);
  40412. this.pixels = new Uint32Array(this.buffer);
  40413. }
  40414. else
  40415. {
  40416. this.pixels = this.imageData.data;
  40417. }
  40418. }
  40419. return this;
  40420. },
  40421. /**
  40422. * Scans through the area specified in this BitmapData and sends a color object for every pixel to the given callback.
  40423. * The callback will be sent a color object with 6 properties: `{ r: number, g: number, b: number, a: number, color: number, rgba: string }`.
  40424. * Where r, g, b and a are integers between 0 and 255 representing the color component values for red, green, blue and alpha.
  40425. * The `color` property is an Int32 of the full color. Note the endianess of this will change per system.
  40426. * The `rgba` property is a CSS style rgba() string which can be used with context.fillStyle calls, among others.
  40427. * The callback will also be sent the pixels x and y coordinates respectively.
  40428. * The callback must return either `false`, in which case no change will be made to the pixel, or a new color object.
  40429. * If a new color object is returned the pixel will be set to the r, g, b and a color values given within it.
  40430. *
  40431. * @method Phaser.BitmapData#processPixelRGB
  40432. * @param {function} callback - The callback that will be sent each pixel color object to be processed.
  40433. * @param {object} callbackContext - The context under which the callback will be called.
  40434. * @param {number} [x=0] - The x coordinate of the top-left of the region to process from.
  40435. * @param {number} [y=0] - The y coordinate of the top-left of the region to process from.
  40436. * @param {number} [width] - The width of the region to process.
  40437. * @param {number} [height] - The height of the region to process.
  40438. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  40439. */
  40440. processPixelRGB: function (callback, callbackContext, x, y, width, height) {
  40441. if (x === undefined) { x = 0; }
  40442. if (y === undefined) { y = 0; }
  40443. if (width === undefined) { width = this.width; }
  40444. if (height === undefined) { height = this.height; }
  40445. var w = x + width;
  40446. var h = y + height;
  40447. var pixel = Phaser.Color.createColor();
  40448. var result = { r: 0, g: 0, b: 0, a: 0 };
  40449. var dirty = false;
  40450. for (var ty = y; ty < h; ty++)
  40451. {
  40452. for (var tx = x; tx < w; tx++)
  40453. {
  40454. Phaser.Color.unpackPixel(this.getPixel32(tx, ty), pixel);
  40455. result = callback.call(callbackContext, pixel, tx, ty);
  40456. if (result !== false && result !== null && result !== undefined)
  40457. {
  40458. this.setPixel32(tx, ty, result.r, result.g, result.b, result.a, false);
  40459. dirty = true;
  40460. }
  40461. }
  40462. }
  40463. if (dirty)
  40464. {
  40465. this.context.putImageData(this.imageData, 0, 0);
  40466. this.dirty = true;
  40467. }
  40468. return this;
  40469. },
  40470. /**
  40471. * Scans through the area specified in this BitmapData and sends the color for every pixel to the given callback along with its x and y coordinates.
  40472. * Whatever value the callback returns is set as the new color for that pixel, unless it returns the same color, in which case it's skipped.
  40473. * Note that the format of the color received will be different depending on if the system is big or little endian.
  40474. * It is expected that your callback will deal with endianess. If you'd rather Phaser did it then use processPixelRGB instead.
  40475. * The callback will also be sent the pixels x and y coordinates respectively.
  40476. *
  40477. * @method Phaser.BitmapData#processPixel
  40478. * @param {function} callback - The callback that will be sent each pixel color to be processed.
  40479. * @param {object} callbackContext - The context under which the callback will be called.
  40480. * @param {number} [x=0] - The x coordinate of the top-left of the region to process from.
  40481. * @param {number} [y=0] - The y coordinate of the top-left of the region to process from.
  40482. * @param {number} [width] - The width of the region to process.
  40483. * @param {number} [height] - The height of the region to process.
  40484. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  40485. */
  40486. processPixel: function (callback, callbackContext, x, y, width, height) {
  40487. if (x === undefined) { x = 0; }
  40488. if (y === undefined) { y = 0; }
  40489. if (width === undefined) { width = this.width; }
  40490. if (height === undefined) { height = this.height; }
  40491. var w = x + width;
  40492. var h = y + height;
  40493. var pixel = 0;
  40494. var result = 0;
  40495. var dirty = false;
  40496. for (var ty = y; ty < h; ty++)
  40497. {
  40498. for (var tx = x; tx < w; tx++)
  40499. {
  40500. pixel = this.getPixel32(tx, ty);
  40501. result = callback.call(callbackContext, pixel, tx, ty);
  40502. if (result !== pixel)
  40503. {
  40504. this.pixels[ty * this.width + tx] = result;
  40505. dirty = true;
  40506. }
  40507. }
  40508. }
  40509. if (dirty)
  40510. {
  40511. this.context.putImageData(this.imageData, 0, 0);
  40512. this.dirty = true;
  40513. }
  40514. return this;
  40515. },
  40516. /**
  40517. * Replaces all pixels matching one color with another. The color values are given as two sets of RGBA values.
  40518. * An optional region parameter controls if the replacement happens in just a specific area of the BitmapData or the entire thing.
  40519. *
  40520. * @method Phaser.BitmapData#replaceRGB
  40521. * @param {number} r1 - The red color value to be replaced. Between 0 and 255.
  40522. * @param {number} g1 - The green color value to be replaced. Between 0 and 255.
  40523. * @param {number} b1 - The blue color value to be replaced. Between 0 and 255.
  40524. * @param {number} a1 - The alpha color value to be replaced. Between 0 and 255.
  40525. * @param {number} r2 - The red color value that is the replacement color. Between 0 and 255.
  40526. * @param {number} g2 - The green color value that is the replacement color. Between 0 and 255.
  40527. * @param {number} b2 - The blue color value that is the replacement color. Between 0 and 255.
  40528. * @param {number} a2 - The alpha color value that is the replacement color. Between 0 and 255.
  40529. * @param {Phaser.Rectangle} [region] - The area to perform the search over. If not given it will replace over the whole BitmapData.
  40530. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  40531. */
  40532. replaceRGB: function (r1, g1, b1, a1, r2, g2, b2, a2, region) {
  40533. var sx = 0;
  40534. var sy = 0;
  40535. var w = this.width;
  40536. var h = this.height;
  40537. var source = Phaser.Color.packPixel(r1, g1, b1, a1);
  40538. if (region !== undefined && region instanceof Phaser.Rectangle)
  40539. {
  40540. sx = region.x;
  40541. sy = region.y;
  40542. w = region.width;
  40543. h = region.height;
  40544. }
  40545. for (var y = 0; y < h; y++)
  40546. {
  40547. for (var x = 0; x < w; x++)
  40548. {
  40549. if (this.getPixel32(sx + x, sy + y) === source)
  40550. {
  40551. this.setPixel32(sx + x, sy + y, r2, g2, b2, a2, false);
  40552. }
  40553. }
  40554. }
  40555. this.context.putImageData(this.imageData, 0, 0);
  40556. this.dirty = true;
  40557. return this;
  40558. },
  40559. /**
  40560. * Sets the hue, saturation and lightness values on every pixel in the given region, or the whole BitmapData if no region was specified.
  40561. *
  40562. * @method Phaser.BitmapData#setHSL
  40563. * @param {number} [h=null] - The hue, in the range 0 - 1.
  40564. * @param {number} [s=null] - The saturation, in the range 0 - 1.
  40565. * @param {number} [l=null] - The lightness, in the range 0 - 1.
  40566. * @param {Phaser.Rectangle} [region] - The area to perform the operation on. If not given it will run over the whole BitmapData.
  40567. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  40568. */
  40569. setHSL: function (h, s, l, region) {
  40570. var bHaveH = h || h === 0;
  40571. var bHaveS = s || s === 0;
  40572. var bHaveL = l || l === 0;
  40573. if (!bHaveH && !bHaveS && !bHaveL)
  40574. {
  40575. return;
  40576. }
  40577. if (region === undefined)
  40578. {
  40579. region = new Phaser.Rectangle(0, 0, this.width, this.height);
  40580. }
  40581. var pixel = Phaser.Color.createColor();
  40582. for (var y = region.y; y < region.bottom; y++)
  40583. {
  40584. for (var x = region.x; x < region.right; x++)
  40585. {
  40586. Phaser.Color.unpackPixel(this.getPixel32(x, y), pixel, true);
  40587. if (bHaveH)
  40588. {
  40589. pixel.h = h;
  40590. }
  40591. if (bHaveS)
  40592. {
  40593. pixel.s = s;
  40594. }
  40595. if (bHaveL)
  40596. {
  40597. pixel.l = l;
  40598. }
  40599. Phaser.Color.HSLtoRGB(pixel.h, pixel.s, pixel.l, pixel);
  40600. this.setPixel32(x, y, pixel.r, pixel.g, pixel.b, pixel.a, false);
  40601. }
  40602. }
  40603. this.context.putImageData(this.imageData, 0, 0);
  40604. this.dirty = true;
  40605. return this;
  40606. },
  40607. /**
  40608. * Shifts any or all of the hue, saturation and lightness values on every pixel in the given region, or the whole BitmapData if no region was specified.
  40609. * Shifting will add the given value onto the current h, s and l values, not replace them.
  40610. * The hue is wrapped to keep it within the range 0 to 1. Saturation and lightness are clamped to not exceed 1.
  40611. *
  40612. * @method Phaser.BitmapData#shiftHSL
  40613. * @param {number} [h=null] - The amount to shift the hue by.
  40614. * @param {number} [s=null] - The amount to shift the saturation by.
  40615. * @param {number} [l=null] - The amount to shift the lightness by.
  40616. * @param {Phaser.Rectangle} [region] - The area to perform the operation on. If not given it will run over the whole BitmapData.
  40617. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  40618. */
  40619. shiftHSL: function (h, s, l, region) {
  40620. if (h === undefined || h === null) { h = false; }
  40621. if (s === undefined || s === null) { s = false; }
  40622. if (l === undefined || l === null) { l = false; }
  40623. if (!h && !s && !l)
  40624. {
  40625. return;
  40626. }
  40627. if (region === undefined)
  40628. {
  40629. region = new Phaser.Rectangle(0, 0, this.width, this.height);
  40630. }
  40631. var pixel = Phaser.Color.createColor();
  40632. for (var y = region.y; y < region.bottom; y++)
  40633. {
  40634. for (var x = region.x; x < region.right; x++)
  40635. {
  40636. Phaser.Color.unpackPixel(this.getPixel32(x, y), pixel, true);
  40637. if (h)
  40638. {
  40639. pixel.h = this.game.math.wrap(pixel.h + h, 0, 1);
  40640. }
  40641. if (s)
  40642. {
  40643. pixel.s = this.game.math.clamp(pixel.s + s, 0, 1);
  40644. }
  40645. if (l)
  40646. {
  40647. pixel.l = this.game.math.clamp(pixel.l + l, 0, 1);
  40648. }
  40649. Phaser.Color.HSLtoRGB(pixel.h, pixel.s, pixel.l, pixel);
  40650. this.setPixel32(x, y, pixel.r, pixel.g, pixel.b, pixel.a, false);
  40651. }
  40652. }
  40653. this.context.putImageData(this.imageData, 0, 0);
  40654. this.dirty = true;
  40655. return this;
  40656. },
  40657. /**
  40658. * Sets the color of the given pixel to the specified red, green, blue and alpha values.
  40659. *
  40660. * @method Phaser.BitmapData#setPixel32
  40661. * @param {number} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
  40662. * @param {number} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
  40663. * @param {number} red - The red color value, between 0 and 0xFF (255).
  40664. * @param {number} green - The green color value, between 0 and 0xFF (255).
  40665. * @param {number} blue - The blue color value, between 0 and 0xFF (255).
  40666. * @param {number} alpha - The alpha color value, between 0 and 0xFF (255).
  40667. * @param {boolean} [immediate=true] - If `true` the context.putImageData will be called and the dirty flag set.
  40668. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  40669. */
  40670. setPixel32: function (x, y, red, green, blue, alpha, immediate) {
  40671. if (immediate === undefined) { immediate = true; }
  40672. if (x >= 0 && x <= this.width && y >= 0 && y <= this.height)
  40673. {
  40674. if (Phaser.Device.LITTLE_ENDIAN)
  40675. {
  40676. this.pixels[y * this.width + x] = (alpha << 24) | (blue << 16) | (green << 8) | red;
  40677. }
  40678. else
  40679. {
  40680. this.pixels[y * this.width + x] = (red << 24) | (green << 16) | (blue << 8) | alpha;
  40681. }
  40682. if (immediate)
  40683. {
  40684. this.context.putImageData(this.imageData, 0, 0);
  40685. this.dirty = true;
  40686. }
  40687. }
  40688. return this;
  40689. },
  40690. /**
  40691. * Sets the color of the given pixel to the specified red, green and blue values.
  40692. *
  40693. * @method Phaser.BitmapData#setPixel
  40694. * @param {number} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
  40695. * @param {number} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
  40696. * @param {number} red - The red color value, between 0 and 0xFF (255).
  40697. * @param {number} green - The green color value, between 0 and 0xFF (255).
  40698. * @param {number} blue - The blue color value, between 0 and 0xFF (255).
  40699. * @param {boolean} [immediate=true] - If `true` the context.putImageData will be called and the dirty flag set.
  40700. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  40701. */
  40702. setPixel: function (x, y, red, green, blue, immediate) {
  40703. return this.setPixel32(x, y, red, green, blue, 255, immediate);
  40704. },
  40705. /**
  40706. * Get the color of a specific pixel in the context into a color object.
  40707. * If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer,
  40708. * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist.
  40709. *
  40710. * @method Phaser.BitmapData#getPixel
  40711. * @param {number} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
  40712. * @param {number} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
  40713. * @param {object} [out] - An object into which 4 properties will be created: r, g, b and a. If not provided a new object will be created.
  40714. * @return {object} An object with the red, green, blue and alpha values set in the r, g, b and a properties.
  40715. */
  40716. getPixel: function (x, y, out) {
  40717. if (!out)
  40718. {
  40719. out = Phaser.Color.createColor();
  40720. }
  40721. var index = ~~(x + (y * this.width));
  40722. index *= 4;
  40723. out.r = this.data[index];
  40724. out.g = this.data[++index];
  40725. out.b = this.data[++index];
  40726. out.a = this.data[++index];
  40727. return out;
  40728. },
  40729. /**
  40730. * Get the color of a specific pixel including its alpha value.
  40731. * If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer,
  40732. * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist.
  40733. * Note that on little-endian systems the format is 0xAABBGGRR and on big-endian the format is 0xRRGGBBAA.
  40734. *
  40735. * @method Phaser.BitmapData#getPixel32
  40736. * @param {number} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
  40737. * @param {number} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
  40738. * @return {number} A native color value integer (format: 0xAARRGGBB)
  40739. */
  40740. getPixel32: function (x, y) {
  40741. if (x >= 0 && x <= this.width && y >= 0 && y <= this.height)
  40742. {
  40743. return this.pixels[y * this.width + x];
  40744. }
  40745. },
  40746. /**
  40747. * Get the color of a specific pixel including its alpha value as a color object containing r,g,b,a and rgba properties.
  40748. * If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer,
  40749. * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist.
  40750. *
  40751. * @method Phaser.BitmapData#getPixelRGB
  40752. * @param {number} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
  40753. * @param {number} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
  40754. * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created.
  40755. * @param {boolean} [hsl=false] - Also convert the rgb values into hsl?
  40756. * @param {boolean} [hsv=false] - Also convert the rgb values into hsv?
  40757. * @return {object} An object with the red, green and blue values set in the r, g and b properties.
  40758. */
  40759. getPixelRGB: function (x, y, out, hsl, hsv) {
  40760. return Phaser.Color.unpackPixel(this.getPixel32(x, y), out, hsl, hsv);
  40761. },
  40762. /**
  40763. * Gets all the pixels from the region specified by the given Rectangle object.
  40764. *
  40765. * @method Phaser.BitmapData#getPixels
  40766. * @param {Phaser.Rectangle} rect - The Rectangle region to get.
  40767. * @return {ImageData} Returns a ImageData object containing a Uint8ClampedArray data property.
  40768. */
  40769. getPixels: function (rect) {
  40770. return this.context.getImageData(rect.x, rect.y, rect.width, rect.height);
  40771. },
  40772. /**
  40773. * Scans the BitmapData, pixel by pixel, until it encounters a pixel that isn't transparent (i.e. has an alpha value > 0).
  40774. * It then stops scanning and returns an object containing the color of the pixel in r, g and b properties and the location in the x and y properties.
  40775. *
  40776. * The direction parameter controls from which direction it should start the scan:
  40777. *
  40778. * 0 = top to bottom
  40779. * 1 = bottom to top
  40780. * 2 = left to right
  40781. * 3 = right to left
  40782. *
  40783. * @method Phaser.BitmapData#getFirstPixel
  40784. * @param {number} [direction=0] - The direction in which to scan for the first pixel. 0 = top to bottom, 1 = bottom to top, 2 = left to right and 3 = right to left.
  40785. * @return {object} Returns an object containing the color of the pixel in the `r`, `g` and `b` properties and the location in the `x` and `y` properties.
  40786. */
  40787. getFirstPixel: function (direction) {
  40788. if (direction === undefined) { direction = 0; }
  40789. var pixel = Phaser.Color.createColor();
  40790. var x = 0;
  40791. var y = 0;
  40792. var v = 1;
  40793. var scan = false;
  40794. if (direction === 1)
  40795. {
  40796. v = -1;
  40797. y = this.height;
  40798. }
  40799. else if (direction === 3)
  40800. {
  40801. v = -1;
  40802. x = this.width;
  40803. }
  40804. do {
  40805. Phaser.Color.unpackPixel(this.getPixel32(x, y), pixel);
  40806. if (direction === 0 || direction === 1)
  40807. {
  40808. // Top to Bottom / Bottom to Top
  40809. x++;
  40810. if (x === this.width)
  40811. {
  40812. x = 0;
  40813. y += v;
  40814. if (y >= this.height || y <= 0)
  40815. {
  40816. scan = true;
  40817. }
  40818. }
  40819. }
  40820. else if (direction === 2 || direction === 3)
  40821. {
  40822. // Left to Right / Right to Left
  40823. y++;
  40824. if (y === this.height)
  40825. {
  40826. y = 0;
  40827. x += v;
  40828. if (x >= this.width || x <= 0)
  40829. {
  40830. scan = true;
  40831. }
  40832. }
  40833. }
  40834. }
  40835. while (pixel.a === 0 && !scan);
  40836. pixel.x = x;
  40837. pixel.y = y;
  40838. return pixel;
  40839. },
  40840. /**
  40841. * Scans the BitmapData and calculates the bounds. This is a rectangle that defines the extent of all non-transparent pixels.
  40842. * The rectangle returned will extend from the top-left of the image to the bottom-right, excluding transparent pixels.
  40843. *
  40844. * @method Phaser.BitmapData#getBounds
  40845. * @param {Phaser.Rectangle} [rect] - If provided this Rectangle object will be populated with the bounds, otherwise a new object will be created.
  40846. * @return {Phaser.Rectangle} A Rectangle whose dimensions encompass the full extent of non-transparent pixels in this BitmapData.
  40847. */
  40848. getBounds: function (rect) {
  40849. if (rect === undefined) { rect = new Phaser.Rectangle(); }
  40850. rect.x = this.getFirstPixel(2).x;
  40851. // If we hit this, there's no point scanning any more, the image is empty
  40852. if (rect.x === this.width)
  40853. {
  40854. return rect.setTo(0, 0, 0, 0);
  40855. }
  40856. rect.y = this.getFirstPixel(0).y;
  40857. rect.width = (this.getFirstPixel(3).x - rect.x) + 1;
  40858. rect.height = (this.getFirstPixel(1).y - rect.y) + 1;
  40859. return rect;
  40860. },
  40861. /**
  40862. * Creates a new Phaser.Image object, assigns this BitmapData to be its texture, adds it to the world then returns it.
  40863. *
  40864. * @method Phaser.BitmapData#addToWorld
  40865. * @param {number} [x=0] - The x coordinate to place the Image at.
  40866. * @param {number} [y=0] - The y coordinate to place the Image at.
  40867. * @param {number} [anchorX=0] - Set the x anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right.
  40868. * @param {number} [anchorY=0] - Set the y anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right.
  40869. * @param {number} [scaleX=1] - The horizontal scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on.
  40870. * @param {number} [scaleY=1] - The vertical scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on.
  40871. * @return {Phaser.Image} The newly added Image object.
  40872. */
  40873. addToWorld: function (x, y, anchorX, anchorY, scaleX, scaleY) {
  40874. scaleX = scaleX || 1;
  40875. scaleY = scaleY || 1;
  40876. var image = this.game.add.image(x, y, this);
  40877. image.anchor.set(anchorX, anchorY);
  40878. image.scale.set(scaleX, scaleY);
  40879. return image;
  40880. },
  40881. /**
  40882. * Copies a rectangular area from the source object to this BitmapData. If you give `null` as the source it will copy from itself.
  40883. * You can optionally resize, translate, rotate, scale, alpha or blend as it's drawn.
  40884. * All rotation, scaling and drawing takes place around the regions center point by default, but can be changed with the anchor parameters.
  40885. * Note that the source image can also be this BitmapData, which can create some interesting effects.
  40886. *
  40887. * This method has a lot of parameters for maximum control.
  40888. * You can use the more friendly methods like `copyRect` and `draw` to avoid having to remember them all.
  40889. *
  40890. * @method Phaser.BitmapData#copy
  40891. * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Image|HTMLCanvasElement|string} [source] - The source to copy from. If you give a string it will try and find the Image in the Game.Cache first. This is quite expensive so try to provide the image itself.
  40892. * @param {number} [x=0] - The x coordinate representing the top-left of the region to copy from the source image.
  40893. * @param {number} [y=0] - The y coordinate representing the top-left of the region to copy from the source image.
  40894. * @param {number} [width] - The width of the region to copy from the source image. If not specified it will use the full source image width.
  40895. * @param {number} [height] - The height of the region to copy from the source image. If not specified it will use the full source image height.
  40896. * @param {number} [tx] - The x coordinate to translate to before drawing. If not specified it will default to the `x` parameter. If `null` and `source` is a Display Object, it will default to `source.x`.
  40897. * @param {number} [ty] - The y coordinate to translate to before drawing. If not specified it will default to the `y` parameter. If `null` and `source` is a Display Object, it will default to `source.y`.
  40898. * @param {number} [newWidth] - The new width of the block being copied. If not specified it will default to the `width` parameter.
  40899. * @param {number} [newHeight] - The new height of the block being copied. If not specified it will default to the `height` parameter.
  40900. * @param {number} [rotate=0] - The angle in radians to rotate the block to before drawing. Rotation takes place around the center by default, but can be changed with the `anchor` parameters.
  40901. * @param {number} [anchorX=0] - The anchor point around which the block is rotated and scaled. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right.
  40902. * @param {number} [anchorY=0] - The anchor point around which the block is rotated and scaled. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right.
  40903. * @param {number} [scaleX=1] - The horizontal scale factor of the block. A value of 1 means no scaling. 2 would be twice the size, and so on.
  40904. * @param {number} [scaleY=1] - The vertical scale factor of the block. A value of 1 means no scaling. 2 would be twice the size, and so on.
  40905. * @param {number} [alpha=1] - The alpha that will be set on the context before drawing. A value between 0 (fully transparent) and 1, opaque.
  40906. * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'.
  40907. * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances.
  40908. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  40909. */
  40910. copy: function (source, x, y, width, height, tx, ty, newWidth, newHeight, rotate, anchorX, anchorY, scaleX, scaleY, alpha, blendMode, roundPx) {
  40911. if (source === undefined || source === null) { source = this; }
  40912. this._image = source;
  40913. if (source instanceof Phaser.Sprite || source instanceof Phaser.Image || source instanceof Phaser.Text || source instanceof PIXI.Sprite)
  40914. {
  40915. // Copy over sprite values
  40916. this._pos.set(source.texture.crop.x, source.texture.crop.y);
  40917. this._size.set(source.texture.crop.width, source.texture.crop.height);
  40918. this._scale.set(source.scale.x, source.scale.y);
  40919. this._anchor.set(source.anchor.x, source.anchor.y);
  40920. this._rotate = source.rotation;
  40921. this._alpha.current = source.alpha;
  40922. this._image = source.texture.baseTexture.source;
  40923. if (tx === undefined || tx === null) { tx = source.x; }
  40924. if (ty === undefined || ty === null) { ty = source.y; }
  40925. if (source.texture.trim)
  40926. {
  40927. // Offset the translation coordinates by the trim amount
  40928. tx += source.texture.trim.x - source.anchor.x * source.texture.trim.width;
  40929. ty += source.texture.trim.y - source.anchor.y * source.texture.trim.height;
  40930. }
  40931. if (source.tint !== 0xFFFFFF)
  40932. {
  40933. if (source.cachedTint !== source.tint)
  40934. {
  40935. source.cachedTint = source.tint;
  40936. source.tintedTexture = PIXI.CanvasTinter.getTintedTexture(source, source.tint);
  40937. }
  40938. this._image = source.tintedTexture;
  40939. this._pos.set(0);
  40940. }
  40941. }
  40942. else
  40943. {
  40944. // Reset
  40945. this._pos.set(0);
  40946. this._scale.set(1);
  40947. this._anchor.set(0);
  40948. this._rotate = 0;
  40949. this._alpha.current = 1;
  40950. if (source instanceof Phaser.BitmapData)
  40951. {
  40952. this._image = source.canvas;
  40953. }
  40954. else if (typeof source === 'string')
  40955. {
  40956. source = this.game.cache.getImage(source);
  40957. if (source === null)
  40958. {
  40959. return;
  40960. }
  40961. else
  40962. {
  40963. this._image = source;
  40964. }
  40965. }
  40966. this._size.set(this._image.width, this._image.height);
  40967. }
  40968. // The source region to copy from
  40969. if (x === undefined || x === null) { x = 0; }
  40970. if (y === undefined || y === null) { y = 0; }
  40971. // If they set a width/height then we override the frame values with them
  40972. if (width)
  40973. {
  40974. this._size.x = width;
  40975. }
  40976. if (height)
  40977. {
  40978. this._size.y = height;
  40979. }
  40980. // The destination region to copy to
  40981. if (tx === undefined || tx === null) { tx = x; }
  40982. if (ty === undefined || ty === null) { ty = y; }
  40983. if (newWidth === undefined || newWidth === null) { newWidth = this._size.x; }
  40984. if (newHeight === undefined || newHeight === null) { newHeight = this._size.y; }
  40985. // Rotation - if set this will override any potential Sprite value
  40986. if (typeof rotate === 'number')
  40987. {
  40988. this._rotate = rotate;
  40989. }
  40990. // Anchor - if set this will override any potential Sprite value
  40991. if (typeof anchorX === 'number')
  40992. {
  40993. this._anchor.x = anchorX;
  40994. }
  40995. if (typeof anchorY === 'number')
  40996. {
  40997. this._anchor.y = anchorY;
  40998. }
  40999. // Scaling - if set this will override any potential Sprite value
  41000. if (typeof scaleX === 'number')
  41001. {
  41002. this._scale.x = scaleX;
  41003. }
  41004. if (typeof scaleY === 'number')
  41005. {
  41006. this._scale.y = scaleY;
  41007. }
  41008. // Effects
  41009. if (typeof alpha === 'number')
  41010. {
  41011. this._alpha.current = alpha;
  41012. }
  41013. if (blendMode === undefined) { blendMode = null; }
  41014. if (roundPx === undefined) { roundPx = false; }
  41015. if (this._alpha.current <= 0 || this._scale.x === 0 || this._scale.y === 0 || this._size.x === 0 || this._size.y === 0)
  41016. {
  41017. // Why bother wasting CPU cycles drawing something you can't see?
  41018. return;
  41019. }
  41020. var ctx = this.context;
  41021. this._alpha.prev = ctx.globalAlpha;
  41022. ctx.save();
  41023. ctx.globalAlpha = this._alpha.current;
  41024. if (blendMode)
  41025. {
  41026. this.op = blendMode;
  41027. }
  41028. if (roundPx)
  41029. {
  41030. tx |= 0;
  41031. ty |= 0;
  41032. }
  41033. ctx.translate(tx, ty);
  41034. ctx.scale(this._scale.x, this._scale.y);
  41035. ctx.rotate(this._rotate);
  41036. ctx.drawImage(this._image, this._pos.x + x, this._pos.y + y, this._size.x, this._size.y, -newWidth * this._anchor.x, -newHeight * this._anchor.y, newWidth, newHeight);
  41037. ctx.restore();
  41038. ctx.globalAlpha = this._alpha.prev;
  41039. this.dirty = true;
  41040. return this;
  41041. },
  41042. /**
  41043. * Copies the area defined by the Rectangle parameter from the source image to this BitmapData at the given location.
  41044. *
  41045. * @method Phaser.BitmapData#copyRect
  41046. * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Image|string} source - The Image to copy from. If you give a string it will try and find the Image in the Game.Cache.
  41047. * @param {Phaser.Rectangle} area - The Rectangle region to copy from the source image.
  41048. * @param {number} x - The destination x coordinate to copy the image to.
  41049. * @param {number} y - The destination y coordinate to copy the image to.
  41050. * @param {number} [alpha=1] - The alpha that will be set on the context before drawing. A value between 0 (fully transparent) and 1, opaque.
  41051. * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'.
  41052. * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances.
  41053. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41054. */
  41055. copyRect: function (source, area, x, y, alpha, blendMode, roundPx) {
  41056. return this.copy(source, area.x, area.y, area.width, area.height, x, y, area.width, area.height, 0, 0, 0, 1, 1, alpha, blendMode, roundPx);
  41057. },
  41058. /**
  41059. * Draws the given Phaser.Sprite, Phaser.Image or Phaser.Text to this BitmapData at the coordinates specified.
  41060. * You can use the optional width and height values to 'stretch' the sprite as it is drawn. This uses drawImage stretching, not scaling.
  41061. * When drawing it will take into account the Sprites rotation, scale and alpha values.
  41062. *
  41063. * @method Phaser.BitmapData#draw
  41064. * @param {Phaser.Sprite|Phaser.Image|Phaser.Text} source - The Sprite, Image or Text object to draw onto this BitmapData.
  41065. * @param {number} [x=0] - The x coordinate to translate to before drawing. If not specified it will default to `source.x`.
  41066. * @param {number} [y=0] - The y coordinate to translate to before drawing. If not specified it will default to `source.y`.
  41067. * @param {number} [width] - The new width of the Sprite being copied. If not specified it will default to `source.width`.
  41068. * @param {number} [height] - The new height of the Sprite being copied. If not specified it will default to `source.height`.
  41069. * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'.
  41070. * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances.
  41071. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41072. */
  41073. draw: function (source, x, y, width, height, blendMode, roundPx) {
  41074. // By specifying null for most parameters it will tell `copy` to use the Sprite values instead, which is what we want here
  41075. return this.copy(source, null, null, null, null, x, y, width, height, null, null, null, null, null, null, blendMode, roundPx);
  41076. },
  41077. /**
  41078. * Draws the immediate children of a Phaser.Group to this BitmapData.
  41079. * Children are only drawn if they have their `exists` property set to `true` and have image based Textures.
  41080. * The children will be drawn at their `x` and `y` world space coordinates. If this is outside the bounds of the BitmapData they won't be drawn.
  41081. * When drawing it will take into account the child's rotation, scale and alpha values.
  41082. * No iteration takes place. Groups nested inside other Groups will not be iterated through.
  41083. *
  41084. * @method Phaser.BitmapData#drawGroup
  41085. * @param {Phaser.Group} group - The Group to draw onto this BitmapData.
  41086. * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'.
  41087. * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances.
  41088. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41089. */
  41090. drawGroup: function (group, blendMode, roundPx) {
  41091. if (group.total > 0)
  41092. {
  41093. group.forEachExists(this.drawGroupProxy, this, blendMode, roundPx);
  41094. }
  41095. return this;
  41096. },
  41097. /**
  41098. * A proxy for drawGroup that handles child iteration for more complex Game Objects.
  41099. *
  41100. * @method Phaser.BitmapData#drawGroupProxy
  41101. * @private
  41102. * @param {Phaser.Sprite|Phaser.Image|Phaser.BitmapText} child - The child to draw.
  41103. * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'.
  41104. * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances.
  41105. */
  41106. drawGroupProxy: function (child, blendMode, roundPx) {
  41107. if (child.type === Phaser.EMITTER || child.type === Phaser.BITMAPTEXT)
  41108. {
  41109. for (var i = 0; i < child.children.length; i++)
  41110. {
  41111. this.copy(child.children[i], null, null, null, null, null, null, null, null, null, null, null, null, null, null, blendMode, roundPx);
  41112. }
  41113. }
  41114. else
  41115. {
  41116. this.copy(child, null, null, null, null, null, null, null, null, null, null, null, null, null, null, blendMode, roundPx);
  41117. }
  41118. },
  41119. /**
  41120. * Draws the Game Object or Group to this BitmapData and then recursively iterates through all of its children.
  41121. *
  41122. * If a child has an `exists` property then it (and its children) will be only be drawn if exists is `true`.
  41123. *
  41124. * The children will be drawn at their `x` and `y` world space coordinates. If this is outside the bounds of the BitmapData
  41125. * they won't be drawn. Depending on your requirements you may need to resize the BitmapData in advance to match the
  41126. * bounds of the top-level Game Object.
  41127. *
  41128. * When drawing it will take into account the child's world rotation, scale and alpha values.
  41129. *
  41130. * It's perfectly valid to pass in `game.world` as the parent object, and it will iterate through the entire display list.
  41131. *
  41132. * Note: If you are trying to grab your entire game at the start of a State then you should ensure that at least 1 full update
  41133. * has taken place before doing so, otherwise all of the objects will render with incorrect positions and scales. You can
  41134. * trigger an update yourself by calling `stage.updateTransform()` before calling `drawFull`.
  41135. *
  41136. * @method Phaser.BitmapData#drawFull
  41137. * @param {Phaser.World|Phaser.Group|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText} parent - The Game Object to draw onto this BitmapData and then recursively draw all of its children.
  41138. * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'.
  41139. * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances.
  41140. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41141. */
  41142. drawFull: function (parent, blendMode, roundPx) {
  41143. if (parent.worldVisible === false || parent.worldAlpha === 0 || (parent.hasOwnProperty('exists') && parent.exists === false))
  41144. {
  41145. return this;
  41146. }
  41147. if (parent.type !== Phaser.GROUP && parent.type !== Phaser.EMITTER && parent.type !== Phaser.BITMAPTEXT)
  41148. {
  41149. if (parent.type === Phaser.GRAPHICS)
  41150. {
  41151. var bounds = parent.getBounds();
  41152. this.ctx.save();
  41153. this.ctx.translate(bounds.x, bounds.y);
  41154. PIXI.CanvasGraphics.renderGraphics(parent, this.ctx);
  41155. this.ctx.restore();
  41156. }
  41157. else
  41158. {
  41159. this.copy(parent, null, null, null, null, parent.worldPosition.x, parent.worldPosition.y, null, null, parent.worldRotation, null, null, parent.worldScale.x, parent.worldScale.y, parent.worldAlpha, blendMode, roundPx);
  41160. }
  41161. }
  41162. if (parent.children)
  41163. {
  41164. for (var i = 0; i < parent.children.length; i++)
  41165. {
  41166. this.drawFull(parent.children[i], blendMode, roundPx);
  41167. }
  41168. }
  41169. return this;
  41170. },
  41171. /**
  41172. * Sets the shadow properties of this BitmapDatas context which will affect all draw operations made to it.
  41173. * You can cancel an existing shadow by calling this method and passing no parameters.
  41174. * Note: At the time of writing (October 2014) Chrome still doesn't support shadowBlur used with drawImage.
  41175. *
  41176. * @method Phaser.BitmapData#shadow
  41177. * @param {string} color - The color of the shadow, given in a CSS format, i.e. `#000000` or `rgba(0,0,0,1)`. If `null` or `undefined` the shadow will be reset.
  41178. * @param {number} [blur=5] - The amount the shadow will be blurred by. Low values = a crisp shadow, high values = a softer shadow.
  41179. * @param {number} [x=10] - The horizontal offset of the shadow in pixels.
  41180. * @param {number} [y=10] - The vertical offset of the shadow in pixels.
  41181. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41182. */
  41183. shadow: function (color, blur, x, y) {
  41184. var ctx = this.context;
  41185. if (color === undefined || color === null)
  41186. {
  41187. ctx.shadowColor = 'rgba(0,0,0,0)';
  41188. }
  41189. else
  41190. {
  41191. ctx.shadowColor = color;
  41192. ctx.shadowBlur = blur || 5;
  41193. ctx.shadowOffsetX = x || 10;
  41194. ctx.shadowOffsetY = y || 10;
  41195. }
  41196. },
  41197. /**
  41198. * Draws the image onto this BitmapData using an image as an alpha mask.
  41199. *
  41200. * @method Phaser.BitmapData#alphaMask
  41201. * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Image|HTMLCanvasElement|string} source - The source to copy from. If you give a string it will try and find the Image in the Game.Cache first. This is quite expensive so try to provide the image itself.
  41202. * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Image|HTMLCanvasElement|string} [mask] - The object to be used as the mask. If you give a string it will try and find the Image in the Game.Cache first. This is quite expensive so try to provide the image itself. If you don't provide a mask it will use this BitmapData as the mask.
  41203. * @param {Phaser.Rectangle} [sourceRect] - A Rectangle where x/y define the coordinates to draw the Source image to and width/height define the size.
  41204. * @param {Phaser.Rectangle} [maskRect] - A Rectangle where x/y define the coordinates to draw the Mask image to and width/height define the size.
  41205. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41206. */
  41207. alphaMask: function (source, mask, sourceRect, maskRect) {
  41208. if (maskRect === undefined || maskRect === null)
  41209. {
  41210. this.draw(mask).blendSourceAtop();
  41211. }
  41212. else
  41213. {
  41214. this.draw(mask, maskRect.x, maskRect.y, maskRect.width, maskRect.height).blendSourceAtop();
  41215. }
  41216. if (sourceRect === undefined || sourceRect === null)
  41217. {
  41218. this.draw(source).blendReset();
  41219. }
  41220. else
  41221. {
  41222. this.draw(source, sourceRect.x, sourceRect.y, sourceRect.width, sourceRect.height).blendReset();
  41223. }
  41224. return this;
  41225. },
  41226. /**
  41227. * Scans this BitmapData for all pixels matching the given r,g,b values and then draws them into the given destination BitmapData.
  41228. * The original BitmapData remains unchanged.
  41229. * The destination BitmapData must be large enough to receive all of the pixels that are scanned unless the 'resize' parameter is true.
  41230. * Although the destination BitmapData is returned from this method, it's actually modified directly in place, meaning this call is perfectly valid:
  41231. * `picture.extract(mask, r, g, b)`
  41232. * You can specify optional r2, g2, b2 color values. If given the pixel written to the destination bitmap will be of the r2, g2, b2 color.
  41233. * If not given it will be written as the same color it was extracted. You can provide one or more alternative colors, allowing you to tint
  41234. * the color during extraction.
  41235. *
  41236. * @method Phaser.BitmapData#extract
  41237. * @param {Phaser.BitmapData} destination - The BitmapData that the extracted pixels will be drawn to.
  41238. * @param {number} r - The red color component, in the range 0 - 255.
  41239. * @param {number} g - The green color component, in the range 0 - 255.
  41240. * @param {number} b - The blue color component, in the range 0 - 255.
  41241. * @param {number} [a=255] - The alpha color component, in the range 0 - 255 that the new pixel will be drawn at.
  41242. * @param {boolean} [resize=false] - Should the destination BitmapData be resized to match this one before the pixels are copied?
  41243. * @param {number} [r2] - An alternative red color component to be written to the destination, in the range 0 - 255.
  41244. * @param {number} [g2] - An alternative green color component to be written to the destination, in the range 0 - 255.
  41245. * @param {number} [b2] - An alternative blue color component to be written to the destination, in the range 0 - 255.
  41246. * @returns {Phaser.BitmapData} The BitmapData that the extract pixels were drawn on.
  41247. */
  41248. extract: function (destination, r, g, b, a, resize, r2, g2, b2) {
  41249. if (a === undefined) { a = 255; }
  41250. if (resize === undefined) { resize = false; }
  41251. if (r2 === undefined) { r2 = r; }
  41252. if (g2 === undefined) { g2 = g; }
  41253. if (b2 === undefined) { b2 = b; }
  41254. if (resize)
  41255. {
  41256. destination.resize(this.width, this.height);
  41257. }
  41258. this.processPixelRGB(
  41259. function (pixel, x, y)
  41260. {
  41261. if (pixel.r === r && pixel.g === g && pixel.b === b)
  41262. {
  41263. destination.setPixel32(x, y, r2, g2, b2, a, false);
  41264. }
  41265. return false;
  41266. },
  41267. this);
  41268. destination.context.putImageData(destination.imageData, 0, 0);
  41269. destination.dirty = true;
  41270. return destination;
  41271. },
  41272. /**
  41273. * Draws a filled Rectangle to the BitmapData at the given x, y coordinates and width / height in size.
  41274. *
  41275. * @method Phaser.BitmapData#rect
  41276. * @param {number} x - The x coordinate of the top-left of the Rectangle.
  41277. * @param {number} y - The y coordinate of the top-left of the Rectangle.
  41278. * @param {number} width - The width of the Rectangle.
  41279. * @param {number} height - The height of the Rectangle.
  41280. * @param {string} [fillStyle] - If set the context fillStyle will be set to this value before the rect is drawn.
  41281. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41282. */
  41283. rect: function (x, y, width, height, fillStyle) {
  41284. if (typeof fillStyle !== 'undefined')
  41285. {
  41286. this.context.fillStyle = fillStyle;
  41287. }
  41288. this.context.fillRect(x, y, width, height);
  41289. return this;
  41290. },
  41291. /**
  41292. * Draws text to the BitmapData in the given font and color.
  41293. * The default font is 14px Courier, so useful for quickly drawing debug text.
  41294. * If you need to do a lot of font work to this BitmapData we'd recommend implementing your own text draw method.
  41295. *
  41296. * @method Phaser.BitmapData#text
  41297. * @param {string} text - The text to write to the BitmapData.
  41298. * @param {number} x - The x coordinate of the top-left of the text string.
  41299. * @param {number} y - The y coordinate of the top-left of the text string.
  41300. * @param {string} [font='14px Courier'] - The font. This is passed directly to Context.font, so anything that can support, this can.
  41301. * @param {string} [color='rgb(255,255,255)'] - The color the text will be drawn in.
  41302. * @param {boolean} [shadow=true] - Draw a single pixel black shadow below the text (offset by text.x/y + 1)
  41303. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41304. */
  41305. text: function (text, x, y, font, color, shadow) {
  41306. if (x === undefined) { x = 0; }
  41307. if (y === undefined) { y = 0; }
  41308. if (font === undefined) { font = '14px Courier'; }
  41309. if (color === undefined) { color = 'rgb(255,255,255)'; }
  41310. if (shadow === undefined) { shadow = true; }
  41311. var ctx = this.context;
  41312. var prevFont = ctx.font;
  41313. ctx.font = font;
  41314. if (shadow)
  41315. {
  41316. ctx.fillStyle = 'rgb(0,0,0)';
  41317. ctx.fillText(text, x + 1, y + 1);
  41318. }
  41319. ctx.fillStyle = color;
  41320. ctx.fillText(text, x, y);
  41321. ctx.font = prevFont;
  41322. },
  41323. /**
  41324. * Draws a filled Circle to the BitmapData at the given x, y coordinates and radius in size.
  41325. *
  41326. * @method Phaser.BitmapData#circle
  41327. * @param {number} x - The x coordinate to draw the Circle at. This is the center of the circle.
  41328. * @param {number} y - The y coordinate to draw the Circle at. This is the center of the circle.
  41329. * @param {number} radius - The radius of the Circle in pixels. The radius is half the diameter.
  41330. * @param {string} [fillStyle] - If set the context fillStyle will be set to this value before the circle is drawn.
  41331. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41332. */
  41333. circle: function (x, y, radius, fillStyle) {
  41334. var ctx = this.context;
  41335. if (fillStyle !== undefined)
  41336. {
  41337. ctx.fillStyle = fillStyle;
  41338. }
  41339. ctx.beginPath();
  41340. ctx.arc(x, y, radius, 0, Math.PI * 2, false);
  41341. ctx.closePath();
  41342. ctx.fill();
  41343. return this;
  41344. },
  41345. /**
  41346. * Draws a line between the coordinates given in the color and thickness specified.
  41347. *
  41348. * @method Phaser.BitmapData#line
  41349. * @param {number} x1 - The x coordinate to start the line from.
  41350. * @param {number} y1 - The y coordinate to start the line from.
  41351. * @param {number} x2 - The x coordinate to draw the line to.
  41352. * @param {number} y2 - The y coordinate to draw the line to.
  41353. * @param {string} [color='#fff'] - The stroke color that the line will be drawn in.
  41354. * @param {number} [width=1] - The line thickness.
  41355. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41356. */
  41357. line: function (x1, y1, x2, y2, color, width) {
  41358. if (color === undefined) { color = '#fff'; }
  41359. if (width === undefined) { width = 1; }
  41360. var ctx = this.context;
  41361. ctx.beginPath();
  41362. ctx.moveTo(x1, y1);
  41363. ctx.lineTo(x2, y2);
  41364. ctx.lineWidth = width;
  41365. ctx.strokeStyle = color;
  41366. ctx.stroke();
  41367. ctx.closePath();
  41368. return this;
  41369. },
  41370. /**
  41371. * Takes the given Line object and image and renders it to this BitmapData as a repeating texture line.
  41372. *
  41373. * @method Phaser.BitmapData#textureLine
  41374. * @param {Phaser.Line} line - A Phaser.Line object that will be used to plot the start and end of the line.
  41375. * @param {string|Image} image - The key of an image in the Phaser.Cache to use as the texture for this line, or an actual Image.
  41376. * @param {string} [repeat='repeat-x'] - The pattern repeat mode to use when drawing the line. Either `repeat`, `repeat-x` or `no-repeat`.
  41377. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41378. */
  41379. textureLine: function (line, image, repeat) {
  41380. if (repeat === undefined) { repeat = 'repeat-x'; }
  41381. if (typeof image === 'string')
  41382. {
  41383. image = this.game.cache.getImage(image);
  41384. if (!image)
  41385. {
  41386. return;
  41387. }
  41388. }
  41389. var width = line.length;
  41390. if (repeat === 'no-repeat' && width > image.width)
  41391. {
  41392. width = image.width;
  41393. }
  41394. var ctx = this.context;
  41395. ctx.fillStyle = ctx.createPattern(image, repeat);
  41396. this._circle = new Phaser.Circle(line.start.x, line.start.y, image.height);
  41397. this._circle.circumferencePoint(line.angle - 1.5707963267948966, false, this._pos);
  41398. ctx.save();
  41399. ctx.translate(this._pos.x, this._pos.y);
  41400. ctx.rotate(line.angle);
  41401. ctx.fillRect(0, 0, width, image.height);
  41402. ctx.restore();
  41403. this.dirty = true;
  41404. return this;
  41405. },
  41406. /**
  41407. * If the game is running in WebGL this will push the texture up to the GPU if it's dirty.
  41408. * 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.
  41409. * If you wish to suppress this functionality set BitmapData.disableTextureUpload to `true`.
  41410. *
  41411. * @method Phaser.BitmapData#render
  41412. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41413. */
  41414. render: function () {
  41415. if (!this.disableTextureUpload && this.dirty)
  41416. {
  41417. this.baseTexture.dirty();
  41418. this.dirty = false;
  41419. }
  41420. return this;
  41421. },
  41422. /**
  41423. * Destroys this BitmapData and puts the canvas it was using back into the canvas pool for re-use.
  41424. *
  41425. * @method Phaser.BitmapData#destroy
  41426. */
  41427. destroy: function () {
  41428. this.frameData.destroy();
  41429. this.texture.destroy(true);
  41430. PIXI.CanvasPool.remove(this);
  41431. },
  41432. /**
  41433. * Resets the blend mode (effectively sets it to 'source-over')
  41434. *
  41435. * @method Phaser.BitmapData#blendReset
  41436. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41437. */
  41438. blendReset: function () {
  41439. this.op = 'source-over';
  41440. return this;
  41441. },
  41442. /**
  41443. * Sets the blend mode to 'source-over'
  41444. *
  41445. * @method Phaser.BitmapData#blendSourceOver
  41446. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41447. */
  41448. blendSourceOver: function () {
  41449. this.op = 'source-over';
  41450. return this;
  41451. },
  41452. /**
  41453. * Sets the blend mode to 'source-in'
  41454. *
  41455. * @method Phaser.BitmapData#blendSourceIn
  41456. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41457. */
  41458. blendSourceIn: function () {
  41459. this.op = 'source-in';
  41460. return this;
  41461. },
  41462. /**
  41463. * Sets the blend mode to 'source-out'
  41464. *
  41465. * @method Phaser.BitmapData#blendSourceOut
  41466. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41467. */
  41468. blendSourceOut: function () {
  41469. this.op = 'source-out';
  41470. return this;
  41471. },
  41472. /**
  41473. * Sets the blend mode to 'source-atop'
  41474. *
  41475. * @method Phaser.BitmapData#blendSourceAtop
  41476. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41477. */
  41478. blendSourceAtop: function () {
  41479. this.op = 'source-atop';
  41480. return this;
  41481. },
  41482. /**
  41483. * Sets the blend mode to 'destination-over'
  41484. *
  41485. * @method Phaser.BitmapData#blendDestinationOver
  41486. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41487. */
  41488. blendDestinationOver: function () {
  41489. this.op = 'destination-over';
  41490. return this;
  41491. },
  41492. /**
  41493. * Sets the blend mode to 'destination-in'
  41494. *
  41495. * @method Phaser.BitmapData#blendDestinationIn
  41496. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41497. */
  41498. blendDestinationIn: function () {
  41499. this.op = 'destination-in';
  41500. return this;
  41501. },
  41502. /**
  41503. * Sets the blend mode to 'destination-out'
  41504. *
  41505. * @method Phaser.BitmapData#blendDestinationOut
  41506. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41507. */
  41508. blendDestinationOut: function () {
  41509. this.op = 'destination-out';
  41510. return this;
  41511. },
  41512. /**
  41513. * Sets the blend mode to 'destination-atop'
  41514. *
  41515. * @method Phaser.BitmapData#blendDestinationAtop
  41516. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41517. */
  41518. blendDestinationAtop: function () {
  41519. this.op = 'destination-atop';
  41520. return this;
  41521. },
  41522. /**
  41523. * Sets the blend mode to 'xor'
  41524. *
  41525. * @method Phaser.BitmapData#blendXor
  41526. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41527. */
  41528. blendXor: function () {
  41529. this.op = 'xor';
  41530. return this;
  41531. },
  41532. /**
  41533. * Sets the blend mode to 'lighter'
  41534. *
  41535. * @method Phaser.BitmapData#blendAdd
  41536. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41537. */
  41538. blendAdd: function () {
  41539. this.op = 'lighter';
  41540. return this;
  41541. },
  41542. /**
  41543. * Sets the blend mode to 'multiply'
  41544. *
  41545. * @method Phaser.BitmapData#blendMultiply
  41546. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41547. */
  41548. blendMultiply: function () {
  41549. this.op = 'multiply';
  41550. return this;
  41551. },
  41552. /**
  41553. * Sets the blend mode to 'screen'
  41554. *
  41555. * @method Phaser.BitmapData#blendScreen
  41556. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41557. */
  41558. blendScreen: function () {
  41559. this.op = 'screen';
  41560. return this;
  41561. },
  41562. /**
  41563. * Sets the blend mode to 'overlay'
  41564. *
  41565. * @method Phaser.BitmapData#blendOverlay
  41566. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41567. */
  41568. blendOverlay: function () {
  41569. this.op = 'overlay';
  41570. return this;
  41571. },
  41572. /**
  41573. * Sets the blend mode to 'darken'
  41574. *
  41575. * @method Phaser.BitmapData#blendDarken
  41576. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41577. */
  41578. blendDarken: function () {
  41579. this.op = 'darken';
  41580. return this;
  41581. },
  41582. /**
  41583. * Sets the blend mode to 'lighten'
  41584. *
  41585. * @method Phaser.BitmapData#blendLighten
  41586. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41587. */
  41588. blendLighten: function () {
  41589. this.op = 'lighten';
  41590. return this;
  41591. },
  41592. /**
  41593. * Sets the blend mode to 'color-dodge'
  41594. *
  41595. * @method Phaser.BitmapData#blendColorDodge
  41596. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41597. */
  41598. blendColorDodge: function () {
  41599. this.op = 'color-dodge';
  41600. return this;
  41601. },
  41602. /**
  41603. * Sets the blend mode to 'color-burn'
  41604. *
  41605. * @method Phaser.BitmapData#blendColorBurn
  41606. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41607. */
  41608. blendColorBurn: function () {
  41609. this.op = 'color-burn';
  41610. return this;
  41611. },
  41612. /**
  41613. * Sets the blend mode to 'hard-light'
  41614. *
  41615. * @method Phaser.BitmapData#blendHardLight
  41616. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41617. */
  41618. blendHardLight: function () {
  41619. this.op = 'hard-light';
  41620. return this;
  41621. },
  41622. /**
  41623. * Sets the blend mode to 'soft-light'
  41624. *
  41625. * @method Phaser.BitmapData#blendSoftLight
  41626. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41627. */
  41628. blendSoftLight: function () {
  41629. this.op = 'soft-light';
  41630. return this;
  41631. },
  41632. /**
  41633. * Sets the blend mode to 'difference'
  41634. *
  41635. * @method Phaser.BitmapData#blendDifference
  41636. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41637. */
  41638. blendDifference: function () {
  41639. this.op = 'difference';
  41640. return this;
  41641. },
  41642. /**
  41643. * Sets the blend mode to 'exclusion'
  41644. *
  41645. * @method Phaser.BitmapData#blendExclusion
  41646. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41647. */
  41648. blendExclusion: function () {
  41649. this.op = 'exclusion';
  41650. return this;
  41651. },
  41652. /**
  41653. * Sets the blend mode to 'hue'
  41654. *
  41655. * @method Phaser.BitmapData#blendHue
  41656. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41657. */
  41658. blendHue: function () {
  41659. this.op = 'hue';
  41660. return this;
  41661. },
  41662. /**
  41663. * Sets the blend mode to 'saturation'
  41664. *
  41665. * @method Phaser.BitmapData#blendSaturation
  41666. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41667. */
  41668. blendSaturation: function () {
  41669. this.op = 'saturation';
  41670. return this;
  41671. },
  41672. /**
  41673. * Sets the blend mode to 'color'
  41674. *
  41675. * @method Phaser.BitmapData#blendColor
  41676. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41677. */
  41678. blendColor: function () {
  41679. this.op = 'color';
  41680. return this;
  41681. },
  41682. /**
  41683. * Sets the blend mode to 'luminosity'
  41684. *
  41685. * @method Phaser.BitmapData#blendLuminosity
  41686. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41687. */
  41688. blendLuminosity: function () {
  41689. this.op = 'luminosity';
  41690. return this;
  41691. }
  41692. };
  41693. /**
  41694. * @memberof Phaser.BitmapData
  41695. * @property {boolean} smoothed - Gets or sets this BitmapData.contexts smoothing enabled value.
  41696. */
  41697. Object.defineProperty(Phaser.BitmapData.prototype, "smoothed", {
  41698. get: function () {
  41699. Phaser.Canvas.getSmoothingEnabled(this.context);
  41700. },
  41701. set: function (value) {
  41702. Phaser.Canvas.setSmoothingEnabled(this.context, value);
  41703. }
  41704. });
  41705. /**
  41706. * @memberof Phaser.BitmapData
  41707. * @property {string} op - A short-hand code to get or set the global composite operation of the BitmapDatas canvas.
  41708. */
  41709. Object.defineProperty(Phaser.BitmapData.prototype, "op", {
  41710. get: function () {
  41711. return this.context.globalCompositeOperation;
  41712. },
  41713. set: function (value) {
  41714. this.context.globalCompositeOperation = value;
  41715. }
  41716. });
  41717. /**
  41718. * Gets a JavaScript object that has 6 properties set that are used by BitmapData in a transform.
  41719. *
  41720. * @method Phaser.BitmapData.getTransform
  41721. * @param {number} translateX - The x translate value.
  41722. * @param {number} translateY - The y translate value.
  41723. * @param {number} scaleX - The scale x value.
  41724. * @param {number} scaleY - The scale y value.
  41725. * @param {number} skewX - The skew x value.
  41726. * @param {number} skewY - The skew y value.
  41727. * @return {object} A JavaScript object containing all of the properties BitmapData needs for transforms.
  41728. */
  41729. Phaser.BitmapData.getTransform = function (translateX, translateY, scaleX, scaleY, skewX, skewY) {
  41730. if (typeof translateX !== 'number') { translateX = 0; }
  41731. if (typeof translateY !== 'number') { translateY = 0; }
  41732. if (typeof scaleX !== 'number') { scaleX = 1; }
  41733. if (typeof scaleY !== 'number') { scaleY = 1; }
  41734. if (typeof skewX !== 'number') { skewX = 0; }
  41735. if (typeof skewY !== 'number') { skewY = 0; }
  41736. return { sx: scaleX, sy: scaleY, scaleX: scaleX, scaleY: scaleY, skewX: skewX, skewY: skewY, translateX: translateX, translateY: translateY, tx: translateX, ty: translateY };
  41737. };
  41738. Phaser.BitmapData.prototype.constructor = Phaser.BitmapData;
  41739. /**
  41740. * @author Mat Groves http://matgroves.com/ @Doormat23
  41741. */
  41742. /**
  41743. * The Graphics class contains methods used to draw primitive shapes such as lines, circles and rectangles to the display, and color and fill them.
  41744. *
  41745. * @class Graphics
  41746. * @extends DisplayObjectContainer
  41747. * @constructor
  41748. */
  41749. PIXI.Graphics = function()
  41750. {
  41751. PIXI.DisplayObjectContainer.call(this);
  41752. this.renderable = true;
  41753. /**
  41754. * The alpha value used when filling the Graphics object.
  41755. *
  41756. * @property fillAlpha
  41757. * @type Number
  41758. */
  41759. this.fillAlpha = 1;
  41760. /**
  41761. * The width (thickness) of any lines drawn.
  41762. *
  41763. * @property lineWidth
  41764. * @type Number
  41765. */
  41766. this.lineWidth = 0;
  41767. /**
  41768. * The color of any lines drawn.
  41769. *
  41770. * @property lineColor
  41771. * @type String
  41772. * @default 0
  41773. */
  41774. this.lineColor = 0;
  41775. /**
  41776. * Graphics data
  41777. *
  41778. * @property graphicsData
  41779. * @type Array
  41780. * @private
  41781. */
  41782. this.graphicsData = [];
  41783. /**
  41784. * The tint applied to the graphic shape. This is a hex value. Apply a value of 0xFFFFFF to reset the tint.
  41785. *
  41786. * @property tint
  41787. * @type Number
  41788. * @default 0xFFFFFF
  41789. */
  41790. this.tint = 0xFFFFFF;
  41791. /**
  41792. * The blend mode to be applied to the graphic shape. Apply a value of PIXI.blendModes.NORMAL to reset the blend mode.
  41793. *
  41794. * @property blendMode
  41795. * @type Number
  41796. * @default PIXI.blendModes.NORMAL;
  41797. */
  41798. this.blendMode = PIXI.blendModes.NORMAL;
  41799. /**
  41800. * Current path
  41801. *
  41802. * @property currentPath
  41803. * @type Object
  41804. * @private
  41805. */
  41806. this.currentPath = null;
  41807. /**
  41808. * Array containing some WebGL-related properties used by the WebGL renderer.
  41809. *
  41810. * @property _webGL
  41811. * @type Array
  41812. * @private
  41813. */
  41814. this._webGL = [];
  41815. /**
  41816. * Whether this shape is being used as a mask.
  41817. *
  41818. * @property isMask
  41819. * @type Boolean
  41820. */
  41821. this.isMask = false;
  41822. /**
  41823. * The bounds' padding used for bounds calculation.
  41824. *
  41825. * @property boundsPadding
  41826. * @type Number
  41827. */
  41828. this.boundsPadding = 0;
  41829. this._localBounds = new PIXI.Rectangle(0,0,1,1);
  41830. /**
  41831. * Used to detect if the graphics object has changed. If this is set to true then the graphics object will be recalculated.
  41832. *
  41833. * @property dirty
  41834. * @type Boolean
  41835. * @private
  41836. */
  41837. this.dirty = true;
  41838. /**
  41839. * Used to detect if the webgl graphics object has changed. If this is set to true then the graphics object will be recalculated.
  41840. *
  41841. * @property webGLDirty
  41842. * @type Boolean
  41843. * @private
  41844. */
  41845. this.webGLDirty = false;
  41846. /**
  41847. * Used to detect if the cached sprite object needs to be updated.
  41848. *
  41849. * @property cachedSpriteDirty
  41850. * @type Boolean
  41851. * @private
  41852. */
  41853. this.cachedSpriteDirty = false;
  41854. };
  41855. // constructor
  41856. PIXI.Graphics.prototype = Object.create( PIXI.DisplayObjectContainer.prototype );
  41857. PIXI.Graphics.prototype.constructor = PIXI.Graphics;
  41858. /**
  41859. * Specifies the line style used for subsequent calls to Graphics methods such as the lineTo() method or the drawCircle() method.
  41860. *
  41861. * @method lineStyle
  41862. * @param lineWidth {Number} width of the line to draw, will update the objects stored style
  41863. * @param color {Number} color of the line to draw, will update the objects stored style
  41864. * @param alpha {Number} alpha of the line to draw, will update the objects stored style
  41865. * @return {Graphics}
  41866. */
  41867. PIXI.Graphics.prototype.lineStyle = function(lineWidth, color, alpha)
  41868. {
  41869. this.lineWidth = lineWidth || 0;
  41870. this.lineColor = color || 0;
  41871. this.lineAlpha = (alpha === undefined) ? 1 : alpha;
  41872. if (this.currentPath)
  41873. {
  41874. if (this.currentPath.shape.points.length)
  41875. {
  41876. // halfway through a line? start a new one!
  41877. this.drawShape(new PIXI.Polygon(this.currentPath.shape.points.slice(-2)));
  41878. }
  41879. else
  41880. {
  41881. // otherwise its empty so lets just set the line properties
  41882. this.currentPath.lineWidth = this.lineWidth;
  41883. this.currentPath.lineColor = this.lineColor;
  41884. this.currentPath.lineAlpha = this.lineAlpha;
  41885. }
  41886. }
  41887. return this;
  41888. };
  41889. /**
  41890. * Moves the current drawing position to x, y.
  41891. *
  41892. * @method moveTo
  41893. * @param x {Number} the X coordinate to move to
  41894. * @param y {Number} the Y coordinate to move to
  41895. * @return {Graphics}
  41896. */
  41897. PIXI.Graphics.prototype.moveTo = function(x, y)
  41898. {
  41899. this.drawShape(new PIXI.Polygon([x, y]));
  41900. return this;
  41901. };
  41902. /**
  41903. * Draws a line using the current line style from the current drawing position to (x, y);
  41904. * The current drawing position is then set to (x, y).
  41905. *
  41906. * @method lineTo
  41907. * @param x {Number} the X coordinate to draw to
  41908. * @param y {Number} the Y coordinate to draw to
  41909. * @return {Graphics}
  41910. */
  41911. PIXI.Graphics.prototype.lineTo = function(x, y)
  41912. {
  41913. if (!this.currentPath)
  41914. {
  41915. this.moveTo(0, 0);
  41916. }
  41917. this.currentPath.shape.points.push(x, y);
  41918. this.dirty = true;
  41919. return this;
  41920. };
  41921. /**
  41922. * Calculate the points for a quadratic bezier curve and then draws it.
  41923. * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c
  41924. *
  41925. * @method quadraticCurveTo
  41926. * @param cpX {Number} Control point x
  41927. * @param cpY {Number} Control point y
  41928. * @param toX {Number} Destination point x
  41929. * @param toY {Number} Destination point y
  41930. * @return {Graphics}
  41931. */
  41932. PIXI.Graphics.prototype.quadraticCurveTo = function(cpX, cpY, toX, toY)
  41933. {
  41934. if (this.currentPath)
  41935. {
  41936. if (this.currentPath.shape.points.length === 0)
  41937. {
  41938. this.currentPath.shape.points = [0, 0];
  41939. }
  41940. }
  41941. else
  41942. {
  41943. this.moveTo(0,0);
  41944. }
  41945. var xa,
  41946. ya,
  41947. n = 20,
  41948. points = this.currentPath.shape.points;
  41949. if (points.length === 0)
  41950. {
  41951. this.moveTo(0, 0);
  41952. }
  41953. var fromX = points[points.length - 2];
  41954. var fromY = points[points.length - 1];
  41955. var j = 0;
  41956. for (var i = 1; i <= n; ++i)
  41957. {
  41958. j = i / n;
  41959. xa = fromX + ( (cpX - fromX) * j );
  41960. ya = fromY + ( (cpY - fromY) * j );
  41961. points.push( xa + ( ((cpX + ( (toX - cpX) * j )) - xa) * j ),
  41962. ya + ( ((cpY + ( (toY - cpY) * j )) - ya) * j ) );
  41963. }
  41964. this.dirty = true;
  41965. return this;
  41966. };
  41967. /**
  41968. * Calculate the points for a bezier curve and then draws it.
  41969. *
  41970. * @method bezierCurveTo
  41971. * @param cpX {Number} Control point x
  41972. * @param cpY {Number} Control point y
  41973. * @param cpX2 {Number} Second Control point x
  41974. * @param cpY2 {Number} Second Control point y
  41975. * @param toX {Number} Destination point x
  41976. * @param toY {Number} Destination point y
  41977. * @return {Graphics}
  41978. */
  41979. PIXI.Graphics.prototype.bezierCurveTo = function(cpX, cpY, cpX2, cpY2, toX, toY)
  41980. {
  41981. if (this.currentPath)
  41982. {
  41983. if (this.currentPath.shape.points.length === 0)
  41984. {
  41985. this.currentPath.shape.points = [0, 0];
  41986. }
  41987. }
  41988. else
  41989. {
  41990. this.moveTo(0,0);
  41991. }
  41992. var n = 20,
  41993. dt,
  41994. dt2,
  41995. dt3,
  41996. t2,
  41997. t3,
  41998. points = this.currentPath.shape.points;
  41999. var fromX = points[points.length-2];
  42000. var fromY = points[points.length-1];
  42001. var j = 0;
  42002. for (var i = 1; i <= n; ++i)
  42003. {
  42004. j = i / n;
  42005. dt = (1 - j);
  42006. dt2 = dt * dt;
  42007. dt3 = dt2 * dt;
  42008. t2 = j * j;
  42009. t3 = t2 * j;
  42010. points.push( dt3 * fromX + 3 * dt2 * j * cpX + 3 * dt * t2 * cpX2 + t3 * toX,
  42011. dt3 * fromY + 3 * dt2 * j * cpY + 3 * dt * t2 * cpY2 + t3 * toY);
  42012. }
  42013. this.dirty = true;
  42014. return this;
  42015. };
  42016. /*
  42017. * The arcTo() method creates an arc/curve between two tangents on the canvas.
  42018. *
  42019. * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google!
  42020. *
  42021. * @method arcTo
  42022. * @param x1 {Number} The x-coordinate of the beginning of the arc
  42023. * @param y1 {Number} The y-coordinate of the beginning of the arc
  42024. * @param x2 {Number} The x-coordinate of the end of the arc
  42025. * @param y2 {Number} The y-coordinate of the end of the arc
  42026. * @param radius {Number} The radius of the arc
  42027. * @return {Graphics}
  42028. */
  42029. PIXI.Graphics.prototype.arcTo = function(x1, y1, x2, y2, radius)
  42030. {
  42031. if (this.currentPath)
  42032. {
  42033. if (this.currentPath.shape.points.length === 0)
  42034. {
  42035. this.currentPath.shape.points.push(x1, y1);
  42036. }
  42037. }
  42038. else
  42039. {
  42040. this.moveTo(x1, y1);
  42041. }
  42042. var points = this.currentPath.shape.points,
  42043. fromX = points[points.length-2],
  42044. fromY = points[points.length-1],
  42045. a1 = fromY - y1,
  42046. b1 = fromX - x1,
  42047. a2 = y2 - y1,
  42048. b2 = x2 - x1,
  42049. mm = Math.abs(a1 * b2 - b1 * a2);
  42050. if (mm < 1.0e-8 || radius === 0)
  42051. {
  42052. if (points[points.length-2] !== x1 || points[points.length-1] !== y1)
  42053. {
  42054. points.push(x1, y1);
  42055. }
  42056. }
  42057. else
  42058. {
  42059. var dd = a1 * a1 + b1 * b1,
  42060. cc = a2 * a2 + b2 * b2,
  42061. tt = a1 * a2 + b1 * b2,
  42062. k1 = radius * Math.sqrt(dd) / mm,
  42063. k2 = radius * Math.sqrt(cc) / mm,
  42064. j1 = k1 * tt / dd,
  42065. j2 = k2 * tt / cc,
  42066. cx = k1 * b2 + k2 * b1,
  42067. cy = k1 * a2 + k2 * a1,
  42068. px = b1 * (k2 + j1),
  42069. py = a1 * (k2 + j1),
  42070. qx = b2 * (k1 + j2),
  42071. qy = a2 * (k1 + j2),
  42072. startAngle = Math.atan2(py - cy, px - cx),
  42073. endAngle = Math.atan2(qy - cy, qx - cx);
  42074. this.arc(cx + x1, cy + y1, radius, startAngle, endAngle, b1 * a2 > b2 * a1);
  42075. }
  42076. this.dirty = true;
  42077. return this;
  42078. };
  42079. /**
  42080. * The arc method creates an arc/curve (used to create circles, or parts of circles).
  42081. *
  42082. * @method arc
  42083. * @param cx {Number} The x-coordinate of the center of the circle
  42084. * @param cy {Number} The y-coordinate of the center of the circle
  42085. * @param radius {Number} The radius of the circle
  42086. * @param startAngle {Number} The starting angle, in radians (0 is at the 3 o'clock position of the arc's circle)
  42087. * @param endAngle {Number} The ending angle, in radians
  42088. * @param anticlockwise {Boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise.
  42089. * @param segments {Number} Optional. The number of segments to use when calculating the arc. The default is 40. If you need more fidelity use a higher number.
  42090. * @return {Graphics}
  42091. */
  42092. PIXI.Graphics.prototype.arc = function(cx, cy, radius, startAngle, endAngle, anticlockwise, segments)
  42093. {
  42094. // If we do this we can never draw a full circle
  42095. if (startAngle === endAngle)
  42096. {
  42097. return this;
  42098. }
  42099. if (anticlockwise === undefined) { anticlockwise = false; }
  42100. if (segments === undefined) { segments = 40; }
  42101. if (!anticlockwise && endAngle <= startAngle)
  42102. {
  42103. endAngle += Math.PI * 2;
  42104. }
  42105. else if (anticlockwise && startAngle <= endAngle)
  42106. {
  42107. startAngle += Math.PI * 2;
  42108. }
  42109. var sweep = anticlockwise ? (startAngle - endAngle) * -1 : (endAngle - startAngle);
  42110. var segs = Math.ceil(Math.abs(sweep) / (Math.PI * 2)) * segments;
  42111. // Sweep check - moved here because we don't want to do the moveTo below if the arc fails
  42112. if (sweep === 0)
  42113. {
  42114. return this;
  42115. }
  42116. var startX = cx + Math.cos(startAngle) * radius;
  42117. var startY = cy + Math.sin(startAngle) * radius;
  42118. if (anticlockwise && this.filling)
  42119. {
  42120. this.moveTo(cx, cy);
  42121. }
  42122. else
  42123. {
  42124. this.moveTo(startX, startY);
  42125. }
  42126. // currentPath will always exist after calling a moveTo
  42127. var points = this.currentPath.shape.points;
  42128. var theta = sweep / (segs * 2);
  42129. var theta2 = theta * 2;
  42130. var cTheta = Math.cos(theta);
  42131. var sTheta = Math.sin(theta);
  42132. var segMinus = segs - 1;
  42133. var remainder = (segMinus % 1) / segMinus;
  42134. for (var i = 0; i <= segMinus; i++)
  42135. {
  42136. var real = i + remainder * i;
  42137. var angle = ((theta) + startAngle + (theta2 * real));
  42138. var c = Math.cos(angle);
  42139. var s = -Math.sin(angle);
  42140. points.push(( (cTheta * c) + (sTheta * s) ) * radius + cx,
  42141. ( (cTheta * -s) + (sTheta * c) ) * radius + cy);
  42142. }
  42143. this.dirty = true;
  42144. return this;
  42145. };
  42146. /**
  42147. * Specifies a simple one-color fill that subsequent calls to other Graphics methods
  42148. * (such as lineTo() or drawCircle()) use when drawing.
  42149. *
  42150. * @method beginFill
  42151. * @param color {Number} the color of the fill
  42152. * @param alpha {Number} the alpha of the fill
  42153. * @return {Graphics}
  42154. */
  42155. PIXI.Graphics.prototype.beginFill = function(color, alpha)
  42156. {
  42157. this.filling = true;
  42158. this.fillColor = color || 0;
  42159. this.fillAlpha = (alpha === undefined) ? 1 : alpha;
  42160. if (this.currentPath)
  42161. {
  42162. if (this.currentPath.shape.points.length <= 2)
  42163. {
  42164. this.currentPath.fill = this.filling;
  42165. this.currentPath.fillColor = this.fillColor;
  42166. this.currentPath.fillAlpha = this.fillAlpha;
  42167. }
  42168. }
  42169. return this;
  42170. };
  42171. /**
  42172. * Applies a fill to the lines and shapes that were added since the last call to the beginFill() method.
  42173. *
  42174. * @method endFill
  42175. * @return {Graphics}
  42176. */
  42177. PIXI.Graphics.prototype.endFill = function()
  42178. {
  42179. this.filling = false;
  42180. this.fillColor = null;
  42181. this.fillAlpha = 1;
  42182. return this;
  42183. };
  42184. /**
  42185. * @method drawRect
  42186. *
  42187. * @param x {Number} The X coord of the top-left of the rectangle
  42188. * @param y {Number} The Y coord of the top-left of the rectangle
  42189. * @param width {Number} The width of the rectangle
  42190. * @param height {Number} The height of the rectangle
  42191. * @return {Graphics}
  42192. */
  42193. PIXI.Graphics.prototype.drawRect = function(x, y, width, height)
  42194. {
  42195. this.drawShape(new PIXI.Rectangle(x, y, width, height));
  42196. return this;
  42197. };
  42198. /**
  42199. * @method drawRoundedRect
  42200. * @param x {Number} The X coord of the top-left of the rectangle
  42201. * @param y {Number} The Y coord of the top-left of the rectangle
  42202. * @param width {Number} The width of the rectangle
  42203. * @param height {Number} The height of the rectangle
  42204. * @param radius {Number} Radius of the rectangle corners. In WebGL this must be a value between 0 and 9.
  42205. */
  42206. PIXI.Graphics.prototype.drawRoundedRect = function(x, y, width, height, radius)
  42207. {
  42208. this.drawShape(new PIXI.RoundedRectangle(x, y, width, height, radius));
  42209. return this;
  42210. };
  42211. /**
  42212. * Draws a circle.
  42213. *
  42214. * @method drawCircle
  42215. * @param x {Number} The X coordinate of the center of the circle
  42216. * @param y {Number} The Y coordinate of the center of the circle
  42217. * @param diameter {Number} The diameter of the circle
  42218. * @return {Graphics}
  42219. */
  42220. PIXI.Graphics.prototype.drawCircle = function(x, y, diameter)
  42221. {
  42222. this.drawShape(new PIXI.Circle(x, y, diameter));
  42223. return this;
  42224. };
  42225. /**
  42226. * Draws an ellipse.
  42227. *
  42228. * @method drawEllipse
  42229. * @param x {Number} The X coordinate of the center of the ellipse
  42230. * @param y {Number} The Y coordinate of the center of the ellipse
  42231. * @param width {Number} The half width of the ellipse
  42232. * @param height {Number} The half height of the ellipse
  42233. * @return {Graphics}
  42234. */
  42235. PIXI.Graphics.prototype.drawEllipse = function(x, y, width, height)
  42236. {
  42237. this.drawShape(new PIXI.Ellipse(x, y, width, height));
  42238. return this;
  42239. };
  42240. /**
  42241. * Draws a polygon using the given path.
  42242. *
  42243. * @method drawPolygon
  42244. * @param path {Array|Phaser.Polygon} The path data used to construct the polygon. Can either be an array of points or a Phaser.Polygon object.
  42245. * @return {Graphics}
  42246. */
  42247. PIXI.Graphics.prototype.drawPolygon = function(path)
  42248. {
  42249. if (path instanceof Phaser.Polygon || path instanceof PIXI.Polygon)
  42250. {
  42251. path = path.points;
  42252. }
  42253. // prevents an argument assignment deopt
  42254. // see section 3.1: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments
  42255. var points = path;
  42256. if (!Array.isArray(points))
  42257. {
  42258. // prevents an argument leak deopt
  42259. // see section 3.2: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments
  42260. points = new Array(arguments.length);
  42261. for (var i = 0; i < points.length; ++i)
  42262. {
  42263. points[i] = arguments[i];
  42264. }
  42265. }
  42266. this.drawShape(new Phaser.Polygon(points));
  42267. return this;
  42268. };
  42269. /**
  42270. * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings.
  42271. *
  42272. * @method clear
  42273. * @return {Graphics}
  42274. */
  42275. PIXI.Graphics.prototype.clear = function()
  42276. {
  42277. this.lineWidth = 0;
  42278. this.filling = false;
  42279. this.dirty = true;
  42280. this.clearDirty = true;
  42281. this.graphicsData = [];
  42282. return this;
  42283. };
  42284. /**
  42285. * Useful function that returns a texture of the graphics object that can then be used to create sprites
  42286. * This can be quite useful if your geometry is complicated and needs to be reused multiple times.
  42287. *
  42288. * @method generateTexture
  42289. * @param [resolution=1] {Number} The resolution of the texture being generated
  42290. * @param [scaleMode=0] {Number} Should be one of the PIXI.scaleMode consts
  42291. * @param [padding=0] {Number} Add optional extra padding to the generated texture (default 0)
  42292. * @return {Texture} a texture of the graphics object
  42293. */
  42294. PIXI.Graphics.prototype.generateTexture = function(resolution, scaleMode, padding)
  42295. {
  42296. if (resolution === undefined) { resolution = 1; }
  42297. if (scaleMode === undefined) { scaleMode = PIXI.scaleModes.DEFAULT; }
  42298. if (padding === undefined) { padding = 0; }
  42299. var bounds = this.getBounds();
  42300. bounds.width += padding;
  42301. bounds.height += padding;
  42302. var canvasBuffer = new PIXI.CanvasBuffer(bounds.width * resolution, bounds.height * resolution);
  42303. var texture = PIXI.Texture.fromCanvas(canvasBuffer.canvas, scaleMode);
  42304. texture.baseTexture.resolution = resolution;
  42305. canvasBuffer.context.scale(resolution, resolution);
  42306. canvasBuffer.context.translate(-bounds.x, -bounds.y);
  42307. // Call here
  42308. PIXI.CanvasGraphics.renderGraphics(this, canvasBuffer.context);
  42309. return texture;
  42310. };
  42311. /**
  42312. * Renders the object using the WebGL renderer
  42313. *
  42314. * @method _renderWebGL
  42315. * @param renderSession {RenderSession}
  42316. * @private
  42317. */
  42318. PIXI.Graphics.prototype._renderWebGL = function(renderSession)
  42319. {
  42320. // if the sprite is not visible or the alpha is 0 then no need to render this element
  42321. if (this.visible === false || this.alpha === 0 || this.isMask === true) return;
  42322. if (this._cacheAsBitmap)
  42323. {
  42324. if (this.dirty || this.cachedSpriteDirty)
  42325. {
  42326. this._generateCachedSprite();
  42327. // we will also need to update the texture on the gpu too!
  42328. this.updateCachedSpriteTexture();
  42329. this.cachedSpriteDirty = false;
  42330. this.dirty = false;
  42331. }
  42332. this._cachedSprite.worldAlpha = this.worldAlpha;
  42333. PIXI.Sprite.prototype._renderWebGL.call(this._cachedSprite, renderSession);
  42334. return;
  42335. }
  42336. else
  42337. {
  42338. renderSession.spriteBatch.stop();
  42339. renderSession.blendModeManager.setBlendMode(this.blendMode);
  42340. if (this._mask) renderSession.maskManager.pushMask(this._mask, renderSession);
  42341. if (this._filters) renderSession.filterManager.pushFilter(this._filterBlock);
  42342. // check blend mode
  42343. if (this.blendMode !== renderSession.spriteBatch.currentBlendMode)
  42344. {
  42345. renderSession.spriteBatch.currentBlendMode = this.blendMode;
  42346. var blendModeWebGL = PIXI.blendModesWebGL[renderSession.spriteBatch.currentBlendMode];
  42347. renderSession.spriteBatch.gl.blendFunc(blendModeWebGL[0], blendModeWebGL[1]);
  42348. }
  42349. // check if the webgl graphic needs to be updated
  42350. if (this.webGLDirty)
  42351. {
  42352. this.dirty = true;
  42353. this.webGLDirty = false;
  42354. }
  42355. PIXI.WebGLGraphics.renderGraphics(this, renderSession);
  42356. // only render if it has children!
  42357. if (this.children.length)
  42358. {
  42359. renderSession.spriteBatch.start();
  42360. // simple render children!
  42361. for (var i = 0; i < this.children.length; i++)
  42362. {
  42363. this.children[i]._renderWebGL(renderSession);
  42364. }
  42365. renderSession.spriteBatch.stop();
  42366. }
  42367. if (this._filters) renderSession.filterManager.popFilter();
  42368. if (this._mask) renderSession.maskManager.popMask(this.mask, renderSession);
  42369. renderSession.drawCount++;
  42370. renderSession.spriteBatch.start();
  42371. }
  42372. };
  42373. /**
  42374. * Renders the object using the Canvas renderer
  42375. *
  42376. * @method _renderCanvas
  42377. * @param renderSession {RenderSession}
  42378. * @private
  42379. */
  42380. PIXI.Graphics.prototype._renderCanvas = function(renderSession)
  42381. {
  42382. // if the sprite is not visible or the alpha is 0 then no need to render this element
  42383. if (this.visible === false || this.alpha === 0 || this.isMask === true) return;
  42384. // if the tint has changed, set the graphics object to dirty.
  42385. if (this._prevTint !== this.tint) {
  42386. this.dirty = true;
  42387. this._prevTint = this.tint;
  42388. }
  42389. if (this._cacheAsBitmap)
  42390. {
  42391. if (this.dirty || this.cachedSpriteDirty)
  42392. {
  42393. this._generateCachedSprite();
  42394. // we will also need to update the texture
  42395. this.updateCachedSpriteTexture();
  42396. this.cachedSpriteDirty = false;
  42397. this.dirty = false;
  42398. }
  42399. this._cachedSprite.alpha = this.alpha;
  42400. PIXI.Sprite.prototype._renderCanvas.call(this._cachedSprite, renderSession);
  42401. return;
  42402. }
  42403. else
  42404. {
  42405. var context = renderSession.context;
  42406. var transform = this.worldTransform;
  42407. if (this.blendMode !== renderSession.currentBlendMode)
  42408. {
  42409. renderSession.currentBlendMode = this.blendMode;
  42410. context.globalCompositeOperation = PIXI.blendModesCanvas[renderSession.currentBlendMode];
  42411. }
  42412. if (this._mask)
  42413. {
  42414. renderSession.maskManager.pushMask(this._mask, renderSession);
  42415. }
  42416. var resolution = renderSession.resolution;
  42417. var tx = (transform.tx * renderSession.resolution) + renderSession.shakeX;
  42418. var ty = (transform.ty * renderSession.resolution) + renderSession.shakeY;
  42419. context.setTransform(transform.a * resolution,
  42420. transform.b * resolution,
  42421. transform.c * resolution,
  42422. transform.d * resolution,
  42423. tx,
  42424. ty);
  42425. PIXI.CanvasGraphics.renderGraphics(this, context);
  42426. // simple render children!
  42427. for (var i = 0; i < this.children.length; i++)
  42428. {
  42429. this.children[i]._renderCanvas(renderSession);
  42430. }
  42431. if (this._mask)
  42432. {
  42433. renderSession.maskManager.popMask(renderSession);
  42434. }
  42435. }
  42436. };
  42437. /**
  42438. * Retrieves the bounds of the graphic shape as a rectangle object
  42439. *
  42440. * @method getBounds
  42441. * @return {Rectangle} the rectangular bounding area
  42442. */
  42443. PIXI.Graphics.prototype.getBounds = function(matrix)
  42444. {
  42445. if (!this._currentBounds)
  42446. {
  42447. // Return an empty object if the item is a mask!
  42448. if (!this.renderable)
  42449. {
  42450. return PIXI.EmptyRectangle;
  42451. }
  42452. if (this.dirty)
  42453. {
  42454. this.updateLocalBounds();
  42455. this.webGLDirty = true;
  42456. this.cachedSpriteDirty = true;
  42457. this.dirty = false;
  42458. }
  42459. var bounds = this._localBounds;
  42460. var w0 = bounds.x;
  42461. var w1 = bounds.width + bounds.x;
  42462. var h0 = bounds.y;
  42463. var h1 = bounds.height + bounds.y;
  42464. var worldTransform = matrix || this.worldTransform;
  42465. var a = worldTransform.a;
  42466. var b = worldTransform.b;
  42467. var c = worldTransform.c;
  42468. var d = worldTransform.d;
  42469. var tx = worldTransform.tx;
  42470. var ty = worldTransform.ty;
  42471. var x1 = a * w1 + c * h1 + tx;
  42472. var y1 = d * h1 + b * w1 + ty;
  42473. var x2 = a * w0 + c * h1 + tx;
  42474. var y2 = d * h1 + b * w0 + ty;
  42475. var x3 = a * w0 + c * h0 + tx;
  42476. var y3 = d * h0 + b * w0 + ty;
  42477. var x4 = a * w1 + c * h0 + tx;
  42478. var y4 = d * h0 + b * w1 + ty;
  42479. var maxX = x1;
  42480. var maxY = y1;
  42481. var minX = x1;
  42482. var minY = y1;
  42483. minX = x2 < minX ? x2 : minX;
  42484. minX = x3 < minX ? x3 : minX;
  42485. minX = x4 < minX ? x4 : minX;
  42486. minY = y2 < minY ? y2 : minY;
  42487. minY = y3 < minY ? y3 : minY;
  42488. minY = y4 < minY ? y4 : minY;
  42489. maxX = x2 > maxX ? x2 : maxX;
  42490. maxX = x3 > maxX ? x3 : maxX;
  42491. maxX = x4 > maxX ? x4 : maxX;
  42492. maxY = y2 > maxY ? y2 : maxY;
  42493. maxY = y3 > maxY ? y3 : maxY;
  42494. maxY = y4 > maxY ? y4 : maxY;
  42495. this._bounds.x = minX;
  42496. this._bounds.width = maxX - minX;
  42497. this._bounds.y = minY;
  42498. this._bounds.height = maxY - minY;
  42499. this._currentBounds = this._bounds;
  42500. }
  42501. return this._currentBounds;
  42502. };
  42503. /**
  42504. * Tests if a point is inside this graphics object
  42505. *
  42506. * @param point {Point} the point to test
  42507. * @return {boolean} the result of the test
  42508. */
  42509. PIXI.Graphics.prototype.containsPoint = function( point )
  42510. {
  42511. this.worldTransform.applyInverse(point, tempPoint);
  42512. var graphicsData = this.graphicsData;
  42513. for (var i = 0; i < graphicsData.length; i++)
  42514. {
  42515. var data = graphicsData[i];
  42516. if (!data.fill)
  42517. {
  42518. continue;
  42519. }
  42520. // only deal with fills..
  42521. if (data.shape)
  42522. {
  42523. if (data.shape.contains(tempPoint.x, tempPoint.y))
  42524. {
  42525. return true;
  42526. }
  42527. }
  42528. }
  42529. return false;
  42530. };
  42531. /**
  42532. * Update the bounds of the object
  42533. *
  42534. * @method updateLocalBounds
  42535. */
  42536. PIXI.Graphics.prototype.updateLocalBounds = function()
  42537. {
  42538. var minX = Infinity;
  42539. var maxX = -Infinity;
  42540. var minY = Infinity;
  42541. var maxY = -Infinity;
  42542. if (this.graphicsData.length)
  42543. {
  42544. var shape, points, x, y, w, h;
  42545. for (var i = 0; i < this.graphicsData.length; i++)
  42546. {
  42547. var data = this.graphicsData[i];
  42548. var type = data.type;
  42549. var lineWidth = data.lineWidth;
  42550. shape = data.shape;
  42551. if (type === PIXI.Graphics.RECT || type === PIXI.Graphics.RREC)
  42552. {
  42553. x = shape.x - lineWidth / 2;
  42554. y = shape.y - lineWidth / 2;
  42555. w = shape.width + lineWidth;
  42556. h = shape.height + lineWidth;
  42557. minX = x < minX ? x : minX;
  42558. maxX = x + w > maxX ? x + w : maxX;
  42559. minY = y < minY ? y : minY;
  42560. maxY = y + h > maxY ? y + h : maxY;
  42561. }
  42562. else if (type === PIXI.Graphics.CIRC)
  42563. {
  42564. x = shape.x;
  42565. y = shape.y;
  42566. w = shape.radius + lineWidth / 2;
  42567. h = shape.radius + lineWidth / 2;
  42568. minX = x - w < minX ? x - w : minX;
  42569. maxX = x + w > maxX ? x + w : maxX;
  42570. minY = y - h < minY ? y - h : minY;
  42571. maxY = y + h > maxY ? y + h : maxY;
  42572. }
  42573. else if (type === PIXI.Graphics.ELIP)
  42574. {
  42575. x = shape.x;
  42576. y = shape.y;
  42577. w = shape.width + lineWidth / 2;
  42578. h = shape.height + lineWidth / 2;
  42579. minX = x - w < minX ? x - w : minX;
  42580. maxX = x + w > maxX ? x + w : maxX;
  42581. minY = y - h < minY ? y - h : minY;
  42582. maxY = y + h > maxY ? y + h : maxY;
  42583. }
  42584. else
  42585. {
  42586. // POLY - assumes points are sequential, not Point objects
  42587. points = shape.points;
  42588. for (var j = 0; j < points.length; j++)
  42589. {
  42590. if (points[j] instanceof Phaser.Point)
  42591. {
  42592. x = points[j].x;
  42593. y = points[j].y;
  42594. }
  42595. else
  42596. {
  42597. x = points[j];
  42598. y = points[j + 1];
  42599. if (j < points.length - 1)
  42600. {
  42601. j++;
  42602. }
  42603. }
  42604. minX = x - lineWidth < minX ? x - lineWidth : minX;
  42605. maxX = x + lineWidth > maxX ? x + lineWidth : maxX;
  42606. minY = y - lineWidth < minY ? y - lineWidth : minY;
  42607. maxY = y + lineWidth > maxY ? y + lineWidth : maxY;
  42608. }
  42609. }
  42610. }
  42611. }
  42612. else
  42613. {
  42614. minX = 0;
  42615. maxX = 0;
  42616. minY = 0;
  42617. maxY = 0;
  42618. }
  42619. var padding = this.boundsPadding;
  42620. this._localBounds.x = minX - padding;
  42621. this._localBounds.width = (maxX - minX) + padding * 2;
  42622. this._localBounds.y = minY - padding;
  42623. this._localBounds.height = (maxY - minY) + padding * 2;
  42624. };
  42625. /**
  42626. * Generates the cached sprite when the sprite has cacheAsBitmap = true
  42627. *
  42628. * @method _generateCachedSprite
  42629. * @private
  42630. */
  42631. PIXI.Graphics.prototype._generateCachedSprite = function()
  42632. {
  42633. var bounds = this.getLocalBounds();
  42634. if (!this._cachedSprite)
  42635. {
  42636. var canvasBuffer = new PIXI.CanvasBuffer(bounds.width, bounds.height);
  42637. var texture = PIXI.Texture.fromCanvas(canvasBuffer.canvas);
  42638. this._cachedSprite = new PIXI.Sprite(texture);
  42639. this._cachedSprite.buffer = canvasBuffer;
  42640. this._cachedSprite.worldTransform = this.worldTransform;
  42641. }
  42642. else
  42643. {
  42644. this._cachedSprite.buffer.resize(bounds.width, bounds.height);
  42645. }
  42646. // leverage the anchor to account for the offset of the element
  42647. this._cachedSprite.anchor.x = -(bounds.x / bounds.width);
  42648. this._cachedSprite.anchor.y = -(bounds.y / bounds.height);
  42649. // this._cachedSprite.buffer.context.save();
  42650. this._cachedSprite.buffer.context.translate(-bounds.x, -bounds.y);
  42651. // make sure we set the alpha of the graphics to 1 for the render..
  42652. this.worldAlpha = 1;
  42653. // now render the graphic..
  42654. PIXI.CanvasGraphics.renderGraphics(this, this._cachedSprite.buffer.context);
  42655. this._cachedSprite.alpha = this.alpha;
  42656. };
  42657. /**
  42658. * Updates texture size based on canvas size
  42659. *
  42660. * @method updateCachedSpriteTexture
  42661. * @private
  42662. */
  42663. PIXI.Graphics.prototype.updateCachedSpriteTexture = function()
  42664. {
  42665. var cachedSprite = this._cachedSprite;
  42666. var texture = cachedSprite.texture;
  42667. var canvas = cachedSprite.buffer.canvas;
  42668. texture.baseTexture.width = canvas.width;
  42669. texture.baseTexture.height = canvas.height;
  42670. texture.crop.width = texture.frame.width = canvas.width;
  42671. texture.crop.height = texture.frame.height = canvas.height;
  42672. cachedSprite._width = canvas.width;
  42673. cachedSprite._height = canvas.height;
  42674. // update the dirty base textures
  42675. texture.baseTexture.dirty();
  42676. };
  42677. /**
  42678. * Destroys a previous cached sprite.
  42679. *
  42680. * @method destroyCachedSprite
  42681. */
  42682. PIXI.Graphics.prototype.destroyCachedSprite = function()
  42683. {
  42684. this._cachedSprite.texture.destroy(true);
  42685. this._cachedSprite = null;
  42686. };
  42687. /**
  42688. * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon.
  42689. *
  42690. * @method drawShape
  42691. * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw.
  42692. * @return {GraphicsData} The generated GraphicsData object.
  42693. */
  42694. PIXI.Graphics.prototype.drawShape = function(shape)
  42695. {
  42696. if (this.currentPath)
  42697. {
  42698. // check current path!
  42699. if (this.currentPath.shape.points.length <= 2)
  42700. {
  42701. this.graphicsData.pop();
  42702. }
  42703. }
  42704. this.currentPath = null;
  42705. // Handle mixed-type polygons
  42706. if (shape instanceof Phaser.Polygon)
  42707. {
  42708. shape = shape.clone();
  42709. shape.flatten();
  42710. }
  42711. var data = new PIXI.GraphicsData(this.lineWidth, this.lineColor, this.lineAlpha, this.fillColor, this.fillAlpha, this.filling, shape);
  42712. this.graphicsData.push(data);
  42713. if (data.type === PIXI.Graphics.POLY)
  42714. {
  42715. data.shape.closed = this.filling;
  42716. this.currentPath = data;
  42717. }
  42718. this.dirty = true;
  42719. return data;
  42720. };
  42721. /**
  42722. * When cacheAsBitmap is set to true the graphics object will be rendered as if it was a sprite.
  42723. * This is useful if your graphics element does not change often, as it will speed up the rendering of the object in exchange for taking up texture memory.
  42724. * It is also useful if you need the graphics object to be anti-aliased, because it will be rendered using canvas.
  42725. * This is not recommended if you are constantly redrawing the graphics element.
  42726. *
  42727. * @property cacheAsBitmap
  42728. * @type Boolean
  42729. * @default false
  42730. * @private
  42731. */
  42732. Object.defineProperty(PIXI.Graphics.prototype, "cacheAsBitmap", {
  42733. get: function() {
  42734. return this._cacheAsBitmap;
  42735. },
  42736. set: function(value) {
  42737. this._cacheAsBitmap = value;
  42738. if (this._cacheAsBitmap)
  42739. {
  42740. this._generateCachedSprite();
  42741. }
  42742. else
  42743. {
  42744. this.destroyCachedSprite();
  42745. }
  42746. this.dirty = true;
  42747. this.webGLDirty = true;
  42748. }
  42749. });
  42750. /**
  42751. * A GraphicsData object.
  42752. *
  42753. * @class GraphicsData
  42754. * @constructor
  42755. PIXI.GraphicsData = function(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape)
  42756. {
  42757. this.lineWidth = lineWidth;
  42758. this.lineColor = lineColor;
  42759. this.lineAlpha = lineAlpha;
  42760. this._lineTint = lineColor;
  42761. this.fillColor = fillColor;
  42762. this.fillAlpha = fillAlpha;
  42763. this._fillTint = fillColor;
  42764. this.fill = fill;
  42765. this.shape = shape;
  42766. this.type = shape.type;
  42767. };
  42768. */
  42769. /**
  42770. * A GraphicsData object.
  42771. *
  42772. * @class
  42773. * @memberof PIXI
  42774. * @param lineWidth {number} the width of the line to draw
  42775. * @param lineColor {number} the color of the line to draw
  42776. * @param lineAlpha {number} the alpha of the line to draw
  42777. * @param fillColor {number} the color of the fill
  42778. * @param fillAlpha {number} the alpha of the fill
  42779. * @param fill {boolean} whether or not the shape is filled with a colour
  42780. * @param shape {Circle|Rectangle|Ellipse|Line|Polygon} The shape object to draw.
  42781. */
  42782. PIXI.GraphicsData = function(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) {
  42783. /*
  42784. * @member {number} the width of the line to draw
  42785. */
  42786. this.lineWidth = lineWidth;
  42787. /*
  42788. * @member {number} the color of the line to draw
  42789. */
  42790. this.lineColor = lineColor;
  42791. /*
  42792. * @member {number} the alpha of the line to draw
  42793. */
  42794. this.lineAlpha = lineAlpha;
  42795. /*
  42796. * @member {number} cached tint of the line to draw
  42797. */
  42798. this._lineTint = lineColor;
  42799. /*
  42800. * @member {number} the color of the fill
  42801. */
  42802. this.fillColor = fillColor;
  42803. /*
  42804. * @member {number} the alpha of the fill
  42805. */
  42806. this.fillAlpha = fillAlpha;
  42807. /*
  42808. * @member {number} cached tint of the fill
  42809. */
  42810. this._fillTint = fillColor;
  42811. /*
  42812. * @member {boolean} whether or not the shape is filled with a color
  42813. */
  42814. this.fill = fill;
  42815. /*
  42816. * @member {Circle|Rectangle|Ellipse|Line|Polygon} The shape object to draw.
  42817. */
  42818. this.shape = shape;
  42819. /*
  42820. * @member {number} The type of the shape, see the Const.Shapes file for all the existing types,
  42821. */
  42822. this.type = shape.type;
  42823. };
  42824. PIXI.GraphicsData.prototype.constructor = PIXI.GraphicsData;
  42825. /**
  42826. * Creates a new GraphicsData object with the same values as this one.
  42827. *
  42828. * @return {GraphicsData}
  42829. */
  42830. PIXI.GraphicsData.prototype.clone = function() {
  42831. return new GraphicsData(
  42832. this.lineWidth,
  42833. this.lineColor,
  42834. this.lineAlpha,
  42835. this.fillColor,
  42836. this.fillAlpha,
  42837. this.fill,
  42838. this.shape
  42839. );
  42840. };
  42841. /*
  42842. PolyK library
  42843. url: http://polyk.ivank.net
  42844. Released under MIT licence.
  42845. Copyright (c) 2012 Ivan Kuckir
  42846. Permission is hereby granted, free of charge, to any person
  42847. obtaining a copy of this software and associated documentation
  42848. files (the "Software"), to deal in the Software without
  42849. restriction, including without limitation the rights to use,
  42850. copy, modify, merge, publish, distribute, sublicense, and/or sell
  42851. copies of the Software, and to permit persons to whom the
  42852. Software is furnished to do so, subject to the following
  42853. conditions:
  42854. The above copyright notice and this permission notice shall be
  42855. included in all copies or substantial portions of the Software.
  42856. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  42857. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  42858. OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  42859. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  42860. HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  42861. WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  42862. FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  42863. OTHER DEALINGS IN THE SOFTWARE.
  42864. This is an amazing lib!
  42865. Slightly modified by Mat Groves (matgroves.com);
  42866. */
  42867. /**
  42868. * Based on the Polyk library http://polyk.ivank.net released under MIT licence.
  42869. * This is an amazing lib!
  42870. * Slightly modified by Mat Groves (matgroves.com);
  42871. * @class PolyK
  42872. */
  42873. PIXI.PolyK = {};
  42874. /**
  42875. * Triangulates shapes for webGL graphic fills.
  42876. *
  42877. * @method Triangulate
  42878. */
  42879. PIXI.PolyK.Triangulate = function(p)
  42880. {
  42881. var sign = true;
  42882. var n = p.length >> 1;
  42883. if(n < 3) return [];
  42884. var tgs = [];
  42885. var avl = [];
  42886. for(var i = 0; i < n; i++) avl.push(i);
  42887. i = 0;
  42888. var al = n;
  42889. while(al > 3)
  42890. {
  42891. var i0 = avl[(i+0)%al];
  42892. var i1 = avl[(i+1)%al];
  42893. var i2 = avl[(i+2)%al];
  42894. var ax = p[2*i0], ay = p[2*i0+1];
  42895. var bx = p[2*i1], by = p[2*i1+1];
  42896. var cx = p[2*i2], cy = p[2*i2+1];
  42897. var earFound = false;
  42898. if(PIXI.PolyK._convex(ax, ay, bx, by, cx, cy, sign))
  42899. {
  42900. earFound = true;
  42901. for(var j = 0; j < al; j++)
  42902. {
  42903. var vi = avl[j];
  42904. if(vi === i0 || vi === i1 || vi === i2) continue;
  42905. if(PIXI.PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) {
  42906. earFound = false;
  42907. break;
  42908. }
  42909. }
  42910. }
  42911. if(earFound)
  42912. {
  42913. tgs.push(i0, i1, i2);
  42914. avl.splice((i+1)%al, 1);
  42915. al--;
  42916. i = 0;
  42917. }
  42918. else if(i++ > 3*al)
  42919. {
  42920. // need to flip flip reverse it!
  42921. // reset!
  42922. if(sign)
  42923. {
  42924. tgs = [];
  42925. avl = [];
  42926. for(i = 0; i < n; i++) avl.push(i);
  42927. i = 0;
  42928. al = n;
  42929. sign = false;
  42930. }
  42931. else
  42932. {
  42933. // window.console.log("PIXI Warning: shape too complex to fill");
  42934. return null;
  42935. }
  42936. }
  42937. }
  42938. tgs.push(avl[0], avl[1], avl[2]);
  42939. return tgs;
  42940. };
  42941. /**
  42942. * Checks whether a point is within a triangle
  42943. *
  42944. * @method _PointInTriangle
  42945. * @param px {Number} x coordinate of the point to test
  42946. * @param py {Number} y coordinate of the point to test
  42947. * @param ax {Number} x coordinate of the a point of the triangle
  42948. * @param ay {Number} y coordinate of the a point of the triangle
  42949. * @param bx {Number} x coordinate of the b point of the triangle
  42950. * @param by {Number} y coordinate of the b point of the triangle
  42951. * @param cx {Number} x coordinate of the c point of the triangle
  42952. * @param cy {Number} y coordinate of the c point of the triangle
  42953. * @private
  42954. * @return {Boolean}
  42955. */
  42956. PIXI.PolyK._PointInTriangle = function(px, py, ax, ay, bx, by, cx, cy)
  42957. {
  42958. var v0x = cx-ax;
  42959. var v0y = cy-ay;
  42960. var v1x = bx-ax;
  42961. var v1y = by-ay;
  42962. var v2x = px-ax;
  42963. var v2y = py-ay;
  42964. var dot00 = v0x*v0x+v0y*v0y;
  42965. var dot01 = v0x*v1x+v0y*v1y;
  42966. var dot02 = v0x*v2x+v0y*v2y;
  42967. var dot11 = v1x*v1x+v1y*v1y;
  42968. var dot12 = v1x*v2x+v1y*v2y;
  42969. var invDenom = 1 / (dot00 * dot11 - dot01 * dot01);
  42970. var u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  42971. var v = (dot00 * dot12 - dot01 * dot02) * invDenom;
  42972. // Check if point is in triangle
  42973. return (u >= 0) && (v >= 0) && (u + v < 1);
  42974. };
  42975. /**
  42976. * Checks whether a shape is convex
  42977. *
  42978. * @method _convex
  42979. * @private
  42980. * @return {Boolean}
  42981. */
  42982. PIXI.PolyK._convex = function(ax, ay, bx, by, cx, cy, sign)
  42983. {
  42984. return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign;
  42985. };
  42986. /*
  42987. Copyright (c) 2016, Mapbox
  42988. Permission to use, copy, modify, and/or distribute this software for any purpose
  42989. with or without fee is hereby granted, provided that the above copyright notice
  42990. and this permission notice appear in all copies.
  42991. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  42992. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  42993. FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  42994. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  42995. OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  42996. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  42997. THIS SOFTWARE.
  42998. */
  42999. /**
  43000. * @class EarCut
  43001. */
  43002. PIXI.EarCut = {};
  43003. PIXI.EarCut.Triangulate = function (data, holeIndices, dim) {
  43004. dim = dim || 2;
  43005. var hasHoles = holeIndices && holeIndices.length,
  43006. outerLen = hasHoles ? holeIndices[0] * dim : data.length,
  43007. outerNode = PIXI.EarCut.linkedList(data, 0, outerLen, dim, true),
  43008. triangles = [];
  43009. if (!outerNode) return triangles;
  43010. var minX, minY, maxX, maxY, x, y, size;
  43011. if (hasHoles) outerNode = PIXI.EarCut.eliminateHoles(data, holeIndices, outerNode, dim);
  43012. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  43013. if (data.length > 80 * dim) {
  43014. minX = maxX = data[0];
  43015. minY = maxY = data[1];
  43016. for (var i = dim; i < outerLen; i += dim) {
  43017. x = data[i];
  43018. y = data[i + 1];
  43019. if (x < minX) minX = x;
  43020. if (y < minY) minY = y;
  43021. if (x > maxX) maxX = x;
  43022. if (y > maxY) maxY = y;
  43023. }
  43024. // minX, minY and size are later used to transform coords into integers for z-order calculation
  43025. size = Math.max(maxX - minX, maxY - minY);
  43026. }
  43027. PIXI.EarCut.earcutLinked(outerNode, triangles, dim, minX, minY, size);
  43028. return triangles;
  43029. }
  43030. // create a circular doubly linked list from polygon points in the specified winding order
  43031. PIXI.EarCut.linkedList = function (data, start, end, dim, clockwise) {
  43032. var sum = 0,
  43033. i, j, last;
  43034. // calculate original winding order of a polygon ring
  43035. for (i = start, j = end - dim; i < end; i += dim) {
  43036. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  43037. j = i;
  43038. }
  43039. // link points into circular doubly-linked list in the specified winding order
  43040. if (clockwise === (sum > 0)) {
  43041. for (i = start; i < end; i += dim) last = PIXI.EarCut.insertNode(i, data[i], data[i + 1], last);
  43042. } else {
  43043. for (i = end - dim; i >= start; i -= dim) last = PIXI.EarCut.insertNode(i, data[i], data[i + 1], last);
  43044. }
  43045. return last;
  43046. }
  43047. // eliminate colinear or duplicate points
  43048. PIXI.EarCut.filterPoints = function (start, end) {
  43049. if (!start) return start;
  43050. if (!end) end = start;
  43051. var p = start,
  43052. again;
  43053. do {
  43054. again = false;
  43055. if (!p.steiner && (PIXI.EarCut.equals(p, p.next) || PIXI.EarCut.area(p.prev, p, p.next) === 0)) {
  43056. PIXI.EarCut.removeNode(p);
  43057. p = end = p.prev;
  43058. if (p === p.next) return null;
  43059. again = true;
  43060. } else {
  43061. p = p.next;
  43062. }
  43063. } while (again || p !== end);
  43064. return end;
  43065. }
  43066. // main ear slicing loop which triangulates a polygon (given as a linked list)
  43067. PIXI.EarCut.earcutLinked = function (ear, triangles, dim, minX, minY, size, pass) {
  43068. if (!ear) return;
  43069. // interlink polygon nodes in z-order
  43070. if (!pass && size) PIXI.EarCut.indexCurve(ear, minX, minY, size);
  43071. var stop = ear,
  43072. prev, next;
  43073. // iterate through ears, slicing them one by one
  43074. while (ear.prev !== ear.next) {
  43075. prev = ear.prev;
  43076. next = ear.next;
  43077. if (size ? PIXI.EarCut.isEarHashed(ear, minX, minY, size) : PIXI.EarCut.isEar(ear)) {
  43078. // cut off the triangle
  43079. triangles.push(prev.i / dim);
  43080. triangles.push(ear.i / dim);
  43081. triangles.push(next.i / dim);
  43082. PIXI.EarCut.removeNode(ear);
  43083. // skipping the next vertice leads to less sliver triangles
  43084. ear = next.next;
  43085. stop = next.next;
  43086. continue;
  43087. }
  43088. ear = next;
  43089. // if we looped through the whole remaining polygon and can't find any more ears
  43090. if (ear === stop) {
  43091. // try filtering points and slicing again
  43092. if (!pass) {
  43093. PIXI.EarCut.earcutLinked(PIXI.EarCut.filterPoints(ear), triangles, dim, minX, minY, size, 1);
  43094. // if this didn't work, try curing all small self-intersections locally
  43095. } else if (pass === 1) {
  43096. ear = PIXI.EarCut.cureLocalIntersections(ear, triangles, dim);
  43097. PIXI.EarCut.earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  43098. // as a last resort, try splitting the remaining polygon into two
  43099. } else if (pass === 2) {
  43100. PIXI.EarCut.splitEarcut(ear, triangles, dim, minX, minY, size);
  43101. }
  43102. break;
  43103. }
  43104. }
  43105. }
  43106. // check whether a polygon node forms a valid ear with adjacent nodes
  43107. PIXI.EarCut.isEar = function (ear) {
  43108. var a = ear.prev,
  43109. b = ear,
  43110. c = ear.next;
  43111. if (PIXI.EarCut.area(a, b, c) >= 0) return false; // reflex, can't be an ear
  43112. // now make sure we don't have other points inside the potential ear
  43113. var p = ear.next.next;
  43114. while (p !== ear.prev) {
  43115. if (PIXI.EarCut.pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  43116. PIXI.EarCut.area(p.prev, p, p.next) >= 0) return false;
  43117. p = p.next;
  43118. }
  43119. return true;
  43120. }
  43121. PIXI.EarCut.isEarHashed = function (ear, minX, minY, size) {
  43122. var a = ear.prev,
  43123. b = ear,
  43124. c = ear.next;
  43125. if (PIXI.EarCut.area(a, b, c) >= 0) return false; // reflex, can't be an ear
  43126. // triangle bbox; min & max are calculated like this for speed
  43127. var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x),
  43128. minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y),
  43129. maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x),
  43130. maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
  43131. // z-order range for the current triangle bbox;
  43132. var minZ = PIXI.EarCut.zOrder(minTX, minTY, minX, minY, size),
  43133. maxZ = PIXI.EarCut.zOrder(maxTX, maxTY, minX, minY, size);
  43134. // first look for points inside the triangle in increasing z-order
  43135. var p = ear.nextZ;
  43136. while (p && p.z <= maxZ) {
  43137. if (p !== ear.prev && p !== ear.next &&
  43138. PIXI.EarCut.pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  43139. PIXI.EarCut.area(p.prev, p, p.next) >= 0) return false;
  43140. p = p.nextZ;
  43141. }
  43142. // then look for points in decreasing z-order
  43143. p = ear.prevZ;
  43144. while (p && p.z >= minZ) {
  43145. if (p !== ear.prev && p !== ear.next &&
  43146. PIXI.EarCut.pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  43147. PIXI.EarCut.area(p.prev, p, p.next) >= 0) return false;
  43148. p = p.prevZ;
  43149. }
  43150. return true;
  43151. }
  43152. // go through all polygon nodes and cure small local self-intersections
  43153. PIXI.EarCut.cureLocalIntersections = function (start, triangles, dim) {
  43154. var p = start;
  43155. do {
  43156. var a = p.prev,
  43157. b = p.next.next;
  43158. // a self-intersection where edge (v[i-1],v[i]) intersects (v[i+1],v[i+2])
  43159. if (PIXI.EarCut.intersects(a, p, p.next, b) && PIXI.EarCut.locallyInside(a, b) && PIXI.EarCut.locallyInside(b, a)) {
  43160. triangles.push(a.i / dim);
  43161. triangles.push(p.i / dim);
  43162. triangles.push(b.i / dim);
  43163. // remove two nodes involved
  43164. PIXI.EarCut.removeNode(p);
  43165. PIXI.EarCut.removeNode(p.next);
  43166. p = start = b;
  43167. }
  43168. p = p.next;
  43169. } while (p !== start);
  43170. return p;
  43171. }
  43172. // try splitting polygon into two and triangulate them independently
  43173. PIXI.EarCut.splitEarcut = function (start, triangles, dim, minX, minY, size) {
  43174. // look for a valid diagonal that divides the polygon into two
  43175. var a = start;
  43176. do {
  43177. var b = a.next.next;
  43178. while (b !== a.prev) {
  43179. if (a.i !== b.i && PIXI.EarCut.isValidDiagonal(a, b)) {
  43180. // split the polygon in two by the diagonal
  43181. var c = PIXI.EarCut.splitPolygon(a, b);
  43182. // filter colinear points around the cuts
  43183. a = PIXI.EarCut.filterPoints(a, a.next);
  43184. c = PIXI.EarCut.filterPoints(c, c.next);
  43185. // run earcut on each half
  43186. PIXI.EarCut.earcutLinked(a, triangles, dim, minX, minY, size);
  43187. PIXI.EarCut.earcutLinked(c, triangles, dim, minX, minY, size);
  43188. return;
  43189. }
  43190. b = b.next;
  43191. }
  43192. a = a.next;
  43193. } while (a !== start);
  43194. }
  43195. // link every hole into the outer loop, producing a single-ring polygon without holes
  43196. PIXI.EarCut.eliminateHoles = function (data, holeIndices, outerNode, dim) {
  43197. var queue = [],
  43198. i, len, start, end, list;
  43199. for (i = 0, len = holeIndices.length; i < len; i++) {
  43200. start = holeIndices[i] * dim;
  43201. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  43202. list = PIXI.EarCut.linkedList(data, start, end, dim, false);
  43203. if (list === list.next) list.steiner = true;
  43204. queue.push(PIXI.EarCut.getLeftmost(list));
  43205. }
  43206. queue.sort(compareX);
  43207. // process holes from left to right
  43208. for (i = 0; i < queue.length; i++) {
  43209. PIXI.EarCut.eliminateHole(queue[i], outerNode);
  43210. outerNode = PIXI.EarCut.filterPoints(outerNode, outerNode.next);
  43211. }
  43212. return outerNode;
  43213. }
  43214. PIXI.EarCut.compareX = function (a, b) {
  43215. return a.x - b.x;
  43216. }
  43217. // find a bridge between vertices that connects hole with an outer ring and and link it
  43218. PIXI.EarCut.eliminateHole = function (hole, outerNode) {
  43219. outerNode = PIXI.EarCut.findHoleBridge(hole, outerNode);
  43220. if (outerNode) {
  43221. var b = PIXI.EarCut.splitPolygon(outerNode, hole);
  43222. PIXI.EarCut.filterPoints(b, b.next);
  43223. }
  43224. }
  43225. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  43226. PIXI.EarCut.findHoleBridge = function (hole, outerNode) {
  43227. var p = outerNode,
  43228. hx = hole.x,
  43229. hy = hole.y,
  43230. qx = -Infinity,
  43231. m;
  43232. // find a segment intersected by a ray from the hole's leftmost point to the left;
  43233. // segment's endpoint with lesser x will be potential connection point
  43234. do {
  43235. if (hy <= p.y && hy >= p.next.y) {
  43236. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  43237. if (x <= hx && x > qx) {
  43238. qx = x;
  43239. m = p.x < p.next.x ? p : p.next;
  43240. }
  43241. }
  43242. p = p.next;
  43243. } while (p !== outerNode);
  43244. if (!m) return null;
  43245. if (hole.x === m.x) return m.prev; // hole touches outer segment; pick lower endpoint
  43246. // look for points inside the triangle of hole point, segment intersection and endpoint;
  43247. // if there are no points found, we have a valid connection;
  43248. // otherwise choose the point of the minimum angle with the ray as connection point
  43249. var stop = m,
  43250. tanMin = Infinity,
  43251. tan;
  43252. p = m.next;
  43253. while (p !== stop) {
  43254. if (hx >= p.x && p.x >= m.x &&
  43255. PIXI.EarCut.pointInTriangle(hy < m.y ? hx : qx, hy, m.x, m.y, hy < m.y ? qx : hx, hy, p.x, p.y)) {
  43256. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  43257. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && PIXI.EarCut.locallyInside(p, hole)) {
  43258. m = p;
  43259. tanMin = tan;
  43260. }
  43261. }
  43262. p = p.next;
  43263. }
  43264. return m;
  43265. }
  43266. // interlink polygon nodes in z-order
  43267. PIXI.EarCut.indexCurve = function (start, minX, minY, size) {
  43268. var p = start;
  43269. do {
  43270. if (p.z === null) p.z = PIXI.EarCut.zOrder(p.x, p.y, minX, minY, size);
  43271. p.prevZ = p.prev;
  43272. p.nextZ = p.next;
  43273. p = p.next;
  43274. } while (p !== start);
  43275. p.prevZ.nextZ = null;
  43276. p.prevZ = null;
  43277. PIXI.EarCut.sortLinked(p);
  43278. }
  43279. // Simon Tatham's linked list merge sort algorithm
  43280. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  43281. PIXI.EarCut.sortLinked = function (list) {
  43282. var i, p, q, e, tail, numMerges, pSize, qSize,
  43283. inSize = 1;
  43284. do {
  43285. p = list;
  43286. list = null;
  43287. tail = null;
  43288. numMerges = 0;
  43289. while (p) {
  43290. numMerges++;
  43291. q = p;
  43292. pSize = 0;
  43293. for (i = 0; i < inSize; i++) {
  43294. pSize++;
  43295. q = q.nextZ;
  43296. if (!q) break;
  43297. }
  43298. qSize = inSize;
  43299. while (pSize > 0 || (qSize > 0 && q)) {
  43300. if (pSize === 0) {
  43301. e = q;
  43302. q = q.nextZ;
  43303. qSize--;
  43304. } else if (qSize === 0 || !q) {
  43305. e = p;
  43306. p = p.nextZ;
  43307. pSize--;
  43308. } else if (p.z <= q.z) {
  43309. e = p;
  43310. p = p.nextZ;
  43311. pSize--;
  43312. } else {
  43313. e = q;
  43314. q = q.nextZ;
  43315. qSize--;
  43316. }
  43317. if (tail) tail.nextZ = e;
  43318. else list = e;
  43319. e.prevZ = tail;
  43320. tail = e;
  43321. }
  43322. p = q;
  43323. }
  43324. tail.nextZ = null;
  43325. inSize *= 2;
  43326. } while (numMerges > 1);
  43327. return list;
  43328. }
  43329. // z-order of a point given coords and size of the data bounding box
  43330. PIXI.EarCut.zOrder = function (x, y, minX, minY, size) {
  43331. // coords are transformed into non-negative 15-bit integer range
  43332. x = 32767 * (x - minX) / size;
  43333. y = 32767 * (y - minY) / size;
  43334. x = (x | (x << 8)) & 0x00FF00FF;
  43335. x = (x | (x << 4)) & 0x0F0F0F0F;
  43336. x = (x | (x << 2)) & 0x33333333;
  43337. x = (x | (x << 1)) & 0x55555555;
  43338. y = (y | (y << 8)) & 0x00FF00FF;
  43339. y = (y | (y << 4)) & 0x0F0F0F0F;
  43340. y = (y | (y << 2)) & 0x33333333;
  43341. y = (y | (y << 1)) & 0x55555555;
  43342. return x | (y << 1);
  43343. }
  43344. // find the leftmost node of a polygon ring
  43345. PIXI.EarCut.getLeftmost = function (start) {
  43346. var p = start,
  43347. leftmost = start;
  43348. do {
  43349. if (p.x < leftmost.x) leftmost = p;
  43350. p = p.next;
  43351. } while (p !== start);
  43352. return leftmost;
  43353. }
  43354. // check if a point lies within a convex triangle
  43355. PIXI.EarCut.pointInTriangle = function (ax, ay, bx, by, cx, cy, px, py) {
  43356. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  43357. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  43358. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  43359. }
  43360. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  43361. PIXI.EarCut.isValidDiagonal = function (a, b) {
  43362. return PIXI.EarCut.equals(a, b) || a.next.i !== b.i && a.prev.i !== b.i && !PIXI.EarCut.intersectsPolygon(a, b) &&
  43363. PIXI.EarCut.locallyInside(a, b) && PIXI.EarCut.locallyInside(b, a) && PIXI.EarCut.middleInside(a, b);
  43364. }
  43365. // signed area of a triangle
  43366. PIXI.EarCut.area = function (p, q, r) {
  43367. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  43368. }
  43369. // check if two points are equal
  43370. PIXI.EarCut.equals = function (p1, p2) {
  43371. return p1.x === p2.x && p1.y === p2.y;
  43372. }
  43373. // check if two segments intersect
  43374. PIXI.EarCut.intersects = function (p1, q1, p2, q2) {
  43375. return PIXI.EarCut.area(p1, q1, p2) > 0 !== PIXI.EarCut.area(p1, q1, q2) > 0 &&
  43376. PIXI.EarCut.area(p2, q2, p1) > 0 !== PIXI.EarCut.area(p2, q2, q1) > 0;
  43377. }
  43378. // check if a polygon diagonal intersects any polygon segments
  43379. PIXI.EarCut.intersectsPolygon = function (a, b) {
  43380. var p = a;
  43381. do {
  43382. if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  43383. PIXI.EarCut.intersects(p, p.next, a, b)) return true;
  43384. p = p.next;
  43385. } while (p !== a);
  43386. return false;
  43387. }
  43388. // check if a polygon diagonal is locally inside the polygon
  43389. PIXI.EarCut.locallyInside = function (a, b) {
  43390. return PIXI.EarCut.area(a.prev, a, a.next) < 0 ?
  43391. PIXI.EarCut.area(a, b, a.next) >= 0 && PIXI.EarCut.area(a, a.prev, b) >= 0 :
  43392. PIXI.EarCut.area(a, b, a.prev) < 0 || PIXI.EarCut.area(a, a.next, b) < 0;
  43393. }
  43394. // check if the middle point of a polygon diagonal is inside the polygon
  43395. PIXI.EarCut.middleInside = function (a, b) {
  43396. var p = a,
  43397. inside = false,
  43398. px = (a.x + b.x) / 2,
  43399. py = (a.y + b.y) / 2;
  43400. do {
  43401. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  43402. inside = !inside;
  43403. p = p.next;
  43404. } while (p !== a);
  43405. return inside;
  43406. }
  43407. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  43408. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  43409. PIXI.EarCut.splitPolygon = function (a, b) {
  43410. var a2 = new PIXI.EarCut.Node(a.i, a.x, a.y),
  43411. b2 = new PIXI.EarCut.Node(b.i, b.x, b.y),
  43412. an = a.next,
  43413. bp = b.prev;
  43414. a.next = b;
  43415. b.prev = a;
  43416. a2.next = an;
  43417. an.prev = a2;
  43418. b2.next = a2;
  43419. a2.prev = b2;
  43420. bp.next = b2;
  43421. b2.prev = bp;
  43422. return b2;
  43423. }
  43424. // create a node and optionally link it with previous one (in a circular doubly linked list)
  43425. PIXI.EarCut.insertNode = function (i, x, y, last) {
  43426. var p = new PIXI.EarCut.Node(i, x, y);
  43427. if (!last) {
  43428. p.prev = p;
  43429. p.next = p;
  43430. } else {
  43431. p.next = last.next;
  43432. p.prev = last;
  43433. last.next.prev = p;
  43434. last.next = p;
  43435. }
  43436. return p;
  43437. }
  43438. PIXI.EarCut.removeNode = function (p) {
  43439. p.next.prev = p.prev;
  43440. p.prev.next = p.next;
  43441. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  43442. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  43443. }
  43444. PIXI.EarCut.Node = function (i, x, y) {
  43445. // vertice index in coordinates array
  43446. this.i = i;
  43447. // vertex coordinates
  43448. this.x = x;
  43449. this.y = y;
  43450. // previous and next vertice nodes in a polygon ring
  43451. this.prev = null;
  43452. this.next = null;
  43453. // z-order curve value
  43454. this.z = null;
  43455. // previous and next nodes in z-order
  43456. this.prevZ = null;
  43457. this.nextZ = null;
  43458. // indicates whether this is a steiner point
  43459. this.steiner = false;
  43460. }
  43461. /**
  43462. * @author Mat Groves http://matgroves.com/ @Doormat23
  43463. */
  43464. /**
  43465. * A set of functions used by the webGL renderer to draw the primitive graphics data
  43466. *
  43467. * @class WebGLGraphics
  43468. * @private
  43469. * @static
  43470. */
  43471. PIXI.WebGLGraphics = function()
  43472. {
  43473. };
  43474. /**
  43475. * The number of points beyond which Pixi swaps to using the Stencil Buffer to render the Graphics.
  43476. *
  43477. * @type {number}
  43478. */
  43479. PIXI.WebGLGraphics.stencilBufferLimit = 6;
  43480. /**
  43481. * Renders the graphics object
  43482. *
  43483. * @static
  43484. * @private
  43485. * @method renderGraphics
  43486. * @param graphics {Graphics}
  43487. * @param renderSession {Object}
  43488. */
  43489. PIXI.WebGLGraphics.renderGraphics = function(graphics, renderSession)//projection, offset)
  43490. {
  43491. var gl = renderSession.gl;
  43492. var projection = renderSession.projection,
  43493. offset = renderSession.offset,
  43494. shader = renderSession.shaderManager.primitiveShader,
  43495. webGLData;
  43496. if(graphics.dirty)
  43497. {
  43498. PIXI.WebGLGraphics.updateGraphics(graphics, gl);
  43499. }
  43500. var webGL = graphics._webGL[gl.id];
  43501. // This could be speeded up for sure!
  43502. for (var i = 0; i < webGL.data.length; i++)
  43503. {
  43504. if(webGL.data[i].mode === 1)
  43505. {
  43506. webGLData = webGL.data[i];
  43507. renderSession.stencilManager.pushStencil(graphics, webGLData, renderSession);
  43508. // render quad..
  43509. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 );
  43510. renderSession.stencilManager.popStencil(graphics, webGLData, renderSession);
  43511. }
  43512. else
  43513. {
  43514. webGLData = webGL.data[i];
  43515. renderSession.shaderManager.setShader( shader );//activatePrimitiveShader();
  43516. shader = renderSession.shaderManager.primitiveShader;
  43517. gl.uniformMatrix3fv(shader.translationMatrix, false, graphics.worldTransform.toArray(true));
  43518. gl.uniform1f(shader.flipY, 1);
  43519. gl.uniform2f(shader.projectionVector, projection.x, -projection.y);
  43520. gl.uniform2f(shader.offsetVector, -offset.x, -offset.y);
  43521. gl.uniform3fv(shader.tintColor, PIXI.hex2rgb(graphics.tint));
  43522. gl.uniform1f(shader.alpha, graphics.worldAlpha);
  43523. gl.bindBuffer(gl.ARRAY_BUFFER, webGLData.buffer);
  43524. gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 4 * 6, 0);
  43525. gl.vertexAttribPointer(shader.colorAttribute, 4, gl.FLOAT, false,4 * 6, 2 * 4);
  43526. // set the index buffer!
  43527. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer);
  43528. gl.drawElements(gl.TRIANGLE_STRIP, webGLData.indices.length, gl.UNSIGNED_SHORT, 0 );
  43529. }
  43530. }
  43531. };
  43532. /**
  43533. * Updates the graphics object
  43534. *
  43535. * @static
  43536. * @private
  43537. * @method updateGraphics
  43538. * @param graphicsData {Graphics} The graphics object to update
  43539. * @param gl {WebGLContext} the current WebGL drawing context
  43540. */
  43541. PIXI.WebGLGraphics.updateGraphics = function(graphics, gl)
  43542. {
  43543. // get the contexts graphics object
  43544. var webGL = graphics._webGL[gl.id];
  43545. // if the graphics object does not exist in the webGL context time to create it!
  43546. if(!webGL)webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl};
  43547. // flag the graphics as not dirty as we are about to update it...
  43548. graphics.dirty = false;
  43549. var i;
  43550. // if the user cleared the graphics object we will need to clear every object
  43551. if(graphics.clearDirty)
  43552. {
  43553. graphics.clearDirty = false;
  43554. // lop through and return all the webGLDatas to the object pool so than can be reused later on
  43555. for (i = 0; i < webGL.data.length; i++)
  43556. {
  43557. var graphicsData = webGL.data[i];
  43558. graphicsData.reset();
  43559. PIXI.WebGLGraphics.graphicsDataPool.push( graphicsData );
  43560. }
  43561. // clear the array and reset the index..
  43562. webGL.data = [];
  43563. webGL.lastIndex = 0;
  43564. }
  43565. var webGLData;
  43566. // loop through the graphics datas and construct each one..
  43567. // if the object is a complex fill then the new stencil buffer technique will be used
  43568. // other wise graphics objects will be pushed into a batch..
  43569. for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++)
  43570. {
  43571. var data = graphics.graphicsData[i];
  43572. if(data.type === PIXI.Graphics.POLY)
  43573. {
  43574. // need to add the points the the graphics object..
  43575. data.points = data.shape.points.slice();
  43576. if(data.shape.closed)
  43577. {
  43578. // close the poly if the value is true!
  43579. if(data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1])
  43580. {
  43581. data.points.push(data.points[0], data.points[1]);
  43582. }
  43583. }
  43584. // MAKE SURE WE HAVE THE CORRECT TYPE..
  43585. if(data.fill)
  43586. {
  43587. if(data.points.length >= PIXI.WebGLGraphics.stencilBufferLimit)
  43588. {
  43589. if(data.points.length < PIXI.WebGLGraphics.stencilBufferLimit * 2)
  43590. {
  43591. webGLData = PIXI.WebGLGraphics.switchMode(webGL, 0);
  43592. var canDrawUsingSimple = PIXI.WebGLGraphics.buildPoly(data, webGLData);
  43593. // console.log(canDrawUsingSimple);
  43594. if(!canDrawUsingSimple)
  43595. {
  43596. // console.log("<>>>")
  43597. webGLData = PIXI.WebGLGraphics.switchMode(webGL, 1);
  43598. PIXI.WebGLGraphics.buildComplexPoly(data, webGLData);
  43599. }
  43600. }
  43601. else
  43602. {
  43603. webGLData = PIXI.WebGLGraphics.switchMode(webGL, 1);
  43604. PIXI.WebGLGraphics.buildComplexPoly(data, webGLData);
  43605. }
  43606. }
  43607. }
  43608. if(data.lineWidth > 0)
  43609. {
  43610. webGLData = PIXI.WebGLGraphics.switchMode(webGL, 0);
  43611. PIXI.WebGLGraphics.buildLine(data, webGLData);
  43612. }
  43613. }
  43614. else
  43615. {
  43616. webGLData = PIXI.WebGLGraphics.switchMode(webGL, 0);
  43617. if(data.type === PIXI.Graphics.RECT)
  43618. {
  43619. PIXI.WebGLGraphics.buildRectangle(data, webGLData);
  43620. }
  43621. else if(data.type === PIXI.Graphics.CIRC || data.type === PIXI.Graphics.ELIP)
  43622. {
  43623. PIXI.WebGLGraphics.buildCircle(data, webGLData);
  43624. }
  43625. else if(data.type === PIXI.Graphics.RREC)
  43626. {
  43627. PIXI.WebGLGraphics.buildRoundedRectangle(data, webGLData);
  43628. }
  43629. }
  43630. webGL.lastIndex++;
  43631. }
  43632. // upload all the dirty data...
  43633. for (i = 0; i < webGL.data.length; i++)
  43634. {
  43635. webGLData = webGL.data[i];
  43636. if(webGLData.dirty)webGLData.upload();
  43637. }
  43638. };
  43639. /**
  43640. * @static
  43641. * @private
  43642. * @method switchMode
  43643. * @param webGL {WebGLContext}
  43644. * @param type {Number}
  43645. */
  43646. PIXI.WebGLGraphics.switchMode = function(webGL, type)
  43647. {
  43648. var webGLData;
  43649. if(!webGL.data.length)
  43650. {
  43651. webGLData = PIXI.WebGLGraphics.graphicsDataPool.pop() || new PIXI.WebGLGraphicsData(webGL.gl);
  43652. webGLData.mode = type;
  43653. webGL.data.push(webGLData);
  43654. }
  43655. else
  43656. {
  43657. webGLData = webGL.data[webGL.data.length-1];
  43658. if(webGLData.mode !== type || type === 1)
  43659. {
  43660. webGLData = PIXI.WebGLGraphics.graphicsDataPool.pop() || new PIXI.WebGLGraphicsData(webGL.gl);
  43661. webGLData.mode = type;
  43662. webGL.data.push(webGLData);
  43663. }
  43664. }
  43665. webGLData.dirty = true;
  43666. return webGLData;
  43667. };
  43668. /**
  43669. * Builds a rectangle to draw
  43670. *
  43671. * @static
  43672. * @private
  43673. * @method buildRectangle
  43674. * @param graphicsData {Graphics} The graphics object containing all the necessary properties
  43675. * @param webGLData {Object}
  43676. */
  43677. PIXI.WebGLGraphics.buildRectangle = function(graphicsData, webGLData)
  43678. {
  43679. // --- //
  43680. // need to convert points to a nice regular data
  43681. //
  43682. var rectData = graphicsData.shape;
  43683. var x = rectData.x;
  43684. var y = rectData.y;
  43685. var width = rectData.width;
  43686. var height = rectData.height;
  43687. if(graphicsData.fill)
  43688. {
  43689. var color = PIXI.hex2rgb(graphicsData.fillColor);
  43690. var alpha = graphicsData.fillAlpha;
  43691. var r = color[0] * alpha;
  43692. var g = color[1] * alpha;
  43693. var b = color[2] * alpha;
  43694. var verts = webGLData.points;
  43695. var indices = webGLData.indices;
  43696. var vertPos = verts.length / 6;
  43697. // start
  43698. verts.push(x, y);
  43699. verts.push(r, g, b, alpha);
  43700. verts.push(x + width, y);
  43701. verts.push(r, g, b, alpha);
  43702. verts.push(x , y + height);
  43703. verts.push(r, g, b, alpha);
  43704. verts.push(x + width, y + height);
  43705. verts.push(r, g, b, alpha);
  43706. // insert 2 dead triangles..
  43707. indices.push(vertPos, vertPos, vertPos + 1, vertPos + 2, vertPos + 3, vertPos + 3);
  43708. }
  43709. if (graphicsData.lineWidth)
  43710. {
  43711. var tempPoints = graphicsData.points;
  43712. graphicsData.points = [x, y,
  43713. x + width, y,
  43714. x + width, y + height,
  43715. x, y + height,
  43716. x, y];
  43717. PIXI.WebGLGraphics.buildLine(graphicsData, webGLData);
  43718. graphicsData.points = tempPoints;
  43719. }
  43720. };
  43721. /**
  43722. * Builds a rounded rectangle to draw
  43723. *
  43724. * @static
  43725. * @private
  43726. * @method buildRoundedRectangle
  43727. * @param graphicsData {Graphics} The graphics object containing all the necessary properties
  43728. * @param webGLData {Object}
  43729. */
  43730. PIXI.WebGLGraphics.buildRoundedRectangle = function(graphicsData, webGLData)
  43731. {
  43732. var rrectData = graphicsData.shape;
  43733. var x = rrectData.x;
  43734. var y = rrectData.y;
  43735. var width = rrectData.width;
  43736. var height = rrectData.height;
  43737. var radius = rrectData.radius;
  43738. var recPoints = [];
  43739. recPoints.push(x, y + radius);
  43740. recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x, y + height - radius, x, y + height, x + radius, y + height));
  43741. recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x + width - radius, y + height, x + width, y + height, x + width, y + height - radius));
  43742. recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y));
  43743. recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius));
  43744. if (graphicsData.fill) {
  43745. var color = PIXI.hex2rgb(graphicsData.fillColor);
  43746. var alpha = graphicsData.fillAlpha;
  43747. var r = color[0] * alpha;
  43748. var g = color[1] * alpha;
  43749. var b = color[2] * alpha;
  43750. var verts = webGLData.points;
  43751. var indices = webGLData.indices;
  43752. var vecPos = verts.length / 6;
  43753. var triangles = PIXI.EarCut.Triangulate(recPoints, null, 2);
  43754. var i = 0;
  43755. for (i = 0; i < triangles.length; i+=3)
  43756. {
  43757. indices.push(triangles[i] + vecPos);
  43758. indices.push(triangles[i] + vecPos);
  43759. indices.push(triangles[i+1] + vecPos);
  43760. indices.push(triangles[i+2] + vecPos);
  43761. indices.push(triangles[i+2] + vecPos);
  43762. }
  43763. for (i = 0; i < recPoints.length; i++)
  43764. {
  43765. verts.push(recPoints[i], recPoints[++i], r, g, b, alpha);
  43766. }
  43767. }
  43768. if (graphicsData.lineWidth) {
  43769. var tempPoints = graphicsData.points;
  43770. graphicsData.points = recPoints;
  43771. PIXI.WebGLGraphics.buildLine(graphicsData, webGLData);
  43772. graphicsData.points = tempPoints;
  43773. }
  43774. };
  43775. /**
  43776. * Calculate the points for a quadratic bezier curve. (helper function..)
  43777. * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c
  43778. *
  43779. * @static
  43780. * @private
  43781. * @method quadraticBezierCurve
  43782. * @param fromX {Number} Origin point x
  43783. * @param fromY {Number} Origin point x
  43784. * @param cpX {Number} Control point x
  43785. * @param cpY {Number} Control point y
  43786. * @param toX {Number} Destination point x
  43787. * @param toY {Number} Destination point y
  43788. * @return {Array(Number)}
  43789. */
  43790. PIXI.WebGLGraphics.quadraticBezierCurve = function(fromX, fromY, cpX, cpY, toX, toY) {
  43791. var xa,
  43792. ya,
  43793. xb,
  43794. yb,
  43795. x,
  43796. y,
  43797. n = 20,
  43798. points = [];
  43799. function getPt(n1 , n2, perc) {
  43800. var diff = n2 - n1;
  43801. return n1 + ( diff * perc );
  43802. }
  43803. var j = 0;
  43804. for (var i = 0; i <= n; i++ )
  43805. {
  43806. j = i / n;
  43807. // The Green Line
  43808. xa = getPt( fromX , cpX , j );
  43809. ya = getPt( fromY , cpY , j );
  43810. xb = getPt( cpX , toX , j );
  43811. yb = getPt( cpY , toY , j );
  43812. // The Black Dot
  43813. x = getPt( xa , xb , j );
  43814. y = getPt( ya , yb , j );
  43815. points.push(x, y);
  43816. }
  43817. return points;
  43818. };
  43819. /**
  43820. * Builds a circle to draw
  43821. *
  43822. * @static
  43823. * @private
  43824. * @method buildCircle
  43825. * @param graphicsData {Graphics} The graphics object to draw
  43826. * @param webGLData {Object}
  43827. */
  43828. PIXI.WebGLGraphics.buildCircle = function(graphicsData, webGLData)
  43829. {
  43830. // need to convert points to a nice regular data
  43831. var circleData = graphicsData.shape;
  43832. var x = circleData.x;
  43833. var y = circleData.y;
  43834. var width;
  43835. var height;
  43836. // TODO - bit hacky??
  43837. if(graphicsData.type === PIXI.Graphics.CIRC)
  43838. {
  43839. width = circleData.radius;
  43840. height = circleData.radius;
  43841. }
  43842. else
  43843. {
  43844. width = circleData.width;
  43845. height = circleData.height;
  43846. }
  43847. var totalSegs = 40;
  43848. var seg = (Math.PI * 2) / totalSegs ;
  43849. var i = 0;
  43850. if(graphicsData.fill)
  43851. {
  43852. var color = PIXI.hex2rgb(graphicsData.fillColor);
  43853. var alpha = graphicsData.fillAlpha;
  43854. var r = color[0] * alpha;
  43855. var g = color[1] * alpha;
  43856. var b = color[2] * alpha;
  43857. var verts = webGLData.points;
  43858. var indices = webGLData.indices;
  43859. var vecPos = verts.length / 6;
  43860. indices.push(vecPos);
  43861. for (i = 0; i < totalSegs + 1 ; i++)
  43862. {
  43863. verts.push(x,y, r, g, b, alpha);
  43864. verts.push(x + Math.sin(seg * i) * width,
  43865. y + Math.cos(seg * i) * height,
  43866. r, g, b, alpha);
  43867. indices.push(vecPos++, vecPos++);
  43868. }
  43869. indices.push(vecPos-1);
  43870. }
  43871. if(graphicsData.lineWidth)
  43872. {
  43873. var tempPoints = graphicsData.points;
  43874. graphicsData.points = [];
  43875. for (i = 0; i < totalSegs + 1; i++)
  43876. {
  43877. graphicsData.points.push(x + Math.sin(seg * i) * width,
  43878. y + Math.cos(seg * i) * height);
  43879. }
  43880. PIXI.WebGLGraphics.buildLine(graphicsData, webGLData);
  43881. graphicsData.points = tempPoints;
  43882. }
  43883. };
  43884. /**
  43885. * Builds a line to draw
  43886. *
  43887. * @static
  43888. * @private
  43889. * @method buildLine
  43890. * @param graphicsData {Graphics} The graphics object containing all the necessary properties
  43891. * @param webGLData {Object}
  43892. */
  43893. PIXI.WebGLGraphics.buildLine = function(graphicsData, webGLData)
  43894. {
  43895. // TODO OPTIMISE!
  43896. var i = 0;
  43897. var points = graphicsData.points;
  43898. if(points.length === 0)return;
  43899. // if the line width is an odd number add 0.5 to align to a whole pixel
  43900. if(graphicsData.lineWidth%2)
  43901. {
  43902. for (i = 0; i < points.length; i++) {
  43903. points[i] += 0.5;
  43904. }
  43905. }
  43906. // get first and last point.. figure out the middle!
  43907. var firstPoint = new PIXI.Point( points[0], points[1] );
  43908. var lastPoint = new PIXI.Point( points[points.length - 2], points[points.length - 1] );
  43909. // if the first point is the last point - gonna have issues :)
  43910. if(firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y)
  43911. {
  43912. // need to clone as we are going to slightly modify the shape..
  43913. points = points.slice();
  43914. points.pop();
  43915. points.pop();
  43916. lastPoint = new PIXI.Point( points[points.length - 2], points[points.length - 1] );
  43917. var midPointX = lastPoint.x + (firstPoint.x - lastPoint.x) *0.5;
  43918. var midPointY = lastPoint.y + (firstPoint.y - lastPoint.y) *0.5;
  43919. points.unshift(midPointX, midPointY);
  43920. points.push(midPointX, midPointY);
  43921. }
  43922. var verts = webGLData.points;
  43923. var indices = webGLData.indices;
  43924. var length = points.length / 2;
  43925. var indexCount = points.length;
  43926. var indexStart = verts.length/6;
  43927. // DRAW the Line
  43928. var width = graphicsData.lineWidth / 2;
  43929. // sort color
  43930. var color = PIXI.hex2rgb(graphicsData.lineColor);
  43931. var alpha = graphicsData.lineAlpha;
  43932. var r = color[0] * alpha;
  43933. var g = color[1] * alpha;
  43934. var b = color[2] * alpha;
  43935. var px, py, p1x, p1y, p2x, p2y, p3x, p3y;
  43936. var perpx, perpy, perp2x, perp2y, perp3x, perp3y;
  43937. var a1, b1, c1, a2, b2, c2;
  43938. var denom, pdist, dist;
  43939. p1x = points[0];
  43940. p1y = points[1];
  43941. p2x = points[2];
  43942. p2y = points[3];
  43943. perpx = -(p1y - p2y);
  43944. perpy = p1x - p2x;
  43945. dist = Math.sqrt(perpx*perpx + perpy*perpy);
  43946. perpx /= dist;
  43947. perpy /= dist;
  43948. perpx *= width;
  43949. perpy *= width;
  43950. // start
  43951. verts.push(p1x - perpx , p1y - perpy,
  43952. r, g, b, alpha);
  43953. verts.push(p1x + perpx , p1y + perpy,
  43954. r, g, b, alpha);
  43955. for (i = 1; i < length-1; i++)
  43956. {
  43957. p1x = points[(i-1)*2];
  43958. p1y = points[(i-1)*2 + 1];
  43959. p2x = points[(i)*2];
  43960. p2y = points[(i)*2 + 1];
  43961. p3x = points[(i+1)*2];
  43962. p3y = points[(i+1)*2 + 1];
  43963. perpx = -(p1y - p2y);
  43964. perpy = p1x - p2x;
  43965. dist = Math.sqrt(perpx*perpx + perpy*perpy);
  43966. perpx /= dist;
  43967. perpy /= dist;
  43968. perpx *= width;
  43969. perpy *= width;
  43970. perp2x = -(p2y - p3y);
  43971. perp2y = p2x - p3x;
  43972. dist = Math.sqrt(perp2x*perp2x + perp2y*perp2y);
  43973. perp2x /= dist;
  43974. perp2y /= dist;
  43975. perp2x *= width;
  43976. perp2y *= width;
  43977. a1 = (-perpy + p1y) - (-perpy + p2y);
  43978. b1 = (-perpx + p2x) - (-perpx + p1x);
  43979. c1 = (-perpx + p1x) * (-perpy + p2y) - (-perpx + p2x) * (-perpy + p1y);
  43980. a2 = (-perp2y + p3y) - (-perp2y + p2y);
  43981. b2 = (-perp2x + p2x) - (-perp2x + p3x);
  43982. c2 = (-perp2x + p3x) * (-perp2y + p2y) - (-perp2x + p2x) * (-perp2y + p3y);
  43983. denom = a1*b2 - a2*b1;
  43984. if(Math.abs(denom) < 0.1 )
  43985. {
  43986. denom+=10.1;
  43987. verts.push(p2x - perpx , p2y - perpy,
  43988. r, g, b, alpha);
  43989. verts.push(p2x + perpx , p2y + perpy,
  43990. r, g, b, alpha);
  43991. continue;
  43992. }
  43993. px = (b1*c2 - b2*c1)/denom;
  43994. py = (a2*c1 - a1*c2)/denom;
  43995. pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y);
  43996. if(pdist > 140 * 140)
  43997. {
  43998. perp3x = perpx - perp2x;
  43999. perp3y = perpy - perp2y;
  44000. dist = Math.sqrt(perp3x*perp3x + perp3y*perp3y);
  44001. perp3x /= dist;
  44002. perp3y /= dist;
  44003. perp3x *= width;
  44004. perp3y *= width;
  44005. verts.push(p2x - perp3x, p2y -perp3y);
  44006. verts.push(r, g, b, alpha);
  44007. verts.push(p2x + perp3x, p2y +perp3y);
  44008. verts.push(r, g, b, alpha);
  44009. verts.push(p2x - perp3x, p2y -perp3y);
  44010. verts.push(r, g, b, alpha);
  44011. indexCount++;
  44012. }
  44013. else
  44014. {
  44015. verts.push(px , py);
  44016. verts.push(r, g, b, alpha);
  44017. verts.push(p2x - (px-p2x), p2y - (py - p2y));
  44018. verts.push(r, g, b, alpha);
  44019. }
  44020. }
  44021. p1x = points[(length-2)*2];
  44022. p1y = points[(length-2)*2 + 1];
  44023. p2x = points[(length-1)*2];
  44024. p2y = points[(length-1)*2 + 1];
  44025. perpx = -(p1y - p2y);
  44026. perpy = p1x - p2x;
  44027. dist = Math.sqrt(perpx*perpx + perpy*perpy);
  44028. perpx /= dist;
  44029. perpy /= dist;
  44030. perpx *= width;
  44031. perpy *= width;
  44032. verts.push(p2x - perpx , p2y - perpy);
  44033. verts.push(r, g, b, alpha);
  44034. verts.push(p2x + perpx , p2y + perpy);
  44035. verts.push(r, g, b, alpha);
  44036. indices.push(indexStart);
  44037. for (i = 0; i < indexCount; i++)
  44038. {
  44039. indices.push(indexStart++);
  44040. }
  44041. indices.push(indexStart-1);
  44042. };
  44043. /**
  44044. * Builds a complex polygon to draw
  44045. *
  44046. * @static
  44047. * @private
  44048. * @method buildComplexPoly
  44049. * @param graphicsData {Graphics} The graphics object containing all the necessary properties
  44050. * @param webGLData {Object}
  44051. */
  44052. PIXI.WebGLGraphics.buildComplexPoly = function(graphicsData, webGLData)
  44053. {
  44054. //TODO - no need to copy this as it gets turned into a FLoat32Array anyways..
  44055. var points = graphicsData.points.slice();
  44056. if(points.length < 6)return;
  44057. // get first and last point.. figure out the middle!
  44058. var indices = webGLData.indices;
  44059. webGLData.points = points;
  44060. webGLData.alpha = graphicsData.fillAlpha;
  44061. webGLData.color = PIXI.hex2rgb(graphicsData.fillColor);
  44062. /*
  44063. calclate the bounds..
  44064. */
  44065. var minX = Infinity;
  44066. var maxX = -Infinity;
  44067. var minY = Infinity;
  44068. var maxY = -Infinity;
  44069. var x,y;
  44070. // get size..
  44071. for (var i = 0; i < points.length; i+=2)
  44072. {
  44073. x = points[i];
  44074. y = points[i+1];
  44075. minX = x < minX ? x : minX;
  44076. maxX = x > maxX ? x : maxX;
  44077. minY = y < minY ? y : minY;
  44078. maxY = y > maxY ? y : maxY;
  44079. }
  44080. // add a quad to the end cos there is no point making another buffer!
  44081. points.push(minX, minY,
  44082. maxX, minY,
  44083. maxX, maxY,
  44084. minX, maxY);
  44085. // push a quad onto the end..
  44086. //TODO - this aint needed!
  44087. var length = points.length / 2;
  44088. for (i = 0; i < length; i++)
  44089. {
  44090. indices.push( i );
  44091. }
  44092. };
  44093. /**
  44094. * Builds a polygon to draw
  44095. *
  44096. * @static
  44097. * @private
  44098. * @method buildPoly
  44099. * @param graphicsData {Graphics} The graphics object containing all the necessary properties
  44100. * @param webGLData {Object}
  44101. */
  44102. PIXI.WebGLGraphics.buildPoly = function(graphicsData, webGLData)
  44103. {
  44104. var points = graphicsData.points;
  44105. if(points.length < 6)return;
  44106. // get first and last point.. figure out the middle!
  44107. var verts = webGLData.points;
  44108. var indices = webGLData.indices;
  44109. var length = points.length / 2;
  44110. // sort color
  44111. var color = PIXI.hex2rgb(graphicsData.fillColor);
  44112. var alpha = graphicsData.fillAlpha;
  44113. var r = color[0] * alpha;
  44114. var g = color[1] * alpha;
  44115. var b = color[2] * alpha;
  44116. var triangles = PIXI.EarCut.Triangulate(points, null, 2);
  44117. if(!triangles)return false;
  44118. var vertPos = verts.length / 6;
  44119. var i = 0;
  44120. for (i = 0; i < triangles.length; i+=3)
  44121. {
  44122. indices.push(triangles[i] + vertPos);
  44123. indices.push(triangles[i] + vertPos);
  44124. indices.push(triangles[i+1] + vertPos);
  44125. indices.push(triangles[i+2] +vertPos);
  44126. indices.push(triangles[i+2] + vertPos);
  44127. }
  44128. for (i = 0; i < length; i++)
  44129. {
  44130. verts.push(points[i * 2], points[i * 2 + 1],
  44131. r, g, b, alpha);
  44132. }
  44133. return true;
  44134. };
  44135. PIXI.WebGLGraphics.graphicsDataPool = [];
  44136. /**
  44137. * @class WebGLGraphicsData
  44138. * @private
  44139. * @static
  44140. */
  44141. PIXI.WebGLGraphicsData = function(gl)
  44142. {
  44143. this.gl = gl;
  44144. //TODO does this need to be split before uploding??
  44145. this.color = [0,0,0]; // color split!
  44146. this.points = [];
  44147. this.indices = [];
  44148. this.buffer = gl.createBuffer();
  44149. this.indexBuffer = gl.createBuffer();
  44150. this.mode = 1;
  44151. this.alpha = 1;
  44152. this.dirty = true;
  44153. };
  44154. /**
  44155. * @method reset
  44156. */
  44157. PIXI.WebGLGraphicsData.prototype.reset = function()
  44158. {
  44159. this.points = [];
  44160. this.indices = [];
  44161. };
  44162. /**
  44163. * @method upload
  44164. */
  44165. PIXI.WebGLGraphicsData.prototype.upload = function()
  44166. {
  44167. var gl = this.gl;
  44168. // this.lastIndex = graphics.graphicsData.length;
  44169. this.glPoints = new PIXI.Float32Array(this.points);
  44170. gl.bindBuffer(gl.ARRAY_BUFFER, this.buffer);
  44171. gl.bufferData(gl.ARRAY_BUFFER, this.glPoints, gl.STATIC_DRAW);
  44172. this.glIndicies = new PIXI.Uint16Array(this.indices);
  44173. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
  44174. gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.glIndicies, gl.STATIC_DRAW);
  44175. this.dirty = false;
  44176. };
  44177. /**
  44178. * @author Mat Groves http://matgroves.com/ @Doormat23
  44179. */
  44180. /**
  44181. * A set of functions used by the canvas renderer to draw the primitive graphics data.
  44182. *
  44183. * @class CanvasGraphics
  44184. * @static
  44185. */
  44186. PIXI.CanvasGraphics = function()
  44187. {
  44188. };
  44189. /*
  44190. * Renders a PIXI.Graphics object to a canvas.
  44191. *
  44192. * @method renderGraphics
  44193. * @static
  44194. * @param graphics {Graphics} the actual graphics object to render
  44195. * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas
  44196. */
  44197. PIXI.CanvasGraphics.renderGraphics = function(graphics, context)
  44198. {
  44199. var worldAlpha = graphics.worldAlpha;
  44200. if (graphics.dirty)
  44201. {
  44202. this.updateGraphicsTint(graphics);
  44203. graphics.dirty = false;
  44204. }
  44205. for (var i = 0; i < graphics.graphicsData.length; i++)
  44206. {
  44207. var data = graphics.graphicsData[i];
  44208. var shape = data.shape;
  44209. var fillColor = data._fillTint;
  44210. var lineColor = data._lineTint;
  44211. context.lineWidth = data.lineWidth;
  44212. if (data.type === PIXI.Graphics.POLY)
  44213. {
  44214. context.beginPath();
  44215. var points = shape.points;
  44216. context.moveTo(points[0], points[1]);
  44217. for (var j=1; j < points.length/2; j++)
  44218. {
  44219. context.lineTo(points[j * 2], points[j * 2 + 1]);
  44220. }
  44221. if (shape.closed)
  44222. {
  44223. context.lineTo(points[0], points[1]);
  44224. }
  44225. // if the first and last point are the same close the path - much neater :)
  44226. if (points[0] === points[points.length-2] && points[1] === points[points.length-1])
  44227. {
  44228. context.closePath();
  44229. }
  44230. if (data.fill)
  44231. {
  44232. context.globalAlpha = data.fillAlpha * worldAlpha;
  44233. context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6);
  44234. context.fill();
  44235. }
  44236. if (data.lineWidth)
  44237. {
  44238. context.globalAlpha = data.lineAlpha * worldAlpha;
  44239. context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6);
  44240. context.stroke();
  44241. }
  44242. }
  44243. else if (data.type === PIXI.Graphics.RECT)
  44244. {
  44245. if (data.fillColor || data.fillColor === 0)
  44246. {
  44247. context.globalAlpha = data.fillAlpha * worldAlpha;
  44248. context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6);
  44249. context.fillRect(shape.x, shape.y, shape.width, shape.height);
  44250. }
  44251. if (data.lineWidth)
  44252. {
  44253. context.globalAlpha = data.lineAlpha * worldAlpha;
  44254. context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6);
  44255. context.strokeRect(shape.x, shape.y, shape.width, shape.height);
  44256. }
  44257. }
  44258. else if (data.type === PIXI.Graphics.CIRC)
  44259. {
  44260. // TODO - need to be Undefined!
  44261. context.beginPath();
  44262. context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI);
  44263. context.closePath();
  44264. if (data.fill)
  44265. {
  44266. context.globalAlpha = data.fillAlpha * worldAlpha;
  44267. context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6);
  44268. context.fill();
  44269. }
  44270. if (data.lineWidth)
  44271. {
  44272. context.globalAlpha = data.lineAlpha * worldAlpha;
  44273. context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6);
  44274. context.stroke();
  44275. }
  44276. }
  44277. else if (data.type === PIXI.Graphics.ELIP)
  44278. {
  44279. // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  44280. var w = shape.width * 2;
  44281. var h = shape.height * 2;
  44282. var x = shape.x - w/2;
  44283. var y = shape.y - h/2;
  44284. context.beginPath();
  44285. var kappa = 0.5522848,
  44286. ox = (w / 2) * kappa, // control point offset horizontal
  44287. oy = (h / 2) * kappa, // control point offset vertical
  44288. xe = x + w, // x-end
  44289. ye = y + h, // y-end
  44290. xm = x + w / 2, // x-middle
  44291. ym = y + h / 2; // y-middle
  44292. context.moveTo(x, ym);
  44293. context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  44294. context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  44295. context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  44296. context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  44297. context.closePath();
  44298. if (data.fill)
  44299. {
  44300. context.globalAlpha = data.fillAlpha * worldAlpha;
  44301. context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6);
  44302. context.fill();
  44303. }
  44304. if (data.lineWidth)
  44305. {
  44306. context.globalAlpha = data.lineAlpha * worldAlpha;
  44307. context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6);
  44308. context.stroke();
  44309. }
  44310. }
  44311. else if (data.type === PIXI.Graphics.RREC)
  44312. {
  44313. var rx = shape.x;
  44314. var ry = shape.y;
  44315. var width = shape.width;
  44316. var height = shape.height;
  44317. var radius = shape.radius;
  44318. var maxRadius = Math.min(width, height) / 2 | 0;
  44319. radius = radius > maxRadius ? maxRadius : radius;
  44320. context.beginPath();
  44321. context.moveTo(rx, ry + radius);
  44322. context.lineTo(rx, ry + height - radius);
  44323. context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height);
  44324. context.lineTo(rx + width - radius, ry + height);
  44325. context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius);
  44326. context.lineTo(rx + width, ry + radius);
  44327. context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry);
  44328. context.lineTo(rx + radius, ry);
  44329. context.quadraticCurveTo(rx, ry, rx, ry + radius);
  44330. context.closePath();
  44331. if (data.fillColor || data.fillColor === 0)
  44332. {
  44333. context.globalAlpha = data.fillAlpha * worldAlpha;
  44334. context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6);
  44335. context.fill();
  44336. }
  44337. if (data.lineWidth)
  44338. {
  44339. context.globalAlpha = data.lineAlpha * worldAlpha;
  44340. context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6);
  44341. context.stroke();
  44342. }
  44343. }
  44344. }
  44345. };
  44346. /*
  44347. * Renders a graphics mask
  44348. *
  44349. * @static
  44350. * @private
  44351. * @method renderGraphicsMask
  44352. * @param graphics {Graphics} the graphics which will be used as a mask
  44353. * @param context {CanvasRenderingContext2D} the context 2d method of the canvas
  44354. */
  44355. PIXI.CanvasGraphics.renderGraphicsMask = function(graphics, context)
  44356. {
  44357. var len = graphics.graphicsData.length;
  44358. if (len === 0)
  44359. {
  44360. return;
  44361. }
  44362. context.beginPath();
  44363. for (var i = 0; i < len; i++)
  44364. {
  44365. var data = graphics.graphicsData[i];
  44366. var shape = data.shape;
  44367. if (data.type === PIXI.Graphics.POLY)
  44368. {
  44369. var points = shape.points;
  44370. context.moveTo(points[0], points[1]);
  44371. for (var j=1; j < points.length/2; j++)
  44372. {
  44373. context.lineTo(points[j * 2], points[j * 2 + 1]);
  44374. }
  44375. // if the first and last point are the same close the path - much neater :)
  44376. if (points[0] === points[points.length-2] && points[1] === points[points.length-1])
  44377. {
  44378. context.closePath();
  44379. }
  44380. }
  44381. else if (data.type === PIXI.Graphics.RECT)
  44382. {
  44383. context.rect(shape.x, shape.y, shape.width, shape.height);
  44384. context.closePath();
  44385. }
  44386. else if (data.type === PIXI.Graphics.CIRC)
  44387. {
  44388. // TODO - need to be Undefined!
  44389. context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI);
  44390. context.closePath();
  44391. }
  44392. else if (data.type === PIXI.Graphics.ELIP)
  44393. {
  44394. // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  44395. var w = shape.width * 2;
  44396. var h = shape.height * 2;
  44397. var x = shape.x - w/2;
  44398. var y = shape.y - h/2;
  44399. var kappa = 0.5522848,
  44400. ox = (w / 2) * kappa, // control point offset horizontal
  44401. oy = (h / 2) * kappa, // control point offset vertical
  44402. xe = x + w, // x-end
  44403. ye = y + h, // y-end
  44404. xm = x + w / 2, // x-middle
  44405. ym = y + h / 2; // y-middle
  44406. context.moveTo(x, ym);
  44407. context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  44408. context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  44409. context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  44410. context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  44411. context.closePath();
  44412. }
  44413. else if (data.type === PIXI.Graphics.RREC)
  44414. {
  44415. var rx = shape.x;
  44416. var ry = shape.y;
  44417. var width = shape.width;
  44418. var height = shape.height;
  44419. var radius = shape.radius;
  44420. var maxRadius = Math.min(width, height) / 2 | 0;
  44421. radius = radius > maxRadius ? maxRadius : radius;
  44422. context.moveTo(rx, ry + radius);
  44423. context.lineTo(rx, ry + height - radius);
  44424. context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height);
  44425. context.lineTo(rx + width - radius, ry + height);
  44426. context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius);
  44427. context.lineTo(rx + width, ry + radius);
  44428. context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry);
  44429. context.lineTo(rx + radius, ry);
  44430. context.quadraticCurveTo(rx, ry, rx, ry + radius);
  44431. context.closePath();
  44432. }
  44433. }
  44434. };
  44435. PIXI.CanvasGraphics.updateGraphicsTint = function(graphics)
  44436. {
  44437. if (graphics.tint === 0xFFFFFF)
  44438. {
  44439. return;
  44440. }
  44441. var tintR = (graphics.tint >> 16 & 0xFF) / 255;
  44442. var tintG = (graphics.tint >> 8 & 0xFF) / 255;
  44443. var tintB = (graphics.tint & 0xFF)/ 255;
  44444. for (var i = 0; i < graphics.graphicsData.length; i++)
  44445. {
  44446. var data = graphics.graphicsData[i];
  44447. var fillColor = data.fillColor | 0;
  44448. var lineColor = data.lineColor | 0;
  44449. data._fillTint = (((fillColor >> 16 & 0xFF) / 255 * tintR*255 << 16) + ((fillColor >> 8 & 0xFF) / 255 * tintG*255 << 8) + (fillColor & 0xFF) / 255 * tintB*255);
  44450. data._lineTint = (((lineColor >> 16 & 0xFF) / 255 * tintR*255 << 16) + ((lineColor >> 8 & 0xFF) / 255 * tintG*255 << 8) + (lineColor & 0xFF) / 255 * tintB*255);
  44451. }
  44452. };
  44453. /**
  44454. * @author Richard Davey <rich@photonstorm.com>
  44455. * @copyright 2016 Photon Storm Ltd.
  44456. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  44457. */
  44458. /**
  44459. * Creates a new `Graphics` object.
  44460. *
  44461. * @class Phaser.Graphics
  44462. * @constructor
  44463. * @extends PIXI.Graphics
  44464. * @extends Phaser.Component.Core
  44465. * @extends Phaser.Component.Angle
  44466. * @extends Phaser.Component.AutoCull
  44467. * @extends Phaser.Component.Bounds
  44468. * @extends Phaser.Component.Destroy
  44469. * @extends Phaser.Component.FixedToCamera
  44470. * @extends Phaser.Component.InputEnabled
  44471. * @extends Phaser.Component.InWorld
  44472. * @extends Phaser.Component.LifeSpan
  44473. * @extends Phaser.Component.PhysicsBody
  44474. * @extends Phaser.Component.Reset
  44475. * @param {Phaser.Game} game - Current game instance.
  44476. * @param {number} [x=0] - X position of the new graphics object.
  44477. * @param {number} [y=0] - Y position of the new graphics object.
  44478. */
  44479. Phaser.Graphics = function (game, x, y) {
  44480. if (x === undefined) { x = 0; }
  44481. if (y === undefined) { y = 0; }
  44482. /**
  44483. * @property {number} type - The const type of this object.
  44484. * @default
  44485. */
  44486. this.type = Phaser.GRAPHICS;
  44487. /**
  44488. * @property {number} physicsType - The const physics body type of this object.
  44489. * @readonly
  44490. */
  44491. this.physicsType = Phaser.SPRITE;
  44492. /**
  44493. * @property {Phaser.Point} anchor - Required for a Graphics shape to work as a Physics body, do not modify this value.
  44494. * @private
  44495. */
  44496. this.anchor = new Phaser.Point();
  44497. PIXI.Graphics.call(this);
  44498. Phaser.Component.Core.init.call(this, game, x, y, '', null);
  44499. };
  44500. Phaser.Graphics.prototype = Object.create(PIXI.Graphics.prototype);
  44501. Phaser.Graphics.prototype.constructor = Phaser.Graphics;
  44502. Phaser.Component.Core.install.call(Phaser.Graphics.prototype, [
  44503. 'Angle',
  44504. 'AutoCull',
  44505. 'Bounds',
  44506. 'Destroy',
  44507. 'FixedToCamera',
  44508. 'InputEnabled',
  44509. 'InWorld',
  44510. 'LifeSpan',
  44511. 'PhysicsBody',
  44512. 'Reset'
  44513. ]);
  44514. Phaser.Graphics.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate;
  44515. Phaser.Graphics.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate;
  44516. Phaser.Graphics.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate;
  44517. Phaser.Graphics.prototype.preUpdateCore = Phaser.Component.Core.preUpdate;
  44518. /**
  44519. * Automatically called by World.preUpdate.
  44520. *
  44521. * @method
  44522. * @memberof Phaser.Graphics
  44523. */
  44524. Phaser.Graphics.prototype.preUpdate = function () {
  44525. if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld())
  44526. {
  44527. return false;
  44528. }
  44529. return this.preUpdateCore();
  44530. };
  44531. /**
  44532. * Destroy this Graphics instance.
  44533. *
  44534. * @method Phaser.Graphics.prototype.destroy
  44535. * @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called?
  44536. */
  44537. Phaser.Graphics.prototype.destroy = function(destroyChildren) {
  44538. this.clear();
  44539. Phaser.Component.Destroy.prototype.destroy.call(this, destroyChildren);
  44540. };
  44541. /*
  44542. * Draws a single {Phaser.Polygon} triangle from a {Phaser.Point} array
  44543. *
  44544. * @method Phaser.Graphics.prototype.drawTriangle
  44545. * @param {Array<Phaser.Point>} points - An array of Phaser.Points that make up the three vertices of this triangle
  44546. * @param {boolean} [cull=false] - Should we check if the triangle is back-facing
  44547. */
  44548. Phaser.Graphics.prototype.drawTriangle = function(points, cull) {
  44549. if (cull === undefined) { cull = false; }
  44550. var triangle = new Phaser.Polygon(points);
  44551. if (cull)
  44552. {
  44553. var cameraToFace = new Phaser.Point(this.game.camera.x - points[0].x, this.game.camera.y - points[0].y);
  44554. var ab = new Phaser.Point(points[1].x - points[0].x, points[1].y - points[0].y);
  44555. var cb = new Phaser.Point(points[1].x - points[2].x, points[1].y - points[2].y);
  44556. var faceNormal = cb.cross(ab);
  44557. if (cameraToFace.dot(faceNormal) > 0)
  44558. {
  44559. this.drawPolygon(triangle);
  44560. }
  44561. }
  44562. else
  44563. {
  44564. this.drawPolygon(triangle);
  44565. }
  44566. };
  44567. /*
  44568. * Draws {Phaser.Polygon} triangles
  44569. *
  44570. * @method Phaser.Graphics.prototype.drawTriangles
  44571. * @param {Array<Phaser.Point>|Array<number>} vertices - An array of Phaser.Points or numbers that make up the vertices of the triangles
  44572. * @param {Array<number>} {indices=null} - An array of numbers that describe what order to draw the vertices in
  44573. * @param {boolean} [cull=false] - Should we check if the triangle is back-facing
  44574. */
  44575. Phaser.Graphics.prototype.drawTriangles = function(vertices, indices, cull) {
  44576. if (cull === undefined) { cull = false; }
  44577. var point1 = new Phaser.Point();
  44578. var point2 = new Phaser.Point();
  44579. var point3 = new Phaser.Point();
  44580. var points = [];
  44581. var i;
  44582. if (!indices)
  44583. {
  44584. if (vertices[0] instanceof Phaser.Point)
  44585. {
  44586. for (i = 0; i < vertices.length / 3; i++)
  44587. {
  44588. this.drawTriangle([vertices[i * 3], vertices[i * 3 + 1], vertices[i * 3 + 2]], cull);
  44589. }
  44590. }
  44591. else
  44592. {
  44593. for (i = 0; i < vertices.length / 6; i++)
  44594. {
  44595. point1.x = vertices[i * 6 + 0];
  44596. point1.y = vertices[i * 6 + 1];
  44597. point2.x = vertices[i * 6 + 2];
  44598. point2.y = vertices[i * 6 + 3];
  44599. point3.x = vertices[i * 6 + 4];
  44600. point3.y = vertices[i * 6 + 5];
  44601. this.drawTriangle([point1, point2, point3], cull);
  44602. }
  44603. }
  44604. }
  44605. else
  44606. {
  44607. if (vertices[0] instanceof Phaser.Point)
  44608. {
  44609. for (i = 0; i < indices.length /3; i++)
  44610. {
  44611. points.push(vertices[indices[i * 3 ]]);
  44612. points.push(vertices[indices[i * 3 + 1]]);
  44613. points.push(vertices[indices[i * 3 + 2]]);
  44614. if (points.length === 3)
  44615. {
  44616. this.drawTriangle(points, cull);
  44617. points = [];
  44618. }
  44619. }
  44620. }
  44621. else
  44622. {
  44623. for (i = 0; i < indices.length; i++)
  44624. {
  44625. point1.x = vertices[indices[i] * 2];
  44626. point1.y = vertices[indices[i] * 2 + 1];
  44627. points.push(point1.copyTo({}));
  44628. if (points.length === 3)
  44629. {
  44630. this.drawTriangle(points, cull);
  44631. points = [];
  44632. }
  44633. }
  44634. }
  44635. }
  44636. };
  44637. /**
  44638. * @author Richard Davey <rich@photonstorm.com>
  44639. * @copyright 2016 Photon Storm Ltd.
  44640. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  44641. */
  44642. /**
  44643. * A RenderTexture is a special texture that allows any displayObject to be rendered to it. It allows you to take many complex objects and
  44644. * render them down into a single quad (on WebGL) which can then be used to texture other display objects with. A way of generating textures at run-time.
  44645. *
  44646. * @class Phaser.RenderTexture
  44647. * @constructor
  44648. * @extends PIXI.RenderTexture
  44649. * @param {Phaser.Game} game - Current game instance.
  44650. * @param {string} key - Internal Phaser reference key for the render texture.
  44651. * @param {number} [width=100] - The width of the render texture.
  44652. * @param {number} [height=100] - The height of the render texture.
  44653. * @param {string} [key=''] - The key of the RenderTexture in the Cache, if stored there.
  44654. * @param {number} [scaleMode=Phaser.scaleModes.DEFAULT] - One of the Phaser.scaleModes consts.
  44655. * @param {number} [resolution=1] - The resolution of the texture being generated.
  44656. */
  44657. Phaser.RenderTexture = function (game, width, height, key, scaleMode, resolution) {
  44658. if (key === undefined) { key = ''; }
  44659. if (scaleMode === undefined) { scaleMode = Phaser.scaleModes.DEFAULT; }
  44660. if (resolution === undefined) { resolution = 1; }
  44661. /**
  44662. * @property {Phaser.Game} game - A reference to the currently running game.
  44663. */
  44664. this.game = game;
  44665. /**
  44666. * @property {string} key - The key of the RenderTexture in the Cache, if stored there.
  44667. */
  44668. this.key = key;
  44669. /**
  44670. * @property {number} type - Base Phaser object type.
  44671. */
  44672. this.type = Phaser.RENDERTEXTURE;
  44673. /**
  44674. * @property {PIXI.Matrix} _tempMatrix - The matrix that is applied when display objects are rendered to this RenderTexture.
  44675. * @private
  44676. */
  44677. this._tempMatrix = new PIXI.Matrix();
  44678. PIXI.RenderTexture.call(this, width, height, this.game.renderer, scaleMode, resolution);
  44679. this.render = Phaser.RenderTexture.prototype.render;
  44680. };
  44681. Phaser.RenderTexture.prototype = Object.create(PIXI.RenderTexture.prototype);
  44682. Phaser.RenderTexture.prototype.constructor = Phaser.RenderTexture;
  44683. /**
  44684. * This function will draw the display object to the RenderTexture at the given coordinates.
  44685. *
  44686. * When the display object is drawn it takes into account scale and rotation.
  44687. *
  44688. * If you don't want those then use RenderTexture.renderRawXY instead.
  44689. *
  44690. * @method Phaser.RenderTexture.prototype.renderXY
  44691. * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Group} displayObject - The display object to render to this texture.
  44692. * @param {number} x - The x position to render the object at.
  44693. * @param {number} y - The y position to render the object at.
  44694. * @param {boolean} [clear=false] - If true the texture will be cleared before the display object is drawn.
  44695. */
  44696. Phaser.RenderTexture.prototype.renderXY = function (displayObject, x, y, clear) {
  44697. displayObject.updateTransform();
  44698. this._tempMatrix.copyFrom(displayObject.worldTransform);
  44699. this._tempMatrix.tx = x;
  44700. this._tempMatrix.ty = y;
  44701. if (this.renderer.type === PIXI.WEBGL_RENDERER)
  44702. {
  44703. this.renderWebGL(displayObject, this._tempMatrix, clear);
  44704. }
  44705. else
  44706. {
  44707. this.renderCanvas(displayObject, this._tempMatrix, clear);
  44708. }
  44709. };
  44710. /**
  44711. * This function will draw the display object to the RenderTexture at the given coordinates.
  44712. *
  44713. * When the display object is drawn it doesn't take into account scale, rotation or translation.
  44714. *
  44715. * If you need those then use RenderTexture.renderXY instead.
  44716. *
  44717. * @method Phaser.RenderTexture.prototype.renderRawXY
  44718. * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Group} displayObject - The display object to render to this texture.
  44719. * @param {number} x - The x position to render the object at.
  44720. * @param {number} y - The y position to render the object at.
  44721. * @param {boolean} [clear=false] - If true the texture will be cleared before the display object is drawn.
  44722. */
  44723. Phaser.RenderTexture.prototype.renderRawXY = function (displayObject, x, y, clear) {
  44724. this._tempMatrix.identity().translate(x, y);
  44725. if (this.renderer.type === PIXI.WEBGL_RENDERER)
  44726. {
  44727. this.renderWebGL(displayObject, this._tempMatrix, clear);
  44728. }
  44729. else
  44730. {
  44731. this.renderCanvas(displayObject, this._tempMatrix, clear);
  44732. }
  44733. };
  44734. /**
  44735. * This function will draw the display object to the RenderTexture.
  44736. *
  44737. * In versions of Phaser prior to 2.4.0 the second parameter was a Phaser.Point object.
  44738. * This is now a Matrix allowing you much more control over how the Display Object is rendered.
  44739. * If you need to replicate the earlier behavior please use Phaser.RenderTexture.renderXY instead.
  44740. *
  44741. * If you wish for the displayObject to be rendered taking its current scale, rotation and translation into account then either
  44742. * pass `null`, leave it undefined or pass `displayObject.worldTransform` as the matrix value.
  44743. *
  44744. * @method Phaser.RenderTexture.prototype.render
  44745. * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Group} displayObject - The display object to render to this texture.
  44746. * @param {Phaser.Matrix} [matrix] - Optional matrix to apply to the display object before rendering. If null or undefined it will use the worldTransform matrix of the given display object.
  44747. * @param {boolean} [clear=false] - If true the texture will be cleared before the display object is drawn.
  44748. */
  44749. Phaser.RenderTexture.prototype.render = function (displayObject, matrix, clear) {
  44750. if (matrix === undefined || matrix === null)
  44751. {
  44752. this._tempMatrix.copyFrom(displayObject.worldTransform);
  44753. }
  44754. else
  44755. {
  44756. this._tempMatrix.copyFrom(matrix);
  44757. }
  44758. if (this.renderer.type === PIXI.WEBGL_RENDERER)
  44759. {
  44760. this.renderWebGL(displayObject, this._tempMatrix, clear);
  44761. }
  44762. else
  44763. {
  44764. this.renderCanvas(displayObject, this._tempMatrix, clear);
  44765. }
  44766. };
  44767. /**
  44768. * @author Richard Davey <rich@photonstorm.com>
  44769. * @copyright 2016 Photon Storm Ltd.
  44770. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  44771. */
  44772. /**
  44773. * Create a new game object for displaying Text.
  44774. *
  44775. * This uses a local hidden Canvas object and renders the type into it. It then makes a texture from this for rendering to the view.
  44776. * Because of this you can only display fonts that are currently loaded and available to the browser: fonts must be pre-loaded.
  44777. *
  44778. * See {@link http://www.jordanm.co.uk/tinytype this compatibility table} for the available default fonts across mobile browsers.
  44779. *
  44780. * @class Phaser.Text
  44781. * @extends Phaser.Sprite
  44782. * @constructor
  44783. * @param {Phaser.Game} game - Current game instance.
  44784. * @param {number} x - X position of the new text object.
  44785. * @param {number} y - Y position of the new text object.
  44786. * @param {string} text - The actual text that will be written.
  44787. * @param {object} [style] - The style properties to be set on the Text.
  44788. * @param {string} [style.font='bold 20pt Arial'] - The style and size of the font.
  44789. * @param {string} [style.fontStyle=(from font)] - The style of the font (eg. 'italic'): overrides the value in `style.font`.
  44790. * @param {string} [style.fontVariant=(from font)] - The variant of the font (eg. 'small-caps'): overrides the value in `style.font`.
  44791. * @param {string} [style.fontWeight=(from font)] - The weight of the font (eg. 'bold'): overrides the value in `style.font`.
  44792. * @param {string|number} [style.fontSize=(from font)] - The size of the font (eg. 32 or '32px'): overrides the value in `style.font`.
  44793. * @param {string} [style.backgroundColor=null] - A canvas fillstyle that will be used as the background for the whole Text object. Set to `null` to disable.
  44794. * @param {string} [style.fill='black'] - A canvas fillstyle that will be used on the text eg 'red', '#00FF00'.
  44795. * @param {string} [style.align='left'] - Horizontal alignment of each line in multiline text. Can be: 'left', 'center' or 'right'. Does not affect single lines of text (see `textBounds` and `boundsAlignH` for that).
  44796. * @param {string} [style.boundsAlignH='left'] - Horizontal alignment of the text within the `textBounds`. Can be: 'left', 'center' or 'right'.
  44797. * @param {string} [style.boundsAlignV='top'] - Vertical alignment of the text within the `textBounds`. Can be: 'top', 'middle' or 'bottom'.
  44798. * @param {string} [style.stroke='black'] - A canvas stroke style that will be used on the text stroke eg 'blue', '#FCFF00'.
  44799. * @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. Default is 0 (no stroke).
  44800. * @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used.
  44801. * @param {number} [style.wordWrapWidth=100] - The width in pixels at which text will wrap.
  44802. * @param {number} [style.maxLines=0] - The maximum number of lines to be shown for wrapped text.
  44803. * @param {number} [style.tabs=0] - The size (in pixels) of the tabs, for when text includes tab characters. 0 disables. Can be an array of varying tab sizes, one per tab stop.
  44804. */
  44805. Phaser.Text = function (game, x, y, text, style) {
  44806. x = x || 0;
  44807. y = y || 0;
  44808. if (text === undefined || text === null)
  44809. {
  44810. text = '';
  44811. }
  44812. else
  44813. {
  44814. text = text.toString();
  44815. }
  44816. style = Phaser.Utils.extend({}, style);
  44817. /**
  44818. * @property {number} type - The const type of this object.
  44819. * @default
  44820. */
  44821. this.type = Phaser.TEXT;
  44822. /**
  44823. * @property {number} physicsType - The const physics body type of this object.
  44824. * @readonly
  44825. */
  44826. this.physicsType = Phaser.SPRITE;
  44827. /**
  44828. * Specify a padding value which is added to the line width and height when calculating the Text size.
  44829. * ALlows you to add extra spacing if Phaser is unable to accurately determine the true font dimensions.
  44830. * @property {Phaser.Point} padding
  44831. */
  44832. this.padding = new Phaser.Point();
  44833. /**
  44834. * The textBounds property allows you to specify a rectangular region upon which text alignment is based.
  44835. * See `Text.setTextBounds` for more details.
  44836. * @property {Phaser.Rectangle} textBounds
  44837. * @readOnly
  44838. */
  44839. this.textBounds = null;
  44840. /**
  44841. * @property {HTMLCanvasElement} canvas - The canvas element that the text is rendered.
  44842. */
  44843. this.canvas = PIXI.CanvasPool.create(this);
  44844. /**
  44845. * @property {HTMLCanvasElement} context - The context of the canvas element that the text is rendered to.
  44846. */
  44847. this.context = this.canvas.getContext('2d');
  44848. /**
  44849. * @property {array} colors - An array of the color values as specified by {@link Phaser.Text#addColor addColor}.
  44850. */
  44851. this.colors = [];
  44852. /**
  44853. * @property {array} strokeColors - An array of the stroke color values as specified by {@link Phaser.Text#addStrokeColor addStrokeColor}.
  44854. */
  44855. this.strokeColors = [];
  44856. /**
  44857. * @property {array} fontStyles - An array of the font styles values as specified by {@link Phaser.Text#addFontStyle addFontStyle}.
  44858. */
  44859. this.fontStyles = [];
  44860. /**
  44861. * @property {array} fontWeights - An array of the font weights values as specified by {@link Phaser.Text#addFontWeight addFontWeight}.
  44862. */
  44863. this.fontWeights = [];
  44864. /**
  44865. * Should the linePositionX and Y values be automatically rounded before rendering the Text?
  44866. * You may wish to enable this if you want to remove the effect of sub-pixel aliasing from text.
  44867. * @property {boolean} autoRound
  44868. * @default
  44869. */
  44870. this.autoRound = false;
  44871. /**
  44872. * Will this Text object use Basic or Advanced Word Wrapping?
  44873. *
  44874. * Advanced wrapping breaks long words if they are the first of a line, and repeats the process as necessary.
  44875. * White space is condensed (e.g., consecutive spaces are replaced with one).
  44876. * Lines are trimmed of white space before processing.
  44877. *
  44878. * It throws an error if wordWrapWidth is less than a single character.
  44879. * @property {boolean} useAdvancedWrap
  44880. * @default
  44881. */
  44882. this.useAdvancedWrap = false;
  44883. /**
  44884. * @property {number} _res - Internal canvas resolution var.
  44885. * @private
  44886. */
  44887. this._res = game.renderer.resolution;
  44888. /**
  44889. * @property {string} _text - Internal cache var.
  44890. * @private
  44891. */
  44892. this._text = text;
  44893. /**
  44894. * @property {object} _fontComponents - The font, broken down into components, set in `setStyle`.
  44895. * @private
  44896. */
  44897. this._fontComponents = null;
  44898. /**
  44899. * @property {number} lineSpacing - Additional spacing (in pixels) between each line of text if multi-line.
  44900. * @private
  44901. */
  44902. this._lineSpacing = 0;
  44903. /**
  44904. * @property {number} _charCount - Internal character counter used by the text coloring.
  44905. * @private
  44906. */
  44907. this._charCount = 0;
  44908. /**
  44909. * @property {number} _width - Internal width var.
  44910. * @private
  44911. */
  44912. this._width = 0;
  44913. /**
  44914. * @property {number} _height - Internal height var.
  44915. * @private
  44916. */
  44917. this._height = 0;
  44918. Phaser.Sprite.call(this, game, x, y, PIXI.Texture.fromCanvas(this.canvas));
  44919. this.setStyle(style);
  44920. if (text !== '')
  44921. {
  44922. this.updateText();
  44923. }
  44924. };
  44925. Phaser.Text.prototype = Object.create(Phaser.Sprite.prototype);
  44926. Phaser.Text.prototype.constructor = Phaser.Text;
  44927. /**
  44928. * Automatically called by World.preUpdate.
  44929. *
  44930. * @method Phaser.Text#preUpdate
  44931. * @protected
  44932. */
  44933. Phaser.Text.prototype.preUpdate = function () {
  44934. if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld())
  44935. {
  44936. return false;
  44937. }
  44938. return this.preUpdateCore();
  44939. };
  44940. /**
  44941. * Override this function to handle any special update requirements.
  44942. *
  44943. * @method Phaser.Text#update
  44944. * @protected
  44945. */
  44946. Phaser.Text.prototype.update = function() {
  44947. };
  44948. /**
  44949. * Destroy this Text object, removing it from the group it belongs to.
  44950. *
  44951. * @method Phaser.Text#destroy
  44952. * @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called?
  44953. */
  44954. Phaser.Text.prototype.destroy = function (destroyChildren) {
  44955. this.texture.destroy(true);
  44956. PIXI.CanvasPool.remove(this);
  44957. Phaser.Component.Destroy.prototype.destroy.call(this, destroyChildren);
  44958. };
  44959. /**
  44960. * Sets a drop shadow effect on the Text. You can specify the horizontal and vertical distance of the drop shadow with the `x` and `y` parameters.
  44961. * The color controls the shade of the shadow (default is black) and can be either an `rgba` or `hex` value.
  44962. * The blur is the strength of the shadow. A value of zero means a hard shadow, a value of 10 means a very soft shadow.
  44963. * To remove a shadow already in place you can call this method with no parameters set.
  44964. *
  44965. * @method Phaser.Text#setShadow
  44966. * @param {number} [x=0] - The shadowOffsetX value in pixels. This is how far offset horizontally the shadow effect will be.
  44967. * @param {number} [y=0] - The shadowOffsetY value in pixels. This is how far offset vertically the shadow effect will be.
  44968. * @param {string} [color='rgba(0,0,0,1)'] - The color of the shadow, as given in CSS rgba or hex format. Set the alpha component to 0 to disable the shadow.
  44969. * @param {number} [blur=0] - The shadowBlur value. Make the shadow softer by applying a Gaussian blur to it. A number from 0 (no blur) up to approx. 10 (depending on scene).
  44970. * @param {boolean} [shadowStroke=true] - Apply the drop shadow to the Text stroke (if set).
  44971. * @param {boolean} [shadowFill=true] - Apply the drop shadow to the Text fill (if set).
  44972. * @return {Phaser.Text} This Text instance.
  44973. */
  44974. Phaser.Text.prototype.setShadow = function (x, y, color, blur, shadowStroke, shadowFill) {
  44975. if (x === undefined) { x = 0; }
  44976. if (y === undefined) { y = 0; }
  44977. if (color === undefined) { color = 'rgba(0, 0, 0, 1)'; }
  44978. if (blur === undefined) { blur = 0; }
  44979. if (shadowStroke === undefined) { shadowStroke = true; }
  44980. if (shadowFill === undefined) { shadowFill = true; }
  44981. this.style.shadowOffsetX = x;
  44982. this.style.shadowOffsetY = y;
  44983. this.style.shadowColor = color;
  44984. this.style.shadowBlur = blur;
  44985. this.style.shadowStroke = shadowStroke;
  44986. this.style.shadowFill = shadowFill;
  44987. this.dirty = true;
  44988. return this;
  44989. };
  44990. /**
  44991. * Set the style of the text by passing a single style object to it.
  44992. *
  44993. * @method Phaser.Text#setStyle
  44994. * @param {object} [style] - The style properties to be set on the Text.
  44995. * @param {string} [style.font='bold 20pt Arial'] - The style and size of the font.
  44996. * @param {string} [style.fontStyle=(from font)] - The style of the font (eg. 'italic'): overrides the value in `style.font`.
  44997. * @param {string} [style.fontVariant=(from font)] - The variant of the font (eg. 'small-caps'): overrides the value in `style.font`.
  44998. * @param {string} [style.fontWeight=(from font)] - The weight of the font (eg. 'bold'): overrides the value in `style.font`.
  44999. * @param {string|number} [style.fontSize=(from font)] - The size of the font (eg. 32 or '32px'): overrides the value in `style.font`.
  45000. * @param {string} [style.backgroundColor=null] - A canvas fillstyle that will be used as the background for the whole Text object. Set to `null` to disable.
  45001. * @param {string} [style.fill='black'] - A canvas fillstyle that will be used on the text eg 'red', '#00FF00'.
  45002. * @param {string} [style.align='left'] - Horizontal alignment of each line in multiline text. Can be: 'left', 'center' or 'right'. Does not affect single lines of text (see `textBounds` and `boundsAlignH` for that).
  45003. * @param {string} [style.boundsAlignH='left'] - Horizontal alignment of the text within the `textBounds`. Can be: 'left', 'center' or 'right'.
  45004. * @param {string} [style.boundsAlignV='top'] - Vertical alignment of the text within the `textBounds`. Can be: 'top', 'middle' or 'bottom'.
  45005. * @param {string} [style.stroke='black'] - A canvas stroke style that will be used on the text stroke eg 'blue', '#FCFF00'.
  45006. * @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. Default is 0 (no stroke).
  45007. * @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used.
  45008. * @param {number} [style.wordWrapWidth=100] - The width in pixels at which text will wrap.
  45009. * @param {number} [style.maxLines=0] - The maximum number of lines to be shown for wrapped text.
  45010. * @param {number|array} [style.tabs=0] - The size (in pixels) of the tabs, for when text includes tab characters. 0 disables. Can be an array of varying tab sizes, one per tab stop.
  45011. * @return {Phaser.Text} This Text instance.
  45012. */
  45013. Phaser.Text.prototype.setStyle = function (style) {
  45014. style = style || {};
  45015. style.font = style.font || 'bold 20pt Arial';
  45016. style.backgroundColor = style.backgroundColor || null;
  45017. style.fill = style.fill || 'black';
  45018. style.align = style.align || 'left';
  45019. style.boundsAlignH = style.boundsAlignH || 'left';
  45020. style.boundsAlignV = style.boundsAlignV || 'top';
  45021. style.stroke = style.stroke || 'black'; //provide a default, see: https://github.com/GoodBoyDigital/pixi.js/issues/136
  45022. style.strokeThickness = style.strokeThickness || 0;
  45023. style.wordWrap = style.wordWrap || false;
  45024. style.wordWrapWidth = style.wordWrapWidth || 100;
  45025. style.maxLines = style.maxLines || 0;
  45026. style.shadowOffsetX = style.shadowOffsetX || 0;
  45027. style.shadowOffsetY = style.shadowOffsetY || 0;
  45028. style.shadowColor = style.shadowColor || 'rgba(0,0,0,0)';
  45029. style.shadowBlur = style.shadowBlur || 0;
  45030. style.tabs = style.tabs || 0;
  45031. var components = this.fontToComponents(style.font);
  45032. if (style.fontStyle)
  45033. {
  45034. components.fontStyle = style.fontStyle;
  45035. }
  45036. if (style.fontVariant)
  45037. {
  45038. components.fontVariant = style.fontVariant;
  45039. }
  45040. if (style.fontWeight)
  45041. {
  45042. components.fontWeight = style.fontWeight;
  45043. }
  45044. if (style.fontSize)
  45045. {
  45046. if (typeof style.fontSize === 'number')
  45047. {
  45048. style.fontSize = style.fontSize + 'px';
  45049. }
  45050. components.fontSize = style.fontSize;
  45051. }
  45052. this._fontComponents = components;
  45053. style.font = this.componentsToFont(this._fontComponents);
  45054. this.style = style;
  45055. this.dirty = true;
  45056. return this;
  45057. };
  45058. /**
  45059. * Renders text. This replaces the Pixi.Text.updateText function as we need a few extra bits in here.
  45060. *
  45061. * @method Phaser.Text#updateText
  45062. * @private
  45063. */
  45064. Phaser.Text.prototype.updateText = function () {
  45065. this.texture.baseTexture.resolution = this._res;
  45066. this.context.font = this.style.font;
  45067. var outputText = this.text;
  45068. if (this.style.wordWrap)
  45069. {
  45070. outputText = this.runWordWrap(this.text);
  45071. }
  45072. // Split text into lines
  45073. var lines = outputText.split(/(?:\r\n|\r|\n)/);
  45074. // Calculate text width
  45075. var tabs = this.style.tabs;
  45076. var lineWidths = [];
  45077. var maxLineWidth = 0;
  45078. var fontProperties = this.determineFontProperties(this.style.font);
  45079. var drawnLines = lines.length;
  45080. if (this.style.maxLines > 0 && this.style.maxLines < lines.length)
  45081. {
  45082. drawnLines = this.style.maxLines;
  45083. }
  45084. for (var i = 0; i < drawnLines; i++)
  45085. {
  45086. if (tabs === 0)
  45087. {
  45088. // Simple layout (no tabs)
  45089. var lineWidth = this.context.measureText(lines[i]).width + this.style.strokeThickness + this.padding.x;
  45090. // Adjust for wrapped text
  45091. if (this.style.wordWrap)
  45092. {
  45093. lineWidth -= this.context.measureText(' ').width;
  45094. }
  45095. }
  45096. else
  45097. {
  45098. // Complex layout (tabs)
  45099. var line = lines[i].split(/(?:\t)/);
  45100. var lineWidth = this.padding.x + this.style.strokeThickness;
  45101. if (Array.isArray(tabs))
  45102. {
  45103. var tab = 0;
  45104. for (var c = 0; c < line.length; c++)
  45105. {
  45106. var section = Math.ceil(this.context.measureText(line[c]).width);
  45107. if (c > 0)
  45108. {
  45109. tab += tabs[c - 1];
  45110. }
  45111. lineWidth = tab + section;
  45112. }
  45113. }
  45114. else
  45115. {
  45116. for (var c = 0; c < line.length; c++)
  45117. {
  45118. // How far to the next tab?
  45119. lineWidth += Math.ceil(this.context.measureText(line[c]).width);
  45120. var diff = this.game.math.snapToCeil(lineWidth, tabs) - lineWidth;
  45121. lineWidth += diff;
  45122. }
  45123. }
  45124. }
  45125. lineWidths[i] = Math.ceil(lineWidth);
  45126. maxLineWidth = Math.max(maxLineWidth, lineWidths[i]);
  45127. }
  45128. this.canvas.width = maxLineWidth * this._res;
  45129. // Calculate text height
  45130. var lineHeight = fontProperties.fontSize + this.style.strokeThickness + this.padding.y;
  45131. var height = lineHeight * drawnLines;
  45132. var lineSpacing = this._lineSpacing;
  45133. if (lineSpacing < 0 && Math.abs(lineSpacing) > lineHeight)
  45134. {
  45135. lineSpacing = -lineHeight;
  45136. }
  45137. // Adjust for line spacing
  45138. if (lineSpacing !== 0)
  45139. {
  45140. height += (lineSpacing > 0) ? lineSpacing * lines.length : lineSpacing * (lines.length - 1);
  45141. }
  45142. this.canvas.height = height * this._res;
  45143. this.context.scale(this._res, this._res);
  45144. if (navigator.isCocoonJS)
  45145. {
  45146. this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
  45147. }
  45148. if (this.style.backgroundColor)
  45149. {
  45150. this.context.fillStyle = this.style.backgroundColor;
  45151. this.context.fillRect(0, 0, this.canvas.width, this.canvas.height);
  45152. }
  45153. this.context.fillStyle = this.style.fill;
  45154. this.context.font = this.style.font;
  45155. this.context.strokeStyle = this.style.stroke;
  45156. this.context.textBaseline = 'alphabetic';
  45157. this.context.lineWidth = this.style.strokeThickness;
  45158. this.context.lineCap = 'round';
  45159. this.context.lineJoin = 'round';
  45160. var linePositionX;
  45161. var linePositionY;
  45162. this._charCount = 0;
  45163. // Draw text line by line
  45164. for (i = 0; i < drawnLines; i++)
  45165. {
  45166. // Split the line by
  45167. linePositionX = this.style.strokeThickness / 2;
  45168. linePositionY = (this.style.strokeThickness / 2 + i * lineHeight) + fontProperties.ascent;
  45169. if (i > 0)
  45170. {
  45171. linePositionY += (lineSpacing * i);
  45172. }
  45173. if (this.style.align === 'right')
  45174. {
  45175. linePositionX += maxLineWidth - lineWidths[i];
  45176. }
  45177. else if (this.style.align === 'center')
  45178. {
  45179. linePositionX += (maxLineWidth - lineWidths[i]) / 2;
  45180. }
  45181. if (this.autoRound)
  45182. {
  45183. linePositionX = Math.round(linePositionX);
  45184. linePositionY = Math.round(linePositionY);
  45185. }
  45186. if (this.colors.length > 0 || this.strokeColors.length > 0 || this.fontWeights.length > 0 || this.fontStyles.length > 0)
  45187. {
  45188. this.updateLine(lines[i], linePositionX, linePositionY);
  45189. }
  45190. else
  45191. {
  45192. if (this.style.stroke && this.style.strokeThickness)
  45193. {
  45194. this.updateShadow(this.style.shadowStroke);
  45195. if (tabs === 0)
  45196. {
  45197. this.context.strokeText(lines[i], linePositionX, linePositionY);
  45198. }
  45199. else
  45200. {
  45201. this.renderTabLine(lines[i], linePositionX, linePositionY, false);
  45202. }
  45203. }
  45204. if (this.style.fill)
  45205. {
  45206. this.updateShadow(this.style.shadowFill);
  45207. if (tabs === 0)
  45208. {
  45209. this.context.fillText(lines[i], linePositionX, linePositionY);
  45210. }
  45211. else
  45212. {
  45213. this.renderTabLine(lines[i], linePositionX, linePositionY, true);
  45214. }
  45215. }
  45216. }
  45217. }
  45218. this.updateTexture();
  45219. };
  45220. /**
  45221. * Renders a line of text that contains tab characters if Text.tab > 0.
  45222. * Called automatically by updateText.
  45223. *
  45224. * @method Phaser.Text#renderTabLine
  45225. * @private
  45226. * @param {string} line - The line of text to render.
  45227. * @param {integer} x - The x position to start rendering from.
  45228. * @param {integer} y - The y position to start rendering from.
  45229. * @param {boolean} fill - If true uses fillText, if false uses strokeText.
  45230. */
  45231. Phaser.Text.prototype.renderTabLine = function (line, x, y, fill) {
  45232. var text = line.split(/(?:\t)/);
  45233. var tabs = this.style.tabs;
  45234. var snap = 0;
  45235. if (Array.isArray(tabs))
  45236. {
  45237. var tab = 0;
  45238. for (var c = 0; c < text.length; c++)
  45239. {
  45240. if (c > 0)
  45241. {
  45242. tab += tabs[c - 1];
  45243. }
  45244. snap = x + tab;
  45245. if (fill)
  45246. {
  45247. this.context.fillText(text[c], snap, y);
  45248. }
  45249. else
  45250. {
  45251. this.context.strokeText(text[c], snap, y);
  45252. }
  45253. }
  45254. }
  45255. else
  45256. {
  45257. for (var c = 0; c < text.length; c++)
  45258. {
  45259. var section = Math.ceil(this.context.measureText(text[c]).width);
  45260. // How far to the next tab?
  45261. snap = this.game.math.snapToCeil(x, tabs);
  45262. if (fill)
  45263. {
  45264. this.context.fillText(text[c], snap, y);
  45265. }
  45266. else
  45267. {
  45268. this.context.strokeText(text[c], snap, y);
  45269. }
  45270. x = snap + section;
  45271. }
  45272. }
  45273. };
  45274. /**
  45275. * Sets the Shadow on the Text.context based on the Style settings, or disables it if not enabled.
  45276. * This is called automatically by Text.updateText.
  45277. *
  45278. * @method Phaser.Text#updateShadow
  45279. * @param {boolean} state - If true the shadow will be set to the Style values, otherwise it will be set to zero.
  45280. */
  45281. Phaser.Text.prototype.updateShadow = function (state) {
  45282. if (state)
  45283. {
  45284. this.context.shadowOffsetX = this.style.shadowOffsetX;
  45285. this.context.shadowOffsetY = this.style.shadowOffsetY;
  45286. this.context.shadowColor = this.style.shadowColor;
  45287. this.context.shadowBlur = this.style.shadowBlur;
  45288. }
  45289. else
  45290. {
  45291. this.context.shadowOffsetX = 0;
  45292. this.context.shadowOffsetY = 0;
  45293. this.context.shadowColor = 0;
  45294. this.context.shadowBlur = 0;
  45295. }
  45296. };
  45297. /**
  45298. * Updates a line of text, applying fill and stroke per-character colors or style and weight per-character font if applicable.
  45299. *
  45300. * @method Phaser.Text#updateLine
  45301. * @private
  45302. */
  45303. Phaser.Text.prototype.updateLine = function (line, x, y) {
  45304. for (var i = 0; i < line.length; i++)
  45305. {
  45306. var letter = line[i];
  45307. if (this.fontWeights.length > 0 || this.fontStyles.length > 0)
  45308. {
  45309. var components = this.fontToComponents(this.context.font);
  45310. if (this.fontStyles[this._charCount])
  45311. {
  45312. components.fontStyle = this.fontStyles[this._charCount];
  45313. }
  45314. if (this.fontWeights[this._charCount])
  45315. {
  45316. components.fontWeight = this.fontWeights[this._charCount];
  45317. }
  45318. this.context.font = this.componentsToFont(components);
  45319. }
  45320. if (this.style.stroke && this.style.strokeThickness)
  45321. {
  45322. if (this.strokeColors[this._charCount])
  45323. {
  45324. this.context.strokeStyle = this.strokeColors[this._charCount];
  45325. }
  45326. this.updateShadow(this.style.shadowStroke);
  45327. this.context.strokeText(letter, x, y);
  45328. }
  45329. if (this.style.fill)
  45330. {
  45331. if (this.colors[this._charCount])
  45332. {
  45333. this.context.fillStyle = this.colors[this._charCount];
  45334. }
  45335. this.updateShadow(this.style.shadowFill);
  45336. this.context.fillText(letter, x, y);
  45337. }
  45338. x += this.context.measureText(letter).width;
  45339. this._charCount++;
  45340. }
  45341. };
  45342. /**
  45343. * Clears any text fill or stroke colors that were set by `addColor` or `addStrokeColor`.
  45344. *
  45345. * @method Phaser.Text#clearColors
  45346. * @return {Phaser.Text} This Text instance.
  45347. */
  45348. Phaser.Text.prototype.clearColors = function () {
  45349. this.colors = [];
  45350. this.strokeColors = [];
  45351. this.dirty = true;
  45352. return this;
  45353. };
  45354. /**
  45355. * Clears any text styles or weights font that were set by `addFontStyle` or `addFontWeight`.
  45356. *
  45357. * @method Phaser.Text#clearFontValues
  45358. * @return {Phaser.Text} This Text instance.
  45359. */
  45360. Phaser.Text.prototype.clearFontValues = function () {
  45361. this.fontStyles = [];
  45362. this.fontWeights = [];
  45363. this.dirty = true;
  45364. return this;
  45365. };
  45366. /**
  45367. * Set specific colors for certain characters within the Text.
  45368. *
  45369. * It works by taking a color value, which is a typical HTML string such as `#ff0000` or `rgb(255,0,0)` and a position.
  45370. * The position value is the index of the character in the Text string to start applying this color to.
  45371. * Once set the color remains in use until either another color or the end of the string is encountered.
  45372. * For example if the Text was `Photon Storm` and you did `Text.addColor('#ffff00', 6)` it would color in the word `Storm` in yellow.
  45373. *
  45374. * If you wish to change the stroke color see addStrokeColor instead.
  45375. *
  45376. * @method Phaser.Text#addColor
  45377. * @param {string} color - A canvas fillstyle that will be used on the text eg `red`, `#00FF00`, `rgba()`.
  45378. * @param {number} position - The index of the character in the string to start applying this color value from.
  45379. * @return {Phaser.Text} This Text instance.
  45380. */
  45381. Phaser.Text.prototype.addColor = function (color, position) {
  45382. this.colors[position] = color;
  45383. this.dirty = true;
  45384. return this;
  45385. };
  45386. /**
  45387. * Set specific stroke colors for certain characters within the Text.
  45388. *
  45389. * It works by taking a color value, which is a typical HTML string such as `#ff0000` or `rgb(255,0,0)` and a position.
  45390. * The position value is the index of the character in the Text string to start applying this color to.
  45391. * Once set the color remains in use until either another color or the end of the string is encountered.
  45392. * For example if the Text was `Photon Storm` and you did `Text.addColor('#ffff00', 6)` it would color in the word `Storm` in yellow.
  45393. *
  45394. * This has no effect if stroke is disabled or has a thickness of 0.
  45395. *
  45396. * If you wish to change the text fill color see addColor instead.
  45397. *
  45398. * @method Phaser.Text#addStrokeColor
  45399. * @param {string} color - A canvas fillstyle that will be used on the text stroke eg `red`, `#00FF00`, `rgba()`.
  45400. * @param {number} position - The index of the character in the string to start applying this color value from.
  45401. * @return {Phaser.Text} This Text instance.
  45402. */
  45403. Phaser.Text.prototype.addStrokeColor = function (color, position) {
  45404. this.strokeColors[position] = color;
  45405. this.dirty = true;
  45406. return this;
  45407. };
  45408. /**
  45409. * Set specific font styles for certain characters within the Text.
  45410. *
  45411. * It works by taking a font style value, which is a typical string such as `normal`, `italic` or `oblique`.
  45412. * The position value is the index of the character in the Text string to start applying this font style to.
  45413. * Once set the font style remains in use until either another font style or the end of the string is encountered.
  45414. * For example if the Text was `Photon Storm` and you did `Text.addFontStyle('italic', 6)` it would font style in the word `Storm` in italic.
  45415. *
  45416. * If you wish to change the text font weight see addFontWeight instead.
  45417. *
  45418. * @method Phaser.Text#addFontStyle
  45419. * @param {string} style - A canvas font-style that will be used on the text style eg `normal`, `italic`, `oblique`.
  45420. * @param {number} position - The index of the character in the string to start applying this font style value from.
  45421. * @return {Phaser.Text} This Text instance.
  45422. */
  45423. Phaser.Text.prototype.addFontStyle = function (style, position) {
  45424. this.fontStyles[position] = style;
  45425. this.dirty = true;
  45426. return this;
  45427. };
  45428. /**
  45429. * Set specific font weights for certain characters within the Text.
  45430. *
  45431. * It works by taking a font weight value, which is a typical string such as `normal`, `bold`, `bolder`, etc.
  45432. * The position value is the index of the character in the Text string to start applying this font weight to.
  45433. * Once set the font weight remains in use until either another font weight or the end of the string is encountered.
  45434. * For example if the Text was `Photon Storm` and you did `Text.addFontWeight('bold', 6)` it would font weight in the word `Storm` in bold.
  45435. *
  45436. * If you wish to change the text font style see addFontStyle instead.
  45437. *
  45438. * @method Phaser.Text#addFontWeight
  45439. * @param {string} style - A canvas font-weight that will be used on the text weight eg `normal`, `bold`, `bolder`, `lighter`, etc.
  45440. * @param {number} position - The index of the character in the string to start applying this font weight value from.
  45441. * @return {Phaser.Text} This Text instance.
  45442. */
  45443. Phaser.Text.prototype.addFontWeight = function (weight, position) {
  45444. this.fontWeights[position] = weight;
  45445. this.dirty = true;
  45446. return this;
  45447. };
  45448. /**
  45449. * Runs the given text through the Text.runWordWrap function and returns
  45450. * the results as an array, where each element of the array corresponds to a wrapped
  45451. * line of text.
  45452. *
  45453. * Useful if you wish to control pagination on long pieces of content.
  45454. *
  45455. * @method Phaser.Text#precalculateWordWrap
  45456. * @param {string} text - The text for which the wrapping will be calculated.
  45457. * @return {array} An array of strings with the pieces of wrapped text.
  45458. */
  45459. Phaser.Text.prototype.precalculateWordWrap = function (text) {
  45460. this.texture.baseTexture.resolution = this._res;
  45461. this.context.font = this.style.font;
  45462. var wrappedLines = this.runWordWrap(text);
  45463. return wrappedLines.split(/(?:\r\n|\r|\n)/);
  45464. };
  45465. /**
  45466. * Greedy wrapping algorithm that will wrap words as the line grows longer than its horizontal bounds.
  45467. *
  45468. * @method Phaser.Text#runWordWrap
  45469. * @param {string} text - The text to perform word wrap detection against.
  45470. * @private
  45471. */
  45472. Phaser.Text.prototype.runWordWrap = function (text) {
  45473. if (this.useAdvancedWrap)
  45474. {
  45475. return this.advancedWordWrap(text);
  45476. }
  45477. else
  45478. {
  45479. return this.basicWordWrap(text);
  45480. }
  45481. };
  45482. /**
  45483. * Advanced wrapping algorithm that will wrap words as the line grows longer than its horizontal bounds.
  45484. * White space is condensed (e.g., consecutive spaces are replaced with one).
  45485. * Lines are trimmed of white space before processing.
  45486. * Throws an error if the user was smart enough to specify a wordWrapWidth less than a single character.
  45487. *
  45488. * @method Phaser.Text#advancedWordWrap
  45489. * @param {string} text - The text to perform word wrap detection against.
  45490. * @private
  45491. */
  45492. Phaser.Text.prototype.advancedWordWrap = function (text) {
  45493. var context = this.context;
  45494. var wordWrapWidth = this.style.wordWrapWidth;
  45495. var output = '';
  45496. // (1) condense whitespace
  45497. // (2) split into lines
  45498. var lines = text
  45499. .replace(/ +/gi, ' ')
  45500. .split(/\r?\n/gi);
  45501. var linesCount = lines.length;
  45502. for (var i = 0; i < linesCount; i++)
  45503. {
  45504. var line = lines[i];
  45505. var out = '';
  45506. // trim whitespace
  45507. line = line.replace(/^ *|\s*$/gi, '');
  45508. // if entire line is less than wordWrapWidth
  45509. // append the entire line and exit early
  45510. var lineWidth = context.measureText(line).width;
  45511. if (lineWidth < wordWrapWidth)
  45512. {
  45513. output += line + '\n';
  45514. continue;
  45515. }
  45516. // otherwise, calculate new lines
  45517. var currentLineWidth = wordWrapWidth;
  45518. // split into words
  45519. var words = line.split(' ');
  45520. for (var j = 0; j < words.length; j++)
  45521. {
  45522. var word = words[j];
  45523. var wordWithSpace = word + ' ';
  45524. var wordWidth = context.measureText(wordWithSpace).width;
  45525. if (wordWidth > currentLineWidth)
  45526. {
  45527. // break word
  45528. if (j === 0)
  45529. {
  45530. // shave off letters from word until it's small enough
  45531. var newWord = wordWithSpace;
  45532. while (newWord.length)
  45533. {
  45534. newWord = newWord.slice(0, -1);
  45535. wordWidth = context.measureText(newWord).width;
  45536. if (wordWidth <= currentLineWidth)
  45537. {
  45538. break;
  45539. }
  45540. }
  45541. // if wordWrapWidth is too small for even a single
  45542. // letter, shame user failure with a fatal error
  45543. if (!newWord.length)
  45544. {
  45545. throw new Error('This text\'s wordWrapWidth setting is less than a single character!');
  45546. }
  45547. // replace current word in array with remainder
  45548. var secondPart = word.substr(newWord.length);
  45549. words[j] = secondPart;
  45550. // append first piece to output
  45551. out += newWord;
  45552. }
  45553. // if existing word length is 0, don't include it
  45554. var offset = (words[j].length) ? j : j + 1;
  45555. // collapse rest of sentence
  45556. var remainder = words.slice(offset).join(' ')
  45557. // remove any trailing white space
  45558. .replace(/[ \n]*$/gi, '');
  45559. // prepend remainder to next line
  45560. lines[i + 1] = remainder + ' ' + (lines[i + 1] || '');
  45561. linesCount = lines.length;
  45562. break; // processing on this line
  45563. // append word with space to output
  45564. }
  45565. else
  45566. {
  45567. out += wordWithSpace;
  45568. currentLineWidth -= wordWidth;
  45569. }
  45570. }
  45571. // append processed line to output
  45572. output += out.replace(/[ \n]*$/gi, '') + '\n';
  45573. }
  45574. // trim the end of the string
  45575. output = output.replace(/[\s|\n]*$/gi, '');
  45576. return output;
  45577. };
  45578. /**
  45579. * Greedy wrapping algorithm that will wrap words as the line grows longer than its horizontal bounds.
  45580. *
  45581. * @method Phaser.Text#basicWordWrap
  45582. * @param {string} text - The text to perform word wrap detection against.
  45583. * @private
  45584. */
  45585. Phaser.Text.prototype.basicWordWrap = function (text) {
  45586. var result = '';
  45587. var lines = text.split('\n');
  45588. for (var i = 0; i < lines.length; i++)
  45589. {
  45590. var spaceLeft = this.style.wordWrapWidth;
  45591. var words = lines[i].split(' ');
  45592. for (var j = 0; j < words.length; j++)
  45593. {
  45594. var wordWidth = this.context.measureText(words[j]).width;
  45595. var wordWidthWithSpace = wordWidth + this.context.measureText(' ').width;
  45596. if (wordWidthWithSpace > spaceLeft)
  45597. {
  45598. // Skip printing the newline if it's the first word of the line that is greater than the word wrap width.
  45599. if (j > 0)
  45600. {
  45601. result += '\n';
  45602. }
  45603. result += words[j] + ' ';
  45604. spaceLeft = this.style.wordWrapWidth - wordWidth;
  45605. }
  45606. else
  45607. {
  45608. spaceLeft -= wordWidthWithSpace;
  45609. result += words[j] + ' ';
  45610. }
  45611. }
  45612. if (i < lines.length-1)
  45613. {
  45614. result += '\n';
  45615. }
  45616. }
  45617. return result;
  45618. };
  45619. /**
  45620. * Updates the internal `style.font` if it now differs according to generation from components.
  45621. *
  45622. * @method Phaser.Text#updateFont
  45623. * @private
  45624. * @param {object} components - Font components.
  45625. */
  45626. Phaser.Text.prototype.updateFont = function (components) {
  45627. var font = this.componentsToFont(components);
  45628. if (this.style.font !== font)
  45629. {
  45630. this.style.font = font;
  45631. this.dirty = true;
  45632. if (this.parent)
  45633. {
  45634. this.updateTransform();
  45635. }
  45636. }
  45637. };
  45638. /**
  45639. * Converting a short CSS-font string into the relevant components.
  45640. *
  45641. * @method Phaser.Text#fontToComponents
  45642. * @private
  45643. * @param {string} font - a CSS font string
  45644. */
  45645. Phaser.Text.prototype.fontToComponents = function (font) {
  45646. // The format is specified in http://www.w3.org/TR/CSS2/fonts.html#font-shorthand:
  45647. // style - normal | italic | oblique | inherit
  45648. // variant - normal | small-caps | inherit
  45649. // weight - normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | inherit
  45650. // size - xx-small | x-small | small | medium | large | x-large | xx-large,
  45651. // larger | smaller
  45652. // {number} (em | ex | ch | rem | vh | vw | vmin | vmax | px | mm | cm | in | pt | pc | %)
  45653. // font-family - rest (but identifiers or quoted with comma separation)
  45654. var m = font.match(/^\s*(?:\b(normal|italic|oblique|inherit)?\b)\s*(?:\b(normal|small-caps|inherit)?\b)\s*(?:\b(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900|inherit)?\b)\s*(?:\b(xx-small|x-small|small|medium|large|x-large|xx-large|larger|smaller|0|\d*(?:[.]\d*)?(?:%|[a-z]{2,5}))?\b)\s*(.*)\s*$/);
  45655. if (m)
  45656. {
  45657. var family = m[5].trim();
  45658. // If it looks like the value should be quoted, but isn't, then quote it.
  45659. if (!/^(?:inherit|serif|sans-serif|cursive|fantasy|monospace)$/.exec(family) && !/['",]/.exec(family))
  45660. {
  45661. family = "'" + family + "'";
  45662. }
  45663. return {
  45664. font: font,
  45665. fontStyle: m[1] || 'normal',
  45666. fontVariant: m[2] || 'normal',
  45667. fontWeight: m[3] || 'normal',
  45668. fontSize: m[4] || 'medium',
  45669. fontFamily: family
  45670. };
  45671. }
  45672. else
  45673. {
  45674. console.warn("Phaser.Text - unparsable CSS font: " + font);
  45675. return {
  45676. font: font
  45677. };
  45678. }
  45679. };
  45680. /**
  45681. * Converts individual font components (see `fontToComponents`) to a short CSS font string.
  45682. *
  45683. * @method Phaser.Text#componentsToFont
  45684. * @private
  45685. * @param {object} components - Font components.
  45686. */
  45687. Phaser.Text.prototype.componentsToFont = function (components) {
  45688. var parts = [];
  45689. var v;
  45690. v = components.fontStyle;
  45691. if (v && v !== 'normal') { parts.push(v); }
  45692. v = components.fontVariant;
  45693. if (v && v !== 'normal') { parts.push(v); }
  45694. v = components.fontWeight;
  45695. if (v && v !== 'normal') { parts.push(v); }
  45696. v = components.fontSize;
  45697. if (v && v !== 'medium') { parts.push(v); }
  45698. v = components.fontFamily;
  45699. if (v) { parts.push(v); }
  45700. if (!parts.length)
  45701. {
  45702. // Fallback to whatever value the 'font' was
  45703. parts.push(components.font);
  45704. }
  45705. return parts.join(" ");
  45706. };
  45707. /**
  45708. * The text to be displayed by this Text object.
  45709. * Use a \n to insert a carriage return and split the text.
  45710. * The text will be rendered with any style currently set.
  45711. *
  45712. * @method Phaser.Text#setText
  45713. * @param {string} [text] - The text to be displayed. Set to an empty string to clear text that is already present.
  45714. * @return {Phaser.Text} This Text instance.
  45715. */
  45716. Phaser.Text.prototype.setText = function (text) {
  45717. this.text = text.toString() || '';
  45718. this.dirty = true;
  45719. return this;
  45720. };
  45721. /**
  45722. * Converts the given array into a tab delimited string and then updates this Text object.
  45723. * This is mostly used when you want to display external data using tab stops.
  45724. *
  45725. * The array can be either single or multi dimensional depending on the result you need:
  45726. *
  45727. * `[ 'a', 'b', 'c' ]` would convert in to `"a\tb\tc"`.
  45728. *
  45729. * Where as:
  45730. *
  45731. * `[
  45732. * [ 'a', 'b', 'c' ],
  45733. * [ 'd', 'e', 'f']
  45734. * ]`
  45735. *
  45736. * would convert in to: `"a\tb\tc\nd\te\tf"`
  45737. *
  45738. * @method Phaser.Text#parseList
  45739. * @param {array} list - The array of data to convert into a string.
  45740. * @return {Phaser.Text} This Text instance.
  45741. */
  45742. Phaser.Text.prototype.parseList = function (list) {
  45743. if (!Array.isArray(list))
  45744. {
  45745. return this;
  45746. }
  45747. else
  45748. {
  45749. var s = "";
  45750. for (var i = 0; i < list.length; i++)
  45751. {
  45752. if (Array.isArray(list[i]))
  45753. {
  45754. s += list[i].join("\t");
  45755. if (i < list.length - 1)
  45756. {
  45757. s += "\n";
  45758. }
  45759. }
  45760. else
  45761. {
  45762. s += list[i];
  45763. if (i < list.length - 1)
  45764. {
  45765. s += "\t";
  45766. }
  45767. }
  45768. }
  45769. }
  45770. this.text = s;
  45771. this.dirty = true;
  45772. return this;
  45773. };
  45774. /**
  45775. * The Text Bounds is a rectangular region that you control the dimensions of into which the Text object itself is positioned,
  45776. * regardless of the number of lines in the text, the font size or any other attribute.
  45777. *
  45778. * Alignment is controlled via the properties `boundsAlignH` and `boundsAlignV` within the Text.style object, or can be directly
  45779. * set through the setters `Text.boundsAlignH` and `Text.boundsAlignV`. Bounds alignment is independent of text alignment.
  45780. *
  45781. * For example: If your game is 800x600 in size and you set the text bounds to be 0,0,800,600 then by setting boundsAlignH to
  45782. * 'center' and boundsAlignV to 'bottom' the text will render in the center and at the bottom of your game window, regardless of
  45783. * how many lines of text there may be. Even if you adjust the text content or change the style it will remain at the bottom center
  45784. * of the text bounds.
  45785. *
  45786. * This is especially powerful when you need to align text against specific coordinates in your game, but the actual text dimensions
  45787. * may vary based on font (say for multi-lingual games).
  45788. *
  45789. * If `Text.wordWrapWidth` is greater than the width of the text bounds it is clamped to match the bounds width.
  45790. *
  45791. * Call this method with no arguments given to reset an existing textBounds.
  45792. *
  45793. * It works by calculating the final position based on the Text.canvas size, which is modified as the text is updated. Some fonts
  45794. * have additional padding around them which you can mitigate by tweaking the Text.padding property. It then adjusts the `pivot`
  45795. * property based on the given bounds and canvas size. This means if you need to set the pivot property directly in your game then
  45796. * you either cannot use `setTextBounds` or you must place the Text object inside another DisplayObject on which you set the pivot.
  45797. *
  45798. * @method Phaser.Text#setTextBounds
  45799. * @param {number} [x] - The x coordinate of the Text Bounds region.
  45800. * @param {number} [y] - The y coordinate of the Text Bounds region.
  45801. * @param {number} [width] - The width of the Text Bounds region.
  45802. * @param {number} [height] - The height of the Text Bounds region.
  45803. * @return {Phaser.Text} This Text instance.
  45804. */
  45805. Phaser.Text.prototype.setTextBounds = function (x, y, width, height) {
  45806. if (x === undefined)
  45807. {
  45808. this.textBounds = null;
  45809. }
  45810. else
  45811. {
  45812. if (!this.textBounds)
  45813. {
  45814. this.textBounds = new Phaser.Rectangle(x, y, width, height);
  45815. }
  45816. else
  45817. {
  45818. this.textBounds.setTo(x, y, width, height);
  45819. }
  45820. if (this.style.wordWrapWidth > width)
  45821. {
  45822. this.style.wordWrapWidth = width;
  45823. }
  45824. }
  45825. this.updateTexture();
  45826. return this;
  45827. };
  45828. /**
  45829. * Updates the texture based on the canvas dimensions.
  45830. *
  45831. * @method Phaser.Text#updateTexture
  45832. * @private
  45833. */
  45834. Phaser.Text.prototype.updateTexture = function () {
  45835. var base = this.texture.baseTexture;
  45836. var crop = this.texture.crop;
  45837. var frame = this.texture.frame;
  45838. var w = this.canvas.width;
  45839. var h = this.canvas.height;
  45840. base.width = w;
  45841. base.height = h;
  45842. crop.width = w;
  45843. crop.height = h;
  45844. frame.width = w;
  45845. frame.height = h;
  45846. this.texture.width = w;
  45847. this.texture.height = h;
  45848. this._width = w;
  45849. this._height = h;
  45850. if (this.textBounds)
  45851. {
  45852. var x = this.textBounds.x;
  45853. var y = this.textBounds.y;
  45854. // Align the canvas based on the bounds
  45855. if (this.style.boundsAlignH === 'right')
  45856. {
  45857. x += this.textBounds.width - this.canvas.width;
  45858. }
  45859. else if (this.style.boundsAlignH === 'center')
  45860. {
  45861. x += this.textBounds.halfWidth - (this.canvas.width / 2);
  45862. }
  45863. if (this.style.boundsAlignV === 'bottom')
  45864. {
  45865. y += this.textBounds.height - this.canvas.height;
  45866. }
  45867. else if (this.style.boundsAlignV === 'middle')
  45868. {
  45869. y += this.textBounds.halfHeight - (this.canvas.height / 2);
  45870. }
  45871. this.pivot.x = -x;
  45872. this.pivot.y = -y;
  45873. }
  45874. // Can't render something with a zero sized dimension
  45875. this.renderable = (w !== 0 && h !== 0);
  45876. this.texture.requiresReTint = true;
  45877. this.texture.baseTexture.dirty();
  45878. };
  45879. /**
  45880. * Renders the object using the WebGL renderer
  45881. *
  45882. * @method Phaser.Text#_renderWebGL
  45883. * @private
  45884. * @param {RenderSession} renderSession - The Render Session to render the Text on.
  45885. */
  45886. Phaser.Text.prototype._renderWebGL = function (renderSession) {
  45887. if (this.dirty)
  45888. {
  45889. this.updateText();
  45890. this.dirty = false;
  45891. }
  45892. PIXI.Sprite.prototype._renderWebGL.call(this, renderSession);
  45893. };
  45894. /**
  45895. * Renders the object using the Canvas renderer.
  45896. *
  45897. * @method Phaser.Text#_renderCanvas
  45898. * @private
  45899. * @param {RenderSession} renderSession - The Render Session to render the Text on.
  45900. */
  45901. Phaser.Text.prototype._renderCanvas = function (renderSession) {
  45902. if (this.dirty)
  45903. {
  45904. this.updateText();
  45905. this.dirty = false;
  45906. }
  45907. PIXI.Sprite.prototype._renderCanvas.call(this, renderSession);
  45908. };
  45909. /**
  45910. * Calculates the ascent, descent and fontSize of a given font style.
  45911. *
  45912. * @method Phaser.Text#determineFontProperties
  45913. * @private
  45914. * @param {object} fontStyle
  45915. */
  45916. Phaser.Text.prototype.determineFontProperties = function (fontStyle) {
  45917. var properties = Phaser.Text.fontPropertiesCache[fontStyle];
  45918. if (!properties)
  45919. {
  45920. properties = {};
  45921. var canvas = Phaser.Text.fontPropertiesCanvas;
  45922. var context = Phaser.Text.fontPropertiesContext;
  45923. context.font = fontStyle;
  45924. var width = Math.ceil(context.measureText('|MÉq').width);
  45925. var baseline = Math.ceil(context.measureText('|MÉq').width);
  45926. var height = 2 * baseline;
  45927. baseline = baseline * 1.4 | 0;
  45928. canvas.width = width;
  45929. canvas.height = height;
  45930. context.fillStyle = '#f00';
  45931. context.fillRect(0, 0, width, height);
  45932. context.font = fontStyle;
  45933. context.textBaseline = 'alphabetic';
  45934. context.fillStyle = '#000';
  45935. context.fillText('|MÉq', 0, baseline);
  45936. if (!context.getImageData(0, 0, width, height))
  45937. {
  45938. properties.ascent = baseline;
  45939. properties.descent = baseline + 6;
  45940. properties.fontSize = properties.ascent + properties.descent;
  45941. Phaser.Text.fontPropertiesCache[fontStyle] = properties;
  45942. return properties;
  45943. }
  45944. var imagedata = context.getImageData(0, 0, width, height).data;
  45945. var pixels = imagedata.length;
  45946. var line = width * 4;
  45947. var i, j;
  45948. var idx = 0;
  45949. var stop = false;
  45950. // ascent. scan from top to bottom until we find a non red pixel
  45951. for (i = 0; i < baseline; i++)
  45952. {
  45953. for (j = 0; j < line; j += 4)
  45954. {
  45955. if (imagedata[idx + j] !== 255)
  45956. {
  45957. stop = true;
  45958. break;
  45959. }
  45960. }
  45961. if (!stop)
  45962. {
  45963. idx += line;
  45964. }
  45965. else
  45966. {
  45967. break;
  45968. }
  45969. }
  45970. properties.ascent = baseline - i;
  45971. idx = pixels - line;
  45972. stop = false;
  45973. // descent. scan from bottom to top until we find a non red pixel
  45974. for (i = height; i > baseline; i--)
  45975. {
  45976. for (j = 0; j < line; j += 4)
  45977. {
  45978. if (imagedata[idx + j] !== 255)
  45979. {
  45980. stop = true;
  45981. break;
  45982. }
  45983. }
  45984. if (!stop)
  45985. {
  45986. idx -= line;
  45987. }
  45988. else
  45989. {
  45990. break;
  45991. }
  45992. }
  45993. properties.descent = i - baseline;
  45994. //TODO might need a tweak. kind of a temp fix!
  45995. properties.descent += 6;
  45996. properties.fontSize = properties.ascent + properties.descent;
  45997. Phaser.Text.fontPropertiesCache[fontStyle] = properties;
  45998. }
  45999. return properties;
  46000. };
  46001. /**
  46002. * Returns the bounds of the Text as a rectangle.
  46003. * The bounds calculation takes the worldTransform into account.
  46004. *
  46005. * @method Phaser.Text#getBounds
  46006. * @param {Phaser.Matrix} matrix - The transformation matrix of the Text.
  46007. * @return {Phaser.Rectangle} The framing rectangle
  46008. */
  46009. Phaser.Text.prototype.getBounds = function (matrix) {
  46010. if (this.dirty)
  46011. {
  46012. this.updateText();
  46013. this.dirty = false;
  46014. }
  46015. return PIXI.Sprite.prototype.getBounds.call(this, matrix);
  46016. };
  46017. /**
  46018. * The text to be displayed by this Text object.
  46019. * Use a \n to insert a carriage return and split the text.
  46020. * The text will be rendered with any style currently set.
  46021. *
  46022. * @name Phaser.Text#text
  46023. * @property {string} text
  46024. */
  46025. Object.defineProperty(Phaser.Text.prototype, 'text', {
  46026. get: function() {
  46027. return this._text;
  46028. },
  46029. set: function(value) {
  46030. if (value !== this._text)
  46031. {
  46032. this._text = value.toString() || '';
  46033. this.dirty = true;
  46034. if (this.parent)
  46035. {
  46036. this.updateTransform();
  46037. }
  46038. }
  46039. }
  46040. });
  46041. /**
  46042. * Change the font used.
  46043. *
  46044. * This is equivalent of the `font` property specified to {@link Phaser.Text#setStyle setStyle}, except
  46045. * that unlike using `setStyle` this will not change any current font fill/color settings.
  46046. *
  46047. * The CSS font string can also be individually altered with the `font`, `fontSize`, `fontWeight`, `fontStyle`, and `fontVariant` properties.
  46048. *
  46049. * @name Phaser.Text#cssFont
  46050. * @property {string} cssFont
  46051. */
  46052. Object.defineProperty(Phaser.Text.prototype, 'cssFont', {
  46053. get: function() {
  46054. return this.componentsToFont(this._fontComponents);
  46055. },
  46056. set: function (value)
  46057. {
  46058. value = value || 'bold 20pt Arial';
  46059. this._fontComponents = this.fontToComponents(value);
  46060. this.updateFont(this._fontComponents);
  46061. }
  46062. });
  46063. /**
  46064. * Change the font family that the text will be rendered in, such as 'Arial'.
  46065. *
  46066. * Multiple CSS font families and generic fallbacks can be specified as long as
  46067. * {@link http://www.w3.org/TR/CSS2/fonts.html#propdef-font-family CSS font-family rules} are followed.
  46068. *
  46069. * To change the entire font string use {@link Phaser.Text#cssFont cssFont} instead: eg. `text.cssFont = 'bold 20pt Arial'`.
  46070. *
  46071. * @name Phaser.Text#font
  46072. * @property {string} font
  46073. */
  46074. Object.defineProperty(Phaser.Text.prototype, 'font', {
  46075. get: function() {
  46076. return this._fontComponents.fontFamily;
  46077. },
  46078. set: function(value) {
  46079. value = value || 'Arial';
  46080. value = value.trim();
  46081. // If it looks like the value should be quoted, but isn't, then quote it.
  46082. if (!/^(?:inherit|serif|sans-serif|cursive|fantasy|monospace)$/.exec(value) && !/['",]/.exec(value))
  46083. {
  46084. value = "'" + value + "'";
  46085. }
  46086. this._fontComponents.fontFamily = value;
  46087. this.updateFont(this._fontComponents);
  46088. }
  46089. });
  46090. /**
  46091. * The size of the font.
  46092. *
  46093. * If the font size is specified in pixels (eg. `32` or `'32px`') then a number (ie. `32`) representing
  46094. * the font size in pixels is returned; otherwise the value with CSS unit is returned as a string (eg. `'12pt'`).
  46095. *
  46096. * @name Phaser.Text#fontSize
  46097. * @property {number|string} fontSize
  46098. */
  46099. Object.defineProperty(Phaser.Text.prototype, 'fontSize', {
  46100. get: function() {
  46101. var size = this._fontComponents.fontSize;
  46102. if (size && /(?:^0$|px$)/.exec(size))
  46103. {
  46104. return parseInt(size, 10);
  46105. }
  46106. else
  46107. {
  46108. return size;
  46109. }
  46110. },
  46111. set: function(value) {
  46112. value = value || '0';
  46113. if (typeof value === 'number')
  46114. {
  46115. value = value + 'px';
  46116. }
  46117. this._fontComponents.fontSize = value;
  46118. this.updateFont(this._fontComponents);
  46119. }
  46120. });
  46121. /**
  46122. * The weight of the font: 'normal', 'bold', or {@link http://www.w3.org/TR/CSS2/fonts.html#propdef-font-weight a valid CSS font weight}.
  46123. * @name Phaser.Text#fontWeight
  46124. * @property {string} fontWeight
  46125. */
  46126. Object.defineProperty(Phaser.Text.prototype, 'fontWeight', {
  46127. get: function() {
  46128. return this._fontComponents.fontWeight || 'normal';
  46129. },
  46130. set: function(value) {
  46131. value = value || 'normal';
  46132. this._fontComponents.fontWeight = value;
  46133. this.updateFont(this._fontComponents);
  46134. }
  46135. });
  46136. /**
  46137. * The style of the font: 'normal', 'italic', 'oblique'
  46138. * @name Phaser.Text#fontStyle
  46139. * @property {string} fontStyle
  46140. */
  46141. Object.defineProperty(Phaser.Text.prototype, 'fontStyle', {
  46142. get: function() {
  46143. return this._fontComponents.fontStyle || 'normal';
  46144. },
  46145. set: function(value) {
  46146. value = value || 'normal';
  46147. this._fontComponents.fontStyle = value;
  46148. this.updateFont(this._fontComponents);
  46149. }
  46150. });
  46151. /**
  46152. * The variant the font: 'normal', 'small-caps'
  46153. * @name Phaser.Text#fontVariant
  46154. * @property {string} fontVariant
  46155. */
  46156. Object.defineProperty(Phaser.Text.prototype, 'fontVariant', {
  46157. get: function() {
  46158. return this._fontComponents.fontVariant || 'normal';
  46159. },
  46160. set: function(value) {
  46161. value = value || 'normal';
  46162. this._fontComponents.fontVariant = value;
  46163. this.updateFont(this._fontComponents);
  46164. }
  46165. });
  46166. /**
  46167. * @name Phaser.Text#fill
  46168. * @property {object} fill - A canvas fillstyle that will be used on the text eg 'red', '#00FF00'.
  46169. */
  46170. Object.defineProperty(Phaser.Text.prototype, 'fill', {
  46171. get: function() {
  46172. return this.style.fill;
  46173. },
  46174. set: function(value) {
  46175. if (value !== this.style.fill)
  46176. {
  46177. this.style.fill = value;
  46178. this.dirty = true;
  46179. }
  46180. }
  46181. });
  46182. /**
  46183. * Controls the horizontal alignment for multiline text.
  46184. * Can be: 'left', 'center' or 'right'.
  46185. * Does not affect single lines of text. For that please see `setTextBounds`.
  46186. * @name Phaser.Text#align
  46187. * @property {string} align
  46188. */
  46189. Object.defineProperty(Phaser.Text.prototype, 'align', {
  46190. get: function() {
  46191. return this.style.align;
  46192. },
  46193. set: function(value) {
  46194. if (value !== this.style.align)
  46195. {
  46196. this.style.align = value;
  46197. this.dirty = true;
  46198. }
  46199. }
  46200. });
  46201. /**
  46202. * The resolution of the canvas the text is rendered to.
  46203. * This defaults to match the resolution of the renderer, but can be changed on a per Text object basis.
  46204. * @name Phaser.Text#resolution
  46205. * @property {integer} resolution
  46206. */
  46207. Object.defineProperty(Phaser.Text.prototype, 'resolution', {
  46208. get: function() {
  46209. return this._res;
  46210. },
  46211. set: function(value) {
  46212. if (value !== this._res)
  46213. {
  46214. this._res = value;
  46215. this.dirty = true;
  46216. }
  46217. }
  46218. });
  46219. /**
  46220. * The size (in pixels) of the tabs, for when text includes tab characters. 0 disables.
  46221. * Can be an integer or an array of varying tab sizes, one tab per element.
  46222. * For example if you set tabs to 100 then when Text encounters a tab it will jump ahead 100 pixels.
  46223. * If you set tabs to be `[100,200]` then it will set the first tab at 100px and the second at 200px.
  46224. *
  46225. * @name Phaser.Text#tabs
  46226. * @property {integer|array} tabs
  46227. */
  46228. Object.defineProperty(Phaser.Text.prototype, 'tabs', {
  46229. get: function() {
  46230. return this.style.tabs;
  46231. },
  46232. set: function(value) {
  46233. if (value !== this.style.tabs)
  46234. {
  46235. this.style.tabs = value;
  46236. this.dirty = true;
  46237. }
  46238. }
  46239. });
  46240. /**
  46241. * Horizontal alignment of the text within the `textBounds`. Can be: 'left', 'center' or 'right'.
  46242. * @name Phaser.Text#boundsAlignH
  46243. * @property {string} boundsAlignH
  46244. */
  46245. Object.defineProperty(Phaser.Text.prototype, 'boundsAlignH', {
  46246. get: function() {
  46247. return this.style.boundsAlignH;
  46248. },
  46249. set: function(value) {
  46250. if (value !== this.style.boundsAlignH)
  46251. {
  46252. this.style.boundsAlignH = value;
  46253. this.dirty = true;
  46254. }
  46255. }
  46256. });
  46257. /**
  46258. * Vertical alignment of the text within the `textBounds`. Can be: 'top', 'middle' or 'bottom'.
  46259. * @name Phaser.Text#boundsAlignV
  46260. * @property {string} boundsAlignV
  46261. */
  46262. Object.defineProperty(Phaser.Text.prototype, 'boundsAlignV', {
  46263. get: function() {
  46264. return this.style.boundsAlignV;
  46265. },
  46266. set: function(value) {
  46267. if (value !== this.style.boundsAlignV)
  46268. {
  46269. this.style.boundsAlignV = value;
  46270. this.dirty = true;
  46271. }
  46272. }
  46273. });
  46274. /**
  46275. * @name Phaser.Text#stroke
  46276. * @property {string} stroke - A canvas fillstyle that will be used on the text stroke eg 'blue', '#FCFF00'.
  46277. */
  46278. Object.defineProperty(Phaser.Text.prototype, 'stroke', {
  46279. get: function() {
  46280. return this.style.stroke;
  46281. },
  46282. set: function(value) {
  46283. if (value !== this.style.stroke)
  46284. {
  46285. this.style.stroke = value;
  46286. this.dirty = true;
  46287. }
  46288. }
  46289. });
  46290. /**
  46291. * @name Phaser.Text#strokeThickness
  46292. * @property {number} strokeThickness - A number that represents the thickness of the stroke. Default is 0 (no stroke)
  46293. */
  46294. Object.defineProperty(Phaser.Text.prototype, 'strokeThickness', {
  46295. get: function() {
  46296. return this.style.strokeThickness;
  46297. },
  46298. set: function(value) {
  46299. if (value !== this.style.strokeThickness)
  46300. {
  46301. this.style.strokeThickness = value;
  46302. this.dirty = true;
  46303. }
  46304. }
  46305. });
  46306. /**
  46307. * @name Phaser.Text#wordWrap
  46308. * @property {boolean} wordWrap - Indicates if word wrap should be used.
  46309. */
  46310. Object.defineProperty(Phaser.Text.prototype, 'wordWrap', {
  46311. get: function() {
  46312. return this.style.wordWrap;
  46313. },
  46314. set: function(value) {
  46315. if (value !== this.style.wordWrap)
  46316. {
  46317. this.style.wordWrap = value;
  46318. this.dirty = true;
  46319. }
  46320. }
  46321. });
  46322. /**
  46323. * @name Phaser.Text#wordWrapWidth
  46324. * @property {number} wordWrapWidth - The width at which text will wrap.
  46325. */
  46326. Object.defineProperty(Phaser.Text.prototype, 'wordWrapWidth', {
  46327. get: function() {
  46328. return this.style.wordWrapWidth;
  46329. },
  46330. set: function(value) {
  46331. if (value !== this.style.wordWrapWidth)
  46332. {
  46333. this.style.wordWrapWidth = value;
  46334. this.dirty = true;
  46335. }
  46336. }
  46337. });
  46338. /**
  46339. * @name Phaser.Text#lineSpacing
  46340. * @property {number} lineSpacing - Additional spacing (in pixels) between each line of text if multi-line.
  46341. */
  46342. Object.defineProperty(Phaser.Text.prototype, 'lineSpacing', {
  46343. get: function() {
  46344. return this._lineSpacing;
  46345. },
  46346. set: function(value) {
  46347. if (value !== this._lineSpacing)
  46348. {
  46349. this._lineSpacing = parseFloat(value);
  46350. this.dirty = true;
  46351. if (this.parent)
  46352. {
  46353. this.updateTransform();
  46354. }
  46355. }
  46356. }
  46357. });
  46358. /**
  46359. * @name Phaser.Text#shadowOffsetX
  46360. * @property {number} shadowOffsetX - The shadowOffsetX value in pixels. This is how far offset horizontally the shadow effect will be.
  46361. */
  46362. Object.defineProperty(Phaser.Text.prototype, 'shadowOffsetX', {
  46363. get: function() {
  46364. return this.style.shadowOffsetX;
  46365. },
  46366. set: function(value) {
  46367. if (value !== this.style.shadowOffsetX)
  46368. {
  46369. this.style.shadowOffsetX = value;
  46370. this.dirty = true;
  46371. }
  46372. }
  46373. });
  46374. /**
  46375. * @name Phaser.Text#shadowOffsetY
  46376. * @property {number} shadowOffsetY - The shadowOffsetY value in pixels. This is how far offset vertically the shadow effect will be.
  46377. */
  46378. Object.defineProperty(Phaser.Text.prototype, 'shadowOffsetY', {
  46379. get: function() {
  46380. return this.style.shadowOffsetY;
  46381. },
  46382. set: function(value) {
  46383. if (value !== this.style.shadowOffsetY)
  46384. {
  46385. this.style.shadowOffsetY = value;
  46386. this.dirty = true;
  46387. }
  46388. }
  46389. });
  46390. /**
  46391. * @name Phaser.Text#shadowColor
  46392. * @property {string} shadowColor - The color of the shadow, as given in CSS rgba format. Set the alpha component to 0 to disable the shadow.
  46393. */
  46394. Object.defineProperty(Phaser.Text.prototype, 'shadowColor', {
  46395. get: function() {
  46396. return this.style.shadowColor;
  46397. },
  46398. set: function(value) {
  46399. if (value !== this.style.shadowColor)
  46400. {
  46401. this.style.shadowColor = value;
  46402. this.dirty = true;
  46403. }
  46404. }
  46405. });
  46406. /**
  46407. * @name Phaser.Text#shadowBlur
  46408. * @property {number} shadowBlur - The shadowBlur value. Make the shadow softer by applying a Gaussian blur to it. A number from 0 (no blur) up to approx. 10 (depending on scene).
  46409. */
  46410. Object.defineProperty(Phaser.Text.prototype, 'shadowBlur', {
  46411. get: function() {
  46412. return this.style.shadowBlur;
  46413. },
  46414. set: function(value) {
  46415. if (value !== this.style.shadowBlur)
  46416. {
  46417. this.style.shadowBlur = value;
  46418. this.dirty = true;
  46419. }
  46420. }
  46421. });
  46422. /**
  46423. * @name Phaser.Text#shadowStroke
  46424. * @property {boolean} shadowStroke - Sets if the drop shadow is applied to the Text stroke.
  46425. */
  46426. Object.defineProperty(Phaser.Text.prototype, 'shadowStroke', {
  46427. get: function() {
  46428. return this.style.shadowStroke;
  46429. },
  46430. set: function(value) {
  46431. if (value !== this.style.shadowStroke)
  46432. {
  46433. this.style.shadowStroke = value;
  46434. this.dirty = true;
  46435. }
  46436. }
  46437. });
  46438. /**
  46439. * @name Phaser.Text#shadowFill
  46440. * @property {boolean} shadowFill - Sets if the drop shadow is applied to the Text fill.
  46441. */
  46442. Object.defineProperty(Phaser.Text.prototype, 'shadowFill', {
  46443. get: function() {
  46444. return this.style.shadowFill;
  46445. },
  46446. set: function(value) {
  46447. if (value !== this.style.shadowFill)
  46448. {
  46449. this.style.shadowFill = value;
  46450. this.dirty = true;
  46451. }
  46452. }
  46453. });
  46454. /**
  46455. * @name Phaser.Text#width
  46456. * @property {number} width - The width of the Text. Setting this will modify the scale to achieve the value requested.
  46457. */
  46458. Object.defineProperty(Phaser.Text.prototype, 'width', {
  46459. get: function() {
  46460. if (this.dirty)
  46461. {
  46462. this.updateText();
  46463. this.dirty = false;
  46464. }
  46465. return this.scale.x * this.texture.frame.width;
  46466. },
  46467. set: function(value) {
  46468. this.scale.x = value / this.texture.frame.width;
  46469. this._width = value;
  46470. }
  46471. });
  46472. /**
  46473. * @name Phaser.Text#height
  46474. * @property {number} height - The height of the Text. Setting this will modify the scale to achieve the value requested.
  46475. */
  46476. Object.defineProperty(Phaser.Text.prototype, 'height', {
  46477. get: function() {
  46478. if (this.dirty)
  46479. {
  46480. this.updateText();
  46481. this.dirty = false;
  46482. }
  46483. return this.scale.y * this.texture.frame.height;
  46484. },
  46485. set: function(value) {
  46486. this.scale.y = value / this.texture.frame.height;
  46487. this._height = value;
  46488. }
  46489. });
  46490. Phaser.Text.fontPropertiesCache = {};
  46491. Phaser.Text.fontPropertiesCanvas = PIXI.CanvasPool.create(Phaser.Text.fontPropertiesCanvas);
  46492. Phaser.Text.fontPropertiesContext = Phaser.Text.fontPropertiesCanvas.getContext('2d');
  46493. /**
  46494. * @author Richard Davey <rich@photonstorm.com>
  46495. * @copyright 2016 Photon Storm Ltd.
  46496. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  46497. */
  46498. /**
  46499. * BitmapText objects work by taking a texture file and an XML or JSON file that describes the font structure.
  46500. * It then generates a new Sprite object for each letter of the text, proportionally spaced out and aligned to
  46501. * match the font structure.
  46502. *
  46503. * BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability
  46504. * to use Web Fonts, however you trade this flexibility for rendering speed. You can also create visually compelling BitmapTexts by
  46505. * processing the font texture in an image editor, applying fills and any other effects required.
  46506. *
  46507. * To create multi-line text insert \r, \n or \r\n escape codes into the text string.
  46508. *
  46509. * If you are having performance issues due to the volume of sprites being rendered, and do not require the text to be constantly
  46510. * updating, you can use BitmapText.generateTexture to create a static texture from this BitmapText.
  46511. *
  46512. * To create a BitmapText data files you can use:
  46513. *
  46514. * BMFont (Windows, free): http://www.angelcode.com/products/bmfont/
  46515. * Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner
  46516. * Littera (Web-based, free): http://kvazars.com/littera/
  46517. *
  46518. * For most use cases it is recommended to use XML. If you wish to use JSON, the formatting should be equal to the result of
  46519. * converting a valid XML file through the popular X2JS library. An online tool for conversion can be found here: http://codebeautify.org/xmltojson
  46520. *
  46521. * If you were using an older version of Phaser (< 2.4) and using the DOMish parser hack, please remove this. It isn't required any longer.
  46522. *
  46523. * @class Phaser.BitmapText
  46524. * @constructor
  46525. * @extends PIXI.DisplayObjectContainer
  46526. * @extends Phaser.Component.Core
  46527. * @extends Phaser.Component.Angle
  46528. * @extends Phaser.Component.AutoCull
  46529. * @extends Phaser.Component.Bounds
  46530. * @extends Phaser.Component.Destroy
  46531. * @extends Phaser.Component.FixedToCamera
  46532. * @extends Phaser.Component.InputEnabled
  46533. * @extends Phaser.Component.InWorld
  46534. * @extends Phaser.Component.LifeSpan
  46535. * @extends Phaser.Component.PhysicsBody
  46536. * @extends Phaser.Component.Reset
  46537. * @param {Phaser.Game} game - A reference to the currently running game.
  46538. * @param {number} x - X coordinate to display the BitmapText object at.
  46539. * @param {number} y - Y coordinate to display the BitmapText object at.
  46540. * @param {string} font - The key of the BitmapText as stored in Phaser.Cache.
  46541. * @param {string} [text=''] - The text that will be rendered. This can also be set later via BitmapText.text.
  46542. * @param {number} [size=32] - The size the font will be rendered at in pixels.
  46543. * @param {string} [align='left'] - The alignment of multi-line text. Has no effect if there is only one line of text.
  46544. */
  46545. Phaser.BitmapText = function (game, x, y, font, text, size, align) {
  46546. x = x || 0;
  46547. y = y || 0;
  46548. font = font || '';
  46549. text = text || '';
  46550. size = size || 32;
  46551. align = align || 'left';
  46552. PIXI.DisplayObjectContainer.call(this);
  46553. /**
  46554. * @property {number} type - The const type of this object.
  46555. * @readonly
  46556. */
  46557. this.type = Phaser.BITMAPTEXT;
  46558. /**
  46559. * @property {number} physicsType - The const physics body type of this object.
  46560. * @readonly
  46561. */
  46562. this.physicsType = Phaser.SPRITE;
  46563. /**
  46564. * @property {number} textWidth - The width in pixels of the overall text area, taking into consideration multi-line text.
  46565. * @readOnly
  46566. */
  46567. this.textWidth = 0;
  46568. /**
  46569. * @property {number} textHeight - The height in pixels of the overall text area, taking into consideration multi-line text.
  46570. * @readOnly
  46571. */
  46572. this.textHeight = 0;
  46573. /**
  46574. * @property {Phaser.Point} anchor - The anchor value of this BitmapText.
  46575. */
  46576. this.anchor = new Phaser.Point();
  46577. /**
  46578. * @property {Phaser.Point} _prevAnchor - The previous anchor value.
  46579. * @private
  46580. */
  46581. this._prevAnchor = new Phaser.Point();
  46582. /**
  46583. * @property {array} _glyphs - Private tracker for the letter sprite pool.
  46584. * @private
  46585. */
  46586. this._glyphs = [];
  46587. /**
  46588. * @property {number} _maxWidth - Internal cache var.
  46589. * @private
  46590. */
  46591. this._maxWidth = 0;
  46592. /**
  46593. * @property {string} _text - Internal cache var.
  46594. * @private
  46595. */
  46596. this._text = text.toString() || '';
  46597. /**
  46598. * @property {string} _data - Internal cache var.
  46599. * @private
  46600. */
  46601. this._data = game.cache.getBitmapFont(font);
  46602. /**
  46603. * @property {string} _font - Internal cache var.
  46604. * @private
  46605. */
  46606. this._font = font;
  46607. /**
  46608. * @property {number} _fontSize - Internal cache var.
  46609. * @private
  46610. */
  46611. this._fontSize = size;
  46612. /**
  46613. * @property {string} _align - Internal cache var.
  46614. * @private
  46615. */
  46616. this._align = align;
  46617. /**
  46618. * @property {number} _tint - Internal cache var.
  46619. * @private
  46620. */
  46621. this._tint = 0xFFFFFF;
  46622. this.updateText();
  46623. /**
  46624. * @property {boolean} dirty - The dirty state of this object.
  46625. */
  46626. this.dirty = false;
  46627. Phaser.Component.Core.init.call(this, game, x, y, '', null);
  46628. };
  46629. Phaser.BitmapText.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
  46630. Phaser.BitmapText.prototype.constructor = Phaser.BitmapText;
  46631. Phaser.Component.Core.install.call(Phaser.BitmapText.prototype, [
  46632. 'Angle',
  46633. 'AutoCull',
  46634. 'Bounds',
  46635. 'Destroy',
  46636. 'FixedToCamera',
  46637. 'InputEnabled',
  46638. 'InWorld',
  46639. 'LifeSpan',
  46640. 'PhysicsBody',
  46641. 'Reset'
  46642. ]);
  46643. Phaser.BitmapText.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate;
  46644. Phaser.BitmapText.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate;
  46645. Phaser.BitmapText.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate;
  46646. Phaser.BitmapText.prototype.preUpdateCore = Phaser.Component.Core.preUpdate;
  46647. /**
  46648. * Automatically called by World.preUpdate.
  46649. *
  46650. * @method
  46651. * @memberof Phaser.BitmapText
  46652. * @return {boolean} True if the BitmapText was rendered, otherwise false.
  46653. */
  46654. Phaser.BitmapText.prototype.preUpdate = function () {
  46655. if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld())
  46656. {
  46657. return false;
  46658. }
  46659. return this.preUpdateCore();
  46660. };
  46661. /**
  46662. * Automatically called by World.preUpdate.
  46663. * @method Phaser.BitmapText.prototype.postUpdate
  46664. */
  46665. Phaser.BitmapText.prototype.postUpdate = function () {
  46666. Phaser.Component.PhysicsBody.postUpdate.call(this);
  46667. Phaser.Component.FixedToCamera.postUpdate.call(this);
  46668. if (this.body && this.body.type === Phaser.Physics.ARCADE)
  46669. {
  46670. if ((this.textWidth !== this.body.sourceWidth) || (this.textHeight !== this.body.sourceHeight))
  46671. {
  46672. this.body.setSize(this.textWidth, this.textHeight);
  46673. }
  46674. }
  46675. };
  46676. /**
  46677. * The text to be displayed by this BitmapText object.
  46678. *
  46679. * It's faster to use `BitmapText.text = string`, but this is kept for backwards compatibility.
  46680. *
  46681. * @method Phaser.BitmapText.prototype.setText
  46682. * @param {string} text - The text to be displayed by this BitmapText object.
  46683. */
  46684. Phaser.BitmapText.prototype.setText = function (text) {
  46685. this.text = text;
  46686. };
  46687. /**
  46688. * Given the input text this will scan the characters until either a newline is encountered,
  46689. * or the line exceeds maxWidth, taking into account kerning, character widths and scaling.
  46690. *
  46691. * @method Phaser.BitmapText.prototype.scanLine
  46692. * @private
  46693. * @param {object} data - A reference to the font object in the Phaser.Cache.
  46694. * @param {float} scale - The scale of the font in relation to the texture.
  46695. * @param {string} text - The text to parse.
  46696. * @return {object} An object containing the parsed characters, total pixel width and x offsets.
  46697. */
  46698. Phaser.BitmapText.prototype.scanLine = function (data, scale, text) {
  46699. var x = 0;
  46700. var w = 0;
  46701. var lastSpace = -1;
  46702. var prevCharCode = null;
  46703. var maxWidth = (this._maxWidth > 0) ? this._maxWidth : null;
  46704. var chars = [];
  46705. // Let's scan the text and work out if any of the lines are > maxWidth
  46706. for (var i = 0; i < text.length; i++)
  46707. {
  46708. var end = (i === text.length - 1) ? true : false;
  46709. if (/(?:\r\n|\r|\n)/.test(text.charAt(i)))
  46710. {
  46711. return { width: w, text: text.substr(0, i), end: end, chars: chars };
  46712. }
  46713. else
  46714. {
  46715. var charCode = text.charCodeAt(i);
  46716. var charData = data.chars[charCode];
  46717. var c = 0;
  46718. // If the character data isn't found in the data array
  46719. // then we replace it with a blank space
  46720. if (charData === undefined)
  46721. {
  46722. charCode = 32;
  46723. charData = data.chars[charCode];
  46724. }
  46725. // Adjust for kerning from previous character to this one
  46726. var kerning = (prevCharCode && charData.kerning[prevCharCode]) ? charData.kerning[prevCharCode] : 0;
  46727. // Record the last space in the string
  46728. lastSpace = /(\s)/.test(text.charAt(i)) ? i : lastSpace;
  46729. // What will the line width be if we add this character to it?
  46730. c = (kerning + charData.texture.width + charData.xOffset) * scale;
  46731. // Do we need to line-wrap?
  46732. if (maxWidth && ((w + c) >= maxWidth) && lastSpace > -1)
  46733. {
  46734. // The last space was at "lastSpace" which was "i - lastSpace" characters ago
  46735. return { width: w, text: text.substr(0, i - (i - lastSpace)), end: end, chars: chars };
  46736. }
  46737. else
  46738. {
  46739. w += (charData.xAdvance + kerning) * scale;
  46740. chars.push(x + (charData.xOffset + kerning) * scale);
  46741. x += (charData.xAdvance + kerning) * scale;
  46742. prevCharCode = charCode;
  46743. }
  46744. }
  46745. }
  46746. return { width: w, text: text, end: end, chars: chars };
  46747. };
  46748. /**
  46749. * Given a text string this will scan each character in the string to ensure it exists
  46750. * in the BitmapText font data. If it doesn't the character is removed, or replaced with the `replace` argument.
  46751. *
  46752. * If no font data has been loaded at all this returns an empty string, as nothing can be rendered.
  46753. *
  46754. * @method Phaser.BitmapText.prototype.cleanText
  46755. * @param {string} text - The text to parse.
  46756. * @param {string} [replace=''] - The replacement string for any missing characters.
  46757. * @return {string} The cleaned text string.
  46758. */
  46759. Phaser.BitmapText.prototype.cleanText = function (text, replace) {
  46760. if (replace === undefined)
  46761. {
  46762. replace = '';
  46763. }
  46764. var data = this._data.font;
  46765. if (!data)
  46766. {
  46767. return '';
  46768. }
  46769. var re = /\r\n|\n\r|\n|\r/g;
  46770. var lines = text.replace(re, "\n").split("\n");
  46771. for (var i = 0; i < lines.length; i++)
  46772. {
  46773. var output = '';
  46774. var line = lines[i];
  46775. for (var c = 0; c < line.length; c++)
  46776. {
  46777. if (data.chars[line.charCodeAt(c)])
  46778. {
  46779. output = output.concat(line[c]);
  46780. }
  46781. else
  46782. {
  46783. output = output.concat(replace);
  46784. }
  46785. }
  46786. lines[i] = output;
  46787. }
  46788. return lines.join("\n");
  46789. };
  46790. /**
  46791. * Renders text and updates it when needed.
  46792. *
  46793. * @method Phaser.BitmapText.prototype.updateText
  46794. * @private
  46795. */
  46796. Phaser.BitmapText.prototype.updateText = function () {
  46797. var data = this._data.font;
  46798. if (!data)
  46799. {
  46800. return;
  46801. }
  46802. var text = this.text;
  46803. var scale = this._fontSize / data.size;
  46804. var lines = [];
  46805. var y = 0;
  46806. this.textWidth = 0;
  46807. do
  46808. {
  46809. var line = this.scanLine(data, scale, text);
  46810. line.y = y;
  46811. lines.push(line);
  46812. if (line.width > this.textWidth)
  46813. {
  46814. this.textWidth = line.width;
  46815. }
  46816. y += (data.lineHeight * scale);
  46817. text = text.substr(line.text.length + 1);
  46818. } while (line.end === false);
  46819. this.textHeight = y;
  46820. var t = 0;
  46821. var align = 0;
  46822. var ax = this.textWidth * this.anchor.x;
  46823. var ay = this.textHeight * this.anchor.y;
  46824. for (var i = 0; i < lines.length; i++)
  46825. {
  46826. var line = lines[i];
  46827. if (this._align === 'right')
  46828. {
  46829. align = this.textWidth - line.width;
  46830. }
  46831. else if (this._align === 'center')
  46832. {
  46833. align = (this.textWidth - line.width) / 2;
  46834. }
  46835. for (var c = 0; c < line.text.length; c++)
  46836. {
  46837. var charCode = line.text.charCodeAt(c);
  46838. var charData = data.chars[charCode];
  46839. if (charData === undefined)
  46840. {
  46841. charCode = 32;
  46842. charData = data.chars[charCode];
  46843. }
  46844. var g = this._glyphs[t];
  46845. if (g)
  46846. {
  46847. // Sprite already exists in the glyphs pool, so we'll reuse it for this letter
  46848. g.texture = charData.texture;
  46849. }
  46850. else
  46851. {
  46852. // We need a new sprite as the pool is empty or exhausted
  46853. g = new PIXI.Sprite(charData.texture);
  46854. g.name = line.text[c];
  46855. this._glyphs.push(g);
  46856. }
  46857. g.position.x = (line.chars[c] + align) - ax;
  46858. g.position.y = (line.y + (charData.yOffset * scale)) - ay;
  46859. g.scale.set(scale);
  46860. g.tint = this.tint;
  46861. g.texture.requiresReTint = true;
  46862. if (!g.parent)
  46863. {
  46864. this.addChild(g);
  46865. }
  46866. t++;
  46867. }
  46868. }
  46869. // Remove unnecessary children
  46870. // This moves them from the display list (children array) but retains them in the _glyphs pool
  46871. for (i = t; i < this._glyphs.length; i++)
  46872. {
  46873. this.removeChild(this._glyphs[i]);
  46874. }
  46875. };
  46876. /**
  46877. * If a BitmapText changes from having a large number of characters to having very few characters it will cause lots of
  46878. * Sprites to be retained in the BitmapText._glyphs array. Although they are not attached to the display list they
  46879. * still take up memory while sat in the glyphs pool waiting to be re-used in the future.
  46880. *
  46881. * If you know that the BitmapText will not grow any larger then you can purge out the excess glyphs from the pool
  46882. * by calling this method.
  46883. *
  46884. * Calling this doesn't prevent you from increasing the length of the text again in the future.
  46885. *
  46886. * @method Phaser.BitmapText.prototype.purgeGlyphs
  46887. * @return {integer} The amount of glyphs removed from the pool.
  46888. */
  46889. Phaser.BitmapText.prototype.purgeGlyphs = function () {
  46890. var len = this._glyphs.length;
  46891. var kept = [];
  46892. for (var i = 0; i < this._glyphs.length; i++)
  46893. {
  46894. if (this._glyphs[i].parent !== this)
  46895. {
  46896. this._glyphs[i].destroy();
  46897. }
  46898. else
  46899. {
  46900. kept.push(this._glyphs[i]);
  46901. }
  46902. }
  46903. this._glyphs = [];
  46904. this._glyphs = kept;
  46905. this.updateText();
  46906. return len - kept.length;
  46907. };
  46908. /**
  46909. * Updates the transform of this object.
  46910. *
  46911. * @method Phaser.BitmapText.prototype.updateTransform
  46912. * @private
  46913. */
  46914. Phaser.BitmapText.prototype.updateTransform = function () {
  46915. if (this.dirty || !this.anchor.equals(this._prevAnchor))
  46916. {
  46917. this.updateText();
  46918. this.dirty = false;
  46919. this._prevAnchor.copyFrom(this.anchor);
  46920. }
  46921. PIXI.DisplayObjectContainer.prototype.updateTransform.call(this);
  46922. };
  46923. /**
  46924. * @name Phaser.BitmapText#align
  46925. * @property {string} align - Alignment for multi-line text ('left', 'center' or 'right'), does not affect single lines of text.
  46926. */
  46927. Object.defineProperty(Phaser.BitmapText.prototype, 'align', {
  46928. get: function() {
  46929. return this._align;
  46930. },
  46931. set: function(value) {
  46932. if (value !== this._align && (value === 'left' || value === 'center' || value === 'right'))
  46933. {
  46934. this._align = value;
  46935. this.updateText();
  46936. }
  46937. }
  46938. });
  46939. /**
  46940. * @name Phaser.BitmapText#tint
  46941. * @property {number} tint - The tint applied to the BitmapText. This is a hex value. Set to white to disable (0xFFFFFF)
  46942. */
  46943. Object.defineProperty(Phaser.BitmapText.prototype, 'tint', {
  46944. get: function() {
  46945. return this._tint;
  46946. },
  46947. set: function(value) {
  46948. if (value !== this._tint)
  46949. {
  46950. this._tint = value;
  46951. this.updateText();
  46952. }
  46953. }
  46954. });
  46955. /**
  46956. * @name Phaser.BitmapText#font
  46957. * @property {string} font - The font the text will be rendered in, i.e. 'Arial'. Must be loaded in the browser before use.
  46958. */
  46959. Object.defineProperty(Phaser.BitmapText.prototype, 'font', {
  46960. get: function() {
  46961. return this._font;
  46962. },
  46963. set: function(value) {
  46964. if (value !== this._font)
  46965. {
  46966. this._font = value.trim();
  46967. this._data = this.game.cache.getBitmapFont(this._font);
  46968. this.updateText();
  46969. }
  46970. }
  46971. });
  46972. /**
  46973. * @name Phaser.BitmapText#fontSize
  46974. * @property {number} fontSize - The size of the font in pixels.
  46975. */
  46976. Object.defineProperty(Phaser.BitmapText.prototype, 'fontSize', {
  46977. get: function() {
  46978. return this._fontSize;
  46979. },
  46980. set: function(value) {
  46981. value = parseInt(value, 10);
  46982. if (value !== this._fontSize && value > 0)
  46983. {
  46984. this._fontSize = value;
  46985. this.updateText();
  46986. }
  46987. }
  46988. });
  46989. /**
  46990. * @name Phaser.BitmapText#text
  46991. * @property {string} text - The text to be displayed by this BitmapText object.
  46992. */
  46993. Object.defineProperty(Phaser.BitmapText.prototype, 'text', {
  46994. get: function() {
  46995. return this._text;
  46996. },
  46997. set: function(value) {
  46998. if (value !== this._text)
  46999. {
  47000. this._text = value.toString() || '';
  47001. this.updateText();
  47002. }
  47003. }
  47004. });
  47005. /**
  47006. * The maximum display width of this BitmapText in pixels.
  47007. *
  47008. * If BitmapText.text is longer than maxWidth then the lines will be automatically wrapped
  47009. * based on the last whitespace character found in the line.
  47010. *
  47011. * If no whitespace was found then no wrapping will take place and consequently the maxWidth value will not be honored.
  47012. *
  47013. * Disable maxWidth by setting the value to 0.
  47014. *
  47015. * @name Phaser.BitmapText#maxWidth
  47016. * @property {number} maxWidth - The maximum width of this BitmapText in pixels.
  47017. */
  47018. Object.defineProperty(Phaser.BitmapText.prototype, 'maxWidth', {
  47019. get: function() {
  47020. return this._maxWidth;
  47021. },
  47022. set: function(value) {
  47023. if (value !== this._maxWidth)
  47024. {
  47025. this._maxWidth = value;
  47026. this.updateText();
  47027. }
  47028. }
  47029. });
  47030. /**
  47031. * Enable or disable texture smoothing for this BitmapText.
  47032. *
  47033. * The smoothing is applied to the BaseTexture of this font, which all letters of the text reference.
  47034. *
  47035. * Smoothing is enabled by default.
  47036. *
  47037. * @name Phaser.BitmapText#smoothed
  47038. * @property {boolean} smoothed
  47039. */
  47040. Object.defineProperty(Phaser.BitmapText.prototype, 'smoothed', {
  47041. get: function() {
  47042. return !this._data.base.scaleMode;
  47043. },
  47044. set: function(value) {
  47045. if (value)
  47046. {
  47047. this._data.base.scaleMode = 0;
  47048. }
  47049. else
  47050. {
  47051. this._data.base.scaleMode = 1;
  47052. }
  47053. }
  47054. });
  47055. /**
  47056. * @author Richard Davey <rich@photonstorm.com>
  47057. * @copyright 2016 Photon Storm Ltd.
  47058. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  47059. */
  47060. /**
  47061. * A Retro Font is similar to a BitmapFont, in that it uses a texture to render the text. However unlike a BitmapFont every character in a RetroFont
  47062. * is the same size. This makes it similar to a sprite sheet. You typically find font sheets like this from old 8/16-bit games and demos.
  47063. *
  47064. * @class Phaser.RetroFont
  47065. * @extends Phaser.RenderTexture
  47066. * @constructor
  47067. * @param {Phaser.Game} game - Current game instance.
  47068. * @param {string} key - The font set graphic set as stored in the Game.Cache.
  47069. * @param {number} characterWidth - The width of each character in the font set.
  47070. * @param {number} characterHeight - The height of each character in the font set.
  47071. * @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements.
  47072. * @param {number} [charsPerRow] - The number of characters per row in the font set. If not given charsPerRow will be the image width / characterWidth.
  47073. * @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here.
  47074. * @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here.
  47075. * @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here.
  47076. * @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here.
  47077. */
  47078. Phaser.RetroFont = function (game, key, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset) {
  47079. if (!game.cache.checkImageKey(key))
  47080. {
  47081. return false;
  47082. }
  47083. if (charsPerRow === undefined || charsPerRow === null)
  47084. {
  47085. charsPerRow = game.cache.getImage(key).width / characterWidth;
  47086. }
  47087. /**
  47088. * @property {number} characterWidth - The width of each character in the font set.
  47089. */
  47090. this.characterWidth = characterWidth;
  47091. /**
  47092. * @property {number} characterHeight - The height of each character in the font set.
  47093. */
  47094. this.characterHeight = characterHeight;
  47095. /**
  47096. * @property {number} characterSpacingX - If the characters in the font set have horizontal spacing between them set the required amount here.
  47097. */
  47098. this.characterSpacingX = xSpacing || 0;
  47099. /**
  47100. * @property {number} characterSpacingY - If the characters in the font set have vertical spacing between them set the required amount here.
  47101. */
  47102. this.characterSpacingY = ySpacing || 0;
  47103. /**
  47104. * @property {number} characterPerRow - The number of characters per row in the font set.
  47105. */
  47106. this.characterPerRow = charsPerRow;
  47107. /**
  47108. * @property {number} offsetX - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here.
  47109. * @readonly
  47110. */
  47111. this.offsetX = xOffset || 0;
  47112. /**
  47113. * @property {number} offsetY - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here.
  47114. * @readonly
  47115. */
  47116. this.offsetY = yOffset || 0;
  47117. /**
  47118. * @property {string} align - Alignment of the text when multiLine = true or a fixedWidth is set. Set to RetroFont.ALIGN_LEFT (default), RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER.
  47119. */
  47120. this.align = "left";
  47121. /**
  47122. * @property {boolean} multiLine - If set to true all carriage-returns in text will form new lines (see align). If false the font will only contain one single line of text (the default)
  47123. * @default
  47124. */
  47125. this.multiLine = false;
  47126. /**
  47127. * @property {boolean} autoUpperCase - Automatically convert any text to upper case. Lots of old bitmap fonts only contain upper-case characters, so the default is true.
  47128. * @default
  47129. */
  47130. this.autoUpperCase = true;
  47131. /**
  47132. * @property {number} customSpacingX - Adds horizontal spacing between each character of the font, in pixels.
  47133. * @default
  47134. */
  47135. this.customSpacingX = 0;
  47136. /**
  47137. * @property {number} customSpacingY - Adds vertical spacing between each line of multi-line text, set in pixels.
  47138. * @default
  47139. */
  47140. this.customSpacingY = 0;
  47141. /**
  47142. * If you need this RetroFont image to have a fixed width you can set the width in this value.
  47143. * If text is wider than the width specified it will be cropped off.
  47144. * @property {number} fixedWidth
  47145. */
  47146. this.fixedWidth = 0;
  47147. /**
  47148. * @property {Image} fontSet - A reference to the image stored in the Game.Cache that contains the font.
  47149. */
  47150. this.fontSet = game.cache.getImage(key);
  47151. /**
  47152. * @property {string} _text - The text of the font image.
  47153. * @private
  47154. */
  47155. this._text = '';
  47156. /**
  47157. * @property {array} grabData - An array of rects for faster character pasting.
  47158. * @private
  47159. */
  47160. this.grabData = [];
  47161. /**
  47162. * @property {Phaser.FrameData} frameData - The FrameData representing this Retro Font.
  47163. */
  47164. this.frameData = new Phaser.FrameData();
  47165. // Now generate our rects for faster copying later on
  47166. var currentX = this.offsetX;
  47167. var currentY = this.offsetY;
  47168. var r = 0;
  47169. for (var c = 0; c < chars.length; c++)
  47170. {
  47171. var frame = this.frameData.addFrame(new Phaser.Frame(c, currentX, currentY, this.characterWidth, this.characterHeight));
  47172. this.grabData[chars.charCodeAt(c)] = frame.index;
  47173. r++;
  47174. if (r === this.characterPerRow)
  47175. {
  47176. r = 0;
  47177. currentX = this.offsetX;
  47178. currentY += this.characterHeight + this.characterSpacingY;
  47179. }
  47180. else
  47181. {
  47182. currentX += this.characterWidth + this.characterSpacingX;
  47183. }
  47184. }
  47185. game.cache.updateFrameData(key, this.frameData);
  47186. /**
  47187. * @property {Phaser.Image} stamp - The image that is stamped to the RenderTexture for each character in the font.
  47188. * @readonly
  47189. */
  47190. this.stamp = new Phaser.Image(game, 0, 0, key, 0);
  47191. Phaser.RenderTexture.call(this, game, 100, 100, '', Phaser.scaleModes.NEAREST);
  47192. /**
  47193. * @property {number} type - Base Phaser object type.
  47194. */
  47195. this.type = Phaser.RETROFONT;
  47196. };
  47197. Phaser.RetroFont.prototype = Object.create(Phaser.RenderTexture.prototype);
  47198. Phaser.RetroFont.prototype.constructor = Phaser.RetroFont;
  47199. /**
  47200. * Align each line of multi-line text to the left.
  47201. * @constant
  47202. * @type {string}
  47203. */
  47204. Phaser.RetroFont.ALIGN_LEFT = "left";
  47205. /**
  47206. * Align each line of multi-line text to the right.
  47207. * @constant
  47208. * @type {string}
  47209. */
  47210. Phaser.RetroFont.ALIGN_RIGHT = "right";
  47211. /**
  47212. * Align each line of multi-line text in the center.
  47213. * @constant
  47214. * @type {string}
  47215. */
  47216. Phaser.RetroFont.ALIGN_CENTER = "center";
  47217. /**
  47218. * Text Set 1 = !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
  47219. * @constant
  47220. * @type {string}
  47221. */
  47222. Phaser.RetroFont.TEXT_SET1 = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
  47223. /**
  47224. * Text Set 2 = !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ
  47225. * @constant
  47226. * @type {string}
  47227. */
  47228. Phaser.RetroFont.TEXT_SET2 = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  47229. /**
  47230. * Text Set 3 = ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
  47231. * @constant
  47232. * @type {string}
  47233. */
  47234. Phaser.RetroFont.TEXT_SET3 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ";
  47235. /**
  47236. * Text Set 4 = ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789
  47237. * @constant
  47238. * @type {string}
  47239. */
  47240. Phaser.RetroFont.TEXT_SET4 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789";
  47241. /**
  47242. * Text Set 5 = ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789
  47243. * @constant
  47244. * @type {string}
  47245. */
  47246. Phaser.RetroFont.TEXT_SET5 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789";
  47247. /**
  47248. * Text Set 6 = ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789"(),-.'
  47249. * @constant
  47250. * @type {string}
  47251. */
  47252. Phaser.RetroFont.TEXT_SET6 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789\"(),-.' ";
  47253. /**
  47254. * Text Set 7 = AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW")28FLRX-'39
  47255. * @constant
  47256. * @type {string}
  47257. */
  47258. Phaser.RetroFont.TEXT_SET7 = "AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW\")28FLRX-'39";
  47259. /**
  47260. * Text Set 8 = 0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ
  47261. * @constant
  47262. * @type {string}
  47263. */
  47264. Phaser.RetroFont.TEXT_SET8 = "0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  47265. /**
  47266. * Text Set 9 = ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'"?!
  47267. * @constant
  47268. * @type {string}
  47269. */
  47270. Phaser.RetroFont.TEXT_SET9 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'\"?!";
  47271. /**
  47272. * Text Set 10 = ABCDEFGHIJKLMNOPQRSTUVWXYZ
  47273. * @constant
  47274. * @type {string}
  47275. */
  47276. Phaser.RetroFont.TEXT_SET10 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  47277. /**
  47278. * Text Set 11 = ABCDEFGHIJKLMNOPQRSTUVWXYZ.,"-+!?()':;0123456789
  47279. * @constant
  47280. * @type {string}
  47281. */
  47282. Phaser.RetroFont.TEXT_SET11 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,\"-+!?()':;0123456789";
  47283. /**
  47284. * If you need this RetroFont to have a fixed width and custom alignment you can set the width here.
  47285. * If text is wider than the width specified it will be cropped off.
  47286. *
  47287. * @method Phaser.RetroFont#setFixedWidth
  47288. * @memberof Phaser.RetroFont
  47289. * @param {number} width - Width in pixels of this RetroFont. Set to zero to disable and re-enable automatic resizing.
  47290. * @param {string} [lineAlignment='left'] - Align the text within this width. Set to RetroFont.ALIGN_LEFT (default), RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER.
  47291. */
  47292. Phaser.RetroFont.prototype.setFixedWidth = function (width, lineAlignment) {
  47293. if (lineAlignment === undefined) { lineAlignment = 'left'; }
  47294. this.fixedWidth = width;
  47295. this.align = lineAlignment;
  47296. };
  47297. /**
  47298. * A helper function that quickly sets lots of variables at once, and then updates the text.
  47299. *
  47300. * @method Phaser.RetroFont#setText
  47301. * @memberof Phaser.RetroFont
  47302. * @param {string} content - The text of this sprite.
  47303. * @param {boolean} [multiLine=false] - Set to true if you want to support carriage-returns in the text and create a multi-line sprite instead of a single line.
  47304. * @param {number} [characterSpacing=0] - To add horizontal spacing between each character specify the amount in pixels.
  47305. * @param {number} [lineSpacing=0] - To add vertical spacing between each line of text, set the amount in pixels.
  47306. * @param {string} [lineAlignment='left'] - Align each line of multi-line text. Set to RetroFont.ALIGN_LEFT, RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER.
  47307. * @param {boolean} [allowLowerCase=false] - Lots of bitmap font sets only include upper-case characters, if yours needs to support lower case then set this to true.
  47308. */
  47309. Phaser.RetroFont.prototype.setText = function (content, multiLine, characterSpacing, lineSpacing, lineAlignment, allowLowerCase) {
  47310. this.multiLine = multiLine || false;
  47311. this.customSpacingX = characterSpacing || 0;
  47312. this.customSpacingY = lineSpacing || 0;
  47313. this.align = lineAlignment || 'left';
  47314. if (allowLowerCase)
  47315. {
  47316. this.autoUpperCase = false;
  47317. }
  47318. else
  47319. {
  47320. this.autoUpperCase = true;
  47321. }
  47322. if (content.length > 0)
  47323. {
  47324. this.text = content;
  47325. }
  47326. };
  47327. /**
  47328. * Updates the texture with the new text.
  47329. *
  47330. * @method Phaser.RetroFont#buildRetroFontText
  47331. * @memberof Phaser.RetroFont
  47332. */
  47333. Phaser.RetroFont.prototype.buildRetroFontText = function () {
  47334. var cx = 0;
  47335. var cy = 0;
  47336. // Clears the textureBuffer
  47337. this.clear();
  47338. if (this.multiLine)
  47339. {
  47340. var lines = this._text.split("\n");
  47341. if (this.fixedWidth > 0)
  47342. {
  47343. this.resize(this.fixedWidth, (lines.length * (this.characterHeight + this.customSpacingY)) - this.customSpacingY, true);
  47344. }
  47345. else
  47346. {
  47347. this.resize(this.getLongestLine() * (this.characterWidth + this.customSpacingX), (lines.length * (this.characterHeight + this.customSpacingY)) - this.customSpacingY, true);
  47348. }
  47349. // Loop through each line of text
  47350. for (var i = 0; i < lines.length; i++)
  47351. {
  47352. // Phaser.RetroFont.ALIGN_LEFT
  47353. cx = 0;
  47354. // This line of text is held in lines[i] - need to work out the alignment
  47355. if (this.align === Phaser.RetroFont.ALIGN_RIGHT)
  47356. {
  47357. cx = this.width - (lines[i].length * (this.characterWidth + this.customSpacingX));
  47358. }
  47359. else if (this.align === Phaser.RetroFont.ALIGN_CENTER)
  47360. {
  47361. cx = (this.width / 2) - ((lines[i].length * (this.characterWidth + this.customSpacingX)) / 2);
  47362. cx += this.customSpacingX / 2;
  47363. }
  47364. // Sanity checks
  47365. if (cx < 0)
  47366. {
  47367. cx = 0;
  47368. }
  47369. this.pasteLine(lines[i], cx, cy, this.customSpacingX);
  47370. cy += this.characterHeight + this.customSpacingY;
  47371. }
  47372. }
  47373. else
  47374. {
  47375. if (this.fixedWidth > 0)
  47376. {
  47377. this.resize(this.fixedWidth, this.characterHeight, true);
  47378. }
  47379. else
  47380. {
  47381. this.resize(this._text.length * (this.characterWidth + this.customSpacingX), this.characterHeight, true);
  47382. }
  47383. // Phaser.RetroFont.ALIGN_LEFT
  47384. cx = 0;
  47385. if (this.align === Phaser.RetroFont.ALIGN_RIGHT)
  47386. {
  47387. cx = this.width - (this._text.length * (this.characterWidth + this.customSpacingX));
  47388. }
  47389. else if (this.align === Phaser.RetroFont.ALIGN_CENTER)
  47390. {
  47391. cx = (this.width / 2) - ((this._text.length * (this.characterWidth + this.customSpacingX)) / 2);
  47392. cx += this.customSpacingX / 2;
  47393. }
  47394. // Sanity checks
  47395. if (cx < 0)
  47396. {
  47397. cx = 0;
  47398. }
  47399. this.pasteLine(this._text, cx, 0, this.customSpacingX);
  47400. }
  47401. this.requiresReTint = true;
  47402. };
  47403. /**
  47404. * Internal function that takes a single line of text (2nd parameter) and pastes it into the BitmapData at the given coordinates.
  47405. * Used by getLine and getMultiLine
  47406. *
  47407. * @method Phaser.RetroFont#pasteLine
  47408. * @memberof Phaser.RetroFont
  47409. * @param {string} line - The single line of text to paste.
  47410. * @param {number} x - The x coordinate.
  47411. * @param {number} y - The y coordinate.
  47412. * @param {number} customSpacingX - Custom X spacing.
  47413. */
  47414. Phaser.RetroFont.prototype.pasteLine = function (line, x, y, customSpacingX) {
  47415. for (var c = 0; c < line.length; c++)
  47416. {
  47417. // If it's a space then there is no point copying, so leave a blank space
  47418. if (line.charAt(c) === " ")
  47419. {
  47420. x += this.characterWidth + customSpacingX;
  47421. }
  47422. else
  47423. {
  47424. // If the character doesn't exist in the font then we don't want a blank space, we just want to skip it
  47425. if (this.grabData[line.charCodeAt(c)] >= 0)
  47426. {
  47427. this.stamp.frame = this.grabData[line.charCodeAt(c)];
  47428. this.renderXY(this.stamp, x, y, false);
  47429. x += this.characterWidth + customSpacingX;
  47430. if (x > this.width)
  47431. {
  47432. break;
  47433. }
  47434. }
  47435. }
  47436. }
  47437. };
  47438. /**
  47439. * Works out the longest line of text in _text and returns its length
  47440. *
  47441. * @method Phaser.RetroFont#getLongestLine
  47442. * @memberof Phaser.RetroFont
  47443. * @return {number} The length of the longest line of text.
  47444. */
  47445. Phaser.RetroFont.prototype.getLongestLine = function () {
  47446. var longestLine = 0;
  47447. if (this._text.length > 0)
  47448. {
  47449. var lines = this._text.split("\n");
  47450. for (var i = 0; i < lines.length; i++)
  47451. {
  47452. if (lines[i].length > longestLine)
  47453. {
  47454. longestLine = lines[i].length;
  47455. }
  47456. }
  47457. }
  47458. return longestLine;
  47459. };
  47460. /**
  47461. * Internal helper function that removes all unsupported characters from the _text String, leaving only characters contained in the font set.
  47462. *
  47463. * @method Phaser.RetroFont#removeUnsupportedCharacters
  47464. * @memberof Phaser.RetroFont
  47465. * @protected
  47466. * @param {boolean} [stripCR=true] - Should it strip carriage returns as well?
  47467. * @return {string} A clean version of the string.
  47468. */
  47469. Phaser.RetroFont.prototype.removeUnsupportedCharacters = function (stripCR) {
  47470. var newString = "";
  47471. for (var c = 0; c < this._text.length; c++)
  47472. {
  47473. var aChar = this._text[c];
  47474. var code = aChar.charCodeAt(0);
  47475. if (this.grabData[code] >= 0 || (!stripCR && aChar === "\n"))
  47476. {
  47477. newString = newString.concat(aChar);
  47478. }
  47479. }
  47480. return newString;
  47481. };
  47482. /**
  47483. * Updates the x and/or y offset that the font is rendered from. This updates all of the texture frames, so be careful how often it is called.
  47484. * Note that the values given for the x and y properties are either ADDED to or SUBTRACTED from (if negative) the existing offsetX/Y values of the characters.
  47485. * So if the current offsetY is 8 and you want it to start rendering from y16 you would call updateOffset(0, 8) to add 8 to the current y offset.
  47486. *
  47487. * @method Phaser.RetroFont#updateOffset
  47488. * @memberof Phaser.RetroFont
  47489. * @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here.
  47490. * @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here.
  47491. */
  47492. Phaser.RetroFont.prototype.updateOffset = function (x, y) {
  47493. if (this.offsetX === x && this.offsetY === y)
  47494. {
  47495. return;
  47496. }
  47497. var diffX = x - this.offsetX;
  47498. var diffY = y - this.offsetY;
  47499. var frames = this.game.cache.getFrameData(this.stamp.key).getFrames();
  47500. var i = frames.length;
  47501. while (i--)
  47502. {
  47503. frames[i].x += diffX;
  47504. frames[i].y += diffY;
  47505. }
  47506. this.buildRetroFontText();
  47507. };
  47508. /**
  47509. * @name Phaser.RetroFont#text
  47510. * @property {string} text - Set this value to update the text in this sprite. Carriage returns are automatically stripped out if multiLine is false. Text is converted to upper case if autoUpperCase is true.
  47511. */
  47512. Object.defineProperty(Phaser.RetroFont.prototype, "text", {
  47513. get: function () {
  47514. return this._text;
  47515. },
  47516. set: function (value) {
  47517. var newText;
  47518. if (this.autoUpperCase)
  47519. {
  47520. newText = value.toUpperCase();
  47521. }
  47522. else
  47523. {
  47524. newText = value;
  47525. }
  47526. if (newText !== this._text)
  47527. {
  47528. this._text = newText;
  47529. this.removeUnsupportedCharacters(this.multiLine);
  47530. this.buildRetroFontText();
  47531. }
  47532. }
  47533. });
  47534. /**
  47535. * @name Phaser.RetroFont#smoothed
  47536. * @property {boolean} smoothed - Sets if the stamp is smoothed or not.
  47537. */
  47538. Object.defineProperty(Phaser.RetroFont.prototype, "smoothed", {
  47539. get: function () {
  47540. return this.stamp.smoothed;
  47541. },
  47542. set: function (value) {
  47543. this.stamp.smoothed = value;
  47544. this.buildRetroFontText();
  47545. }
  47546. });
  47547. /**
  47548. * @author Richard Davey <rich@photonstorm.com>
  47549. * @copyright 2016 Photon Storm Ltd, Richard Davey
  47550. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  47551. */
  47552. /**
  47553. * A Rope is a Sprite that has a repeating texture.
  47554. *
  47555. * The texture will automatically wrap on the edges as it moves.
  47556. *
  47557. * Please note that Ropes cannot have an input handler.
  47558. *
  47559. * @class Phaser.Rope
  47560. * @constructor
  47561. * @extends PIXI.Rope
  47562. * @extends Phaser.Component.Core
  47563. * @extends Phaser.Component.Angle
  47564. * @extends Phaser.Component.Animation
  47565. * @extends Phaser.Component.AutoCull
  47566. * @extends Phaser.Component.Bounds
  47567. * @extends Phaser.Component.BringToTop
  47568. * @extends Phaser.Component.Crop
  47569. * @extends Phaser.Component.Delta
  47570. * @extends Phaser.Component.Destroy
  47571. * @extends Phaser.Component.FixedToCamera
  47572. * @extends Phaser.Component.InWorld
  47573. * @extends Phaser.Component.LifeSpan
  47574. * @extends Phaser.Component.LoadTexture
  47575. * @extends Phaser.Component.Overlap
  47576. * @extends Phaser.Component.PhysicsBody
  47577. * @extends Phaser.Component.Reset
  47578. * @extends Phaser.Component.ScaleMinMax
  47579. * @extends Phaser.Component.Smoothed
  47580. * @param {Phaser.Game} game - A reference to the currently running game.
  47581. * @param {number} x - The x coordinate (in world space) to position the Rope at.
  47582. * @param {number} y - The y coordinate (in world space) to position the Rope at.
  47583. * @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Rope during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture.
  47584. * @param {string|number} frame - If this Rope 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.
  47585. * @param {Array} points - An array of {Phaser.Point}.
  47586. */
  47587. Phaser.Rope = function (game, x, y, key, frame, points) {
  47588. this.points = [];
  47589. this.points = points;
  47590. this._hasUpdateAnimation = false;
  47591. this._updateAnimationCallback = null;
  47592. x = x || 0;
  47593. y = y || 0;
  47594. key = key || null;
  47595. frame = frame || null;
  47596. /**
  47597. * @property {number} type - The const type of this object.
  47598. * @readonly
  47599. */
  47600. this.type = Phaser.ROPE;
  47601. PIXI.Rope.call(this, PIXI.TextureCache['__default'], this.points);
  47602. Phaser.Component.Core.init.call(this, game, x, y, key, frame);
  47603. };
  47604. Phaser.Rope.prototype = Object.create(PIXI.Rope.prototype);
  47605. Phaser.Rope.prototype.constructor = Phaser.Rope;
  47606. Phaser.Component.Core.install.call(Phaser.Rope.prototype, [
  47607. 'Angle',
  47608. 'Animation',
  47609. 'AutoCull',
  47610. 'Bounds',
  47611. 'BringToTop',
  47612. 'Crop',
  47613. 'Delta',
  47614. 'Destroy',
  47615. 'FixedToCamera',
  47616. 'InWorld',
  47617. 'LifeSpan',
  47618. 'LoadTexture',
  47619. 'Overlap',
  47620. 'PhysicsBody',
  47621. 'Reset',
  47622. 'ScaleMinMax',
  47623. 'Smoothed'
  47624. ]);
  47625. Phaser.Rope.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate;
  47626. Phaser.Rope.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate;
  47627. Phaser.Rope.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate;
  47628. Phaser.Rope.prototype.preUpdateCore = Phaser.Component.Core.preUpdate;
  47629. /**
  47630. * Automatically called by World.preUpdate.
  47631. *
  47632. * @method Phaser.Rope#preUpdate
  47633. * @memberof Phaser.Rope
  47634. */
  47635. Phaser.Rope.prototype.preUpdate = function() {
  47636. if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld())
  47637. {
  47638. return false;
  47639. }
  47640. return this.preUpdateCore();
  47641. };
  47642. /**
  47643. * Override and use this function in your own custom objects to handle any update requirements you may have.
  47644. *
  47645. * @method Phaser.Rope#update
  47646. * @memberof Phaser.Rope
  47647. */
  47648. Phaser.Rope.prototype.update = function() {
  47649. if (this._hasUpdateAnimation)
  47650. {
  47651. this.updateAnimation.call(this);
  47652. }
  47653. };
  47654. /**
  47655. * Resets the Rope. This places the Rope at the given x/y world coordinates and then
  47656. * sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state.
  47657. * If the Rope has a physics body that too is reset.
  47658. *
  47659. * @method Phaser.Rope#reset
  47660. * @memberof Phaser.Rope
  47661. * @param {number} x - The x coordinate (in world space) to position the Sprite at.
  47662. * @param {number} y - The y coordinate (in world space) to position the Sprite at.
  47663. * @return {Phaser.Rope} This instance.
  47664. */
  47665. Phaser.Rope.prototype.reset = function(x, y) {
  47666. Phaser.Component.Reset.prototype.reset.call(this, x, y);
  47667. return this;
  47668. };
  47669. /**
  47670. * A Rope will call its updateAnimation function on each update loop if it has one.
  47671. *
  47672. * @name Phaser.Rope#updateAnimation
  47673. * @property {function} updateAnimation - Set to a function if you'd like the rope to animate during the update phase. Set to false or null to remove it.
  47674. */
  47675. Object.defineProperty(Phaser.Rope.prototype, "updateAnimation", {
  47676. get: function () {
  47677. return this._updateAnimation;
  47678. },
  47679. set: function (value) {
  47680. if (value && typeof value === 'function')
  47681. {
  47682. this._hasUpdateAnimation = true;
  47683. this._updateAnimation = value;
  47684. }
  47685. else
  47686. {
  47687. this._hasUpdateAnimation = false;
  47688. this._updateAnimation = null;
  47689. }
  47690. }
  47691. });
  47692. /**
  47693. * The segments that make up the rope body as an array of Phaser.Rectangles
  47694. *
  47695. * @name Phaser.Rope#segments
  47696. * @property {Phaser.Rectangles[]} updateAnimation - Returns an array of Phaser.Rectangles that represent the segments of the given rope
  47697. */
  47698. Object.defineProperty(Phaser.Rope.prototype, "segments", {
  47699. get: function() {
  47700. var segments = [];
  47701. var index, x1, y1, x2, y2, width, height, rect;
  47702. for (var i = 0; i < this.points.length; i++)
  47703. {
  47704. index = i * 4;
  47705. x1 = this.vertices[index] * this.scale.x;
  47706. y1 = this.vertices[index + 1] * this.scale.y;
  47707. x2 = this.vertices[index + 4] * this.scale.x;
  47708. y2 = this.vertices[index + 3] * this.scale.y;
  47709. width = Phaser.Math.difference(x1, x2);
  47710. height = Phaser.Math.difference(y1, y2);
  47711. x1 += this.world.x;
  47712. y1 += this.world.y;
  47713. rect = new Phaser.Rectangle(x1, y1, width, height);
  47714. segments.push(rect);
  47715. }
  47716. return segments;
  47717. }
  47718. });
  47719. /**
  47720. * @author Richard Davey <rich@photonstorm.com>
  47721. * @copyright 2016 Photon Storm Ltd.
  47722. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  47723. */
  47724. /**
  47725. * A TileSprite is a Sprite that has a repeating texture. The texture can be scrolled and scaled independently of the TileSprite itself.
  47726. * Textures will automatically wrap and are designed so that you can create game backdrops using seamless textures as a source.
  47727. *
  47728. * TileSprites have no input handler or physics bodies by default, both need enabling in the same way as for normal Sprites.
  47729. *
  47730. * You shouldn't ever create a TileSprite any larger than your actual screen size. If you want to create a large repeating background
  47731. * that scrolls across the whole map of your game, then you create a TileSprite that fits the screen size and then use the `tilePosition`
  47732. * property to scroll the texture as the player moves. If you create a TileSprite that is thousands of pixels in size then it will
  47733. * consume huge amounts of memory and cause performance issues. Remember: use `tilePosition` to scroll your texture and `tileScale` to
  47734. * adjust the scale of the texture - don't resize the sprite itself or make it larger than it needs.
  47735. *
  47736. * An important note about texture dimensions:
  47737. *
  47738. * When running under Canvas a TileSprite can use any texture size without issue. When running under WebGL the texture should ideally be
  47739. * a power of two in size (i.e. 4, 8, 16, 32, 64, 128, 256, 512, etch pixels width by height). If the texture isn't a power of two
  47740. * it will be rendered to a blank canvas that is the correct size, which means you may have 'blank' areas appearing to the right and
  47741. * bottom of your frame. To avoid this ensure your textures are perfect powers of two.
  47742. *
  47743. * TileSprites support animations in the same way that Sprites do. You add and play animations using the AnimationManager. However
  47744. * if your game is running under WebGL please note that each frame of the animation must be a power of two in size, or it will receive
  47745. * additional padding to enforce it to be so.
  47746. *
  47747. * @class Phaser.TileSprite
  47748. * @constructor
  47749. * @extends PIXI.TilingSprite
  47750. * @extends Phaser.Component.Core
  47751. * @extends Phaser.Component.Angle
  47752. * @extends Phaser.Component.Animation
  47753. * @extends Phaser.Component.AutoCull
  47754. * @extends Phaser.Component.Bounds
  47755. * @extends Phaser.Component.BringToTop
  47756. * @extends Phaser.Component.Destroy
  47757. * @extends Phaser.Component.FixedToCamera
  47758. * @extends Phaser.Component.Health
  47759. * @extends Phaser.Component.InCamera
  47760. * @extends Phaser.Component.InputEnabled
  47761. * @extends Phaser.Component.InWorld
  47762. * @extends Phaser.Component.LifeSpan
  47763. * @extends Phaser.Component.LoadTexture
  47764. * @extends Phaser.Component.Overlap
  47765. * @extends Phaser.Component.PhysicsBody
  47766. * @extends Phaser.Component.Reset
  47767. * @extends Phaser.Component.Smoothed
  47768. * @param {Phaser.Game} game - A reference to the currently running game.
  47769. * @param {number} x - The x coordinate (in world space) to position the TileSprite at.
  47770. * @param {number} y - The y coordinate (in world space) to position the TileSprite at.
  47771. * @param {number} width - The width of the TileSprite.
  47772. * @param {number} height - The height of the TileSprite.
  47773. * @param {string|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Phaser Image Cache entry, or an instance of a PIXI.Texture or BitmapData.
  47774. * @param {string|number} frame - If this TileSprite 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.
  47775. */
  47776. Phaser.TileSprite = function (game, x, y, width, height, key, frame) {
  47777. x = x || 0;
  47778. y = y || 0;
  47779. width = width || 256;
  47780. height = height || 256;
  47781. key = key || null;
  47782. frame = frame || null;
  47783. /**
  47784. * @property {number} type - The const type of this object.
  47785. * @readonly
  47786. */
  47787. this.type = Phaser.TILESPRITE;
  47788. /**
  47789. * @property {number} physicsType - The const physics body type of this object.
  47790. * @readonly
  47791. */
  47792. this.physicsType = Phaser.SPRITE;
  47793. /**
  47794. * @property {Phaser.Point} _scroll - Internal cache var.
  47795. * @private
  47796. */
  47797. this._scroll = new Phaser.Point();
  47798. var def = game.cache.getImage('__default', true);
  47799. PIXI.TilingSprite.call(this, new PIXI.Texture(def.base), width, height);
  47800. Phaser.Component.Core.init.call(this, game, x, y, key, frame);
  47801. };
  47802. Phaser.TileSprite.prototype = Object.create(PIXI.TilingSprite.prototype);
  47803. Phaser.TileSprite.prototype.constructor = Phaser.TileSprite;
  47804. Phaser.Component.Core.install.call(Phaser.TileSprite.prototype, [
  47805. 'Angle',
  47806. 'Animation',
  47807. 'AutoCull',
  47808. 'Bounds',
  47809. 'BringToTop',
  47810. 'Destroy',
  47811. 'FixedToCamera',
  47812. 'Health',
  47813. 'InCamera',
  47814. 'InputEnabled',
  47815. 'InWorld',
  47816. 'LifeSpan',
  47817. 'LoadTexture',
  47818. 'Overlap',
  47819. 'PhysicsBody',
  47820. 'Reset',
  47821. 'Smoothed'
  47822. ]);
  47823. Phaser.TileSprite.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate;
  47824. Phaser.TileSprite.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate;
  47825. Phaser.TileSprite.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate;
  47826. Phaser.TileSprite.prototype.preUpdateCore = Phaser.Component.Core.preUpdate;
  47827. /**
  47828. * Automatically called by World.preUpdate.
  47829. *
  47830. * @method Phaser.TileSprite#preUpdate
  47831. * @memberof Phaser.TileSprite
  47832. */
  47833. Phaser.TileSprite.prototype.preUpdate = function() {
  47834. if (this._scroll.x !== 0)
  47835. {
  47836. this.tilePosition.x += this._scroll.x * this.game.time.physicsElapsed;
  47837. }
  47838. if (this._scroll.y !== 0)
  47839. {
  47840. this.tilePosition.y += this._scroll.y * this.game.time.physicsElapsed;
  47841. }
  47842. if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld())
  47843. {
  47844. return false;
  47845. }
  47846. return this.preUpdateCore();
  47847. };
  47848. /**
  47849. * Sets this TileSprite to automatically scroll in the given direction until stopped via TileSprite.stopScroll().
  47850. * The scroll speed is specified in pixels per second.
  47851. * A negative x value will scroll to the left. A positive x value will scroll to the right.
  47852. * A negative y value will scroll up. A positive y value will scroll down.
  47853. *
  47854. * @method Phaser.TileSprite#autoScroll
  47855. * @memberof Phaser.TileSprite
  47856. * @param {number} x - Horizontal scroll speed in pixels per second.
  47857. * @param {number} y - Vertical scroll speed in pixels per second.
  47858. */
  47859. Phaser.TileSprite.prototype.autoScroll = function(x, y) {
  47860. this._scroll.set(x, y);
  47861. };
  47862. /**
  47863. * Stops an automatically scrolling TileSprite.
  47864. *
  47865. * @method Phaser.TileSprite#stopScroll
  47866. * @memberof Phaser.TileSprite
  47867. */
  47868. Phaser.TileSprite.prototype.stopScroll = function() {
  47869. this._scroll.set(0, 0);
  47870. };
  47871. /**
  47872. * Destroys the TileSprite. This removes it from its parent group, destroys the event and animation handlers if present
  47873. * and nulls its reference to game, freeing it up for garbage collection.
  47874. *
  47875. * @method Phaser.TileSprite#destroy
  47876. * @memberof Phaser.TileSprite
  47877. * @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called?
  47878. */
  47879. Phaser.TileSprite.prototype.destroy = function(destroyChildren) {
  47880. Phaser.Component.Destroy.prototype.destroy.call(this, destroyChildren);
  47881. PIXI.TilingSprite.prototype.destroy.call(this);
  47882. };
  47883. /**
  47884. * Resets the TileSprite. This places the TileSprite at the given x/y world coordinates, resets the tilePosition and then
  47885. * sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state.
  47886. * If the TileSprite has a physics body that too is reset.
  47887. *
  47888. * @method Phaser.TileSprite#reset
  47889. * @memberof Phaser.TileSprite
  47890. * @param {number} x - The x coordinate (in world space) to position the Sprite at.
  47891. * @param {number} y - The y coordinate (in world space) to position the Sprite at.
  47892. * @return {Phaser.TileSprite} This instance.
  47893. */
  47894. Phaser.TileSprite.prototype.reset = function(x, y) {
  47895. Phaser.Component.Reset.prototype.reset.call(this, x, y);
  47896. this.tilePosition.x = 0;
  47897. this.tilePosition.y = 0;
  47898. return this;
  47899. };
  47900. /**
  47901. * @author Richard Davey <rich@photonstorm.com>
  47902. * @copyright 2016 Photon Storm Ltd.
  47903. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  47904. */
  47905. /**
  47906. * @classdesc
  47907. * Detects device support capabilities and is responsible for device intialization - see {@link Phaser.Device.whenReady whenReady}.
  47908. *
  47909. * This class represents a singleton object that can be accessed directly as `game.device`
  47910. * (or, as a fallback, `Phaser.Device` when a game instance is not available) without the need to instantiate it.
  47911. *
  47912. * Unless otherwise noted the device capabilities are only guaranteed after initialization. Initialization
  47913. * occurs automatically and is guaranteed complete before {@link Phaser.Game} begins its "boot" phase.
  47914. * Feature detection can be modified in the {@link Phaser.Device.onInitialized onInitialized} signal.
  47915. *
  47916. * When checking features using the exposed properties only the *truth-iness* of the value should be relied upon
  47917. * unless the documentation states otherwise: properties may return `false`, `''`, `null`, or even `undefined`
  47918. * when indicating the lack of a feature.
  47919. *
  47920. * Uses elements from System.js by MrDoob and Modernizr
  47921. *
  47922. * @description
  47923. * It is not possible to instantiate the Device class manually.
  47924. *
  47925. * @class
  47926. * @protected
  47927. */
  47928. Phaser.Device = function () {
  47929. /**
  47930. * The time the device became ready.
  47931. * @property {integer} deviceReadyAt
  47932. * @protected
  47933. */
  47934. this.deviceReadyAt = 0;
  47935. /**
  47936. * The time as which initialization has completed.
  47937. * @property {boolean} initialized
  47938. * @protected
  47939. */
  47940. this.initialized = false;
  47941. // Browser / Host / Operating System
  47942. /**
  47943. * @property {boolean} desktop - Is running on a desktop?
  47944. * @default
  47945. */
  47946. this.desktop = false;
  47947. /**
  47948. * @property {boolean} iOS - Is running on iOS?
  47949. * @default
  47950. */
  47951. this.iOS = false;
  47952. /**
  47953. * @property {number} iOSVersion - If running in iOS this will contain the major version number.
  47954. * @default
  47955. */
  47956. this.iOSVersion = 0;
  47957. /**
  47958. * @property {boolean} cocoonJS - Is the game running under CocoonJS?
  47959. * @default
  47960. */
  47961. this.cocoonJS = false;
  47962. /**
  47963. * @property {boolean} cocoonJSApp - Is this game running with CocoonJS.App?
  47964. * @default
  47965. */
  47966. this.cocoonJSApp = false;
  47967. /**
  47968. * @property {boolean} cordova - Is the game running under Apache Cordova?
  47969. * @default
  47970. */
  47971. this.cordova = false;
  47972. /**
  47973. * @property {boolean} node - Is the game running under Node.js?
  47974. * @default
  47975. */
  47976. this.node = false;
  47977. /**
  47978. * @property {boolean} nodeWebkit - Is the game running under Node-Webkit?
  47979. * @default
  47980. */
  47981. this.nodeWebkit = false;
  47982. /**
  47983. * @property {boolean} electron - Is the game running under GitHub Electron?
  47984. * @default
  47985. */
  47986. this.electron = false;
  47987. /**
  47988. * @property {boolean} ejecta - Is the game running under Ejecta?
  47989. * @default
  47990. */
  47991. this.ejecta = false;
  47992. /**
  47993. * @property {boolean} crosswalk - Is the game running under the Intel Crosswalk XDK?
  47994. * @default
  47995. */
  47996. this.crosswalk = false;
  47997. /**
  47998. * @property {boolean} android - Is running on android?
  47999. * @default
  48000. */
  48001. this.android = false;
  48002. /**
  48003. * @property {boolean} chromeOS - Is running on chromeOS?
  48004. * @default
  48005. */
  48006. this.chromeOS = false;
  48007. /**
  48008. * @property {boolean} linux - Is running on linux?
  48009. * @default
  48010. */
  48011. this.linux = false;
  48012. /**
  48013. * @property {boolean} macOS - Is running on macOS?
  48014. * @default
  48015. */
  48016. this.macOS = false;
  48017. /**
  48018. * @property {boolean} windows - Is running on windows?
  48019. * @default
  48020. */
  48021. this.windows = false;
  48022. /**
  48023. * @property {boolean} windowsPhone - Is running on a Windows Phone?
  48024. * @default
  48025. */
  48026. this.windowsPhone = false;
  48027. // Features
  48028. /**
  48029. * @property {boolean} canvas - Is canvas available?
  48030. * @default
  48031. */
  48032. this.canvas = false;
  48033. /**
  48034. * @property {?boolean} canvasBitBltShift - True if canvas supports a 'copy' bitblt onto itself when the source and destination regions overlap.
  48035. * @default
  48036. */
  48037. this.canvasBitBltShift = null;
  48038. /**
  48039. * @property {boolean} webGL - Is webGL available?
  48040. * @default
  48041. */
  48042. this.webGL = false;
  48043. /**
  48044. * @property {boolean} file - Is file available?
  48045. * @default
  48046. */
  48047. this.file = false;
  48048. /**
  48049. * @property {boolean} fileSystem - Is fileSystem available?
  48050. * @default
  48051. */
  48052. this.fileSystem = false;
  48053. /**
  48054. * @property {boolean} localStorage - Is localStorage available?
  48055. * @default
  48056. */
  48057. this.localStorage = false;
  48058. /**
  48059. * @property {boolean} worker - Is worker available?
  48060. * @default
  48061. */
  48062. this.worker = false;
  48063. /**
  48064. * @property {boolean} css3D - Is css3D available?
  48065. * @default
  48066. */
  48067. this.css3D = false;
  48068. /**
  48069. * @property {boolean} pointerLock - Is Pointer Lock available?
  48070. * @default
  48071. */
  48072. this.pointerLock = false;
  48073. /**
  48074. * @property {boolean} typedArray - Does the browser support TypedArrays?
  48075. * @default
  48076. */
  48077. this.typedArray = false;
  48078. /**
  48079. * @property {boolean} vibration - Does the device support the Vibration API?
  48080. * @default
  48081. */
  48082. this.vibration = false;
  48083. /**
  48084. * @property {boolean} getUserMedia - Does the device support the getUserMedia API?
  48085. * @default
  48086. */
  48087. this.getUserMedia = true;
  48088. /**
  48089. * @property {boolean} quirksMode - Is the browser running in strict mode (false) or quirks mode? (true)
  48090. * @default
  48091. */
  48092. this.quirksMode = false;
  48093. // Input
  48094. /**
  48095. * @property {boolean} touch - Is touch available?
  48096. * @default
  48097. */
  48098. this.touch = false;
  48099. /**
  48100. * @property {boolean} mspointer - Is mspointer available?
  48101. * @default
  48102. */
  48103. this.mspointer = false;
  48104. /**
  48105. * @property {?string} wheelType - The newest type of Wheel/Scroll event supported: 'wheel', 'mousewheel', 'DOMMouseScroll'
  48106. * @default
  48107. * @protected
  48108. */
  48109. this.wheelEvent = null;
  48110. // Browser
  48111. /**
  48112. * @property {boolean} arora - Set to true if running in Arora.
  48113. * @default
  48114. */
  48115. this.arora = false;
  48116. /**
  48117. * @property {boolean} chrome - Set to true if running in Chrome.
  48118. * @default
  48119. */
  48120. this.chrome = false;
  48121. /**
  48122. * @property {number} chromeVersion - If running in Chrome this will contain the major version number.
  48123. * @default
  48124. */
  48125. this.chromeVersion = 0;
  48126. /**
  48127. * @property {boolean} epiphany - Set to true if running in Epiphany.
  48128. * @default
  48129. */
  48130. this.epiphany = false;
  48131. /**
  48132. * @property {boolean} firefox - Set to true if running in Firefox.
  48133. * @default
  48134. */
  48135. this.firefox = false;
  48136. /**
  48137. * @property {number} firefoxVersion - If running in Firefox this will contain the major version number.
  48138. * @default
  48139. */
  48140. this.firefoxVersion = 0;
  48141. /**
  48142. * @property {boolean} ie - Set to true if running in Internet Explorer.
  48143. * @default
  48144. */
  48145. this.ie = false;
  48146. /**
  48147. * @property {number} ieVersion - If running in Internet Explorer this will contain the major version number. Beyond IE10 you should use Device.trident and Device.tridentVersion.
  48148. * @default
  48149. */
  48150. this.ieVersion = 0;
  48151. /**
  48152. * @property {boolean} trident - Set to true if running a Trident version of Internet Explorer (IE11+)
  48153. * @default
  48154. */
  48155. this.trident = false;
  48156. /**
  48157. * @property {number} tridentVersion - If running in Internet Explorer 11 this will contain the major version number. See {@link http://msdn.microsoft.com/en-us/library/ie/ms537503(v=vs.85).aspx}
  48158. * @default
  48159. */
  48160. this.tridentVersion = 0;
  48161. /**
  48162. * @property {boolean} edge - Set to true if running in Microsoft Edge browser.
  48163. * @default
  48164. */
  48165. this.edge = false;
  48166. /**
  48167. * @property {boolean} mobileSafari - Set to true if running in Mobile Safari.
  48168. * @default
  48169. */
  48170. this.mobileSafari = false;
  48171. /**
  48172. * @property {boolean} midori - Set to true if running in Midori.
  48173. * @default
  48174. */
  48175. this.midori = false;
  48176. /**
  48177. * @property {boolean} opera - Set to true if running in Opera.
  48178. * @default
  48179. */
  48180. this.opera = false;
  48181. /**
  48182. * @property {boolean} safari - Set to true if running in Safari.
  48183. * @default
  48184. */
  48185. this.safari = false;
  48186. /**
  48187. * @property {number} safariVersion - If running in Safari this will contain the major version number.
  48188. * @default
  48189. */
  48190. this.safariVersion = 0;
  48191. /**
  48192. * @property {boolean} webApp - Set to true if running as a WebApp, i.e. within a WebView
  48193. * @default
  48194. */
  48195. this.webApp = false;
  48196. /**
  48197. * @property {boolean} silk - Set to true if running in the Silk browser (as used on the Amazon Kindle)
  48198. * @default
  48199. */
  48200. this.silk = false;
  48201. // Audio
  48202. /**
  48203. * @property {boolean} audioData - Are Audio tags available?
  48204. * @default
  48205. */
  48206. this.audioData = false;
  48207. /**
  48208. * @property {boolean} webAudio - Is the WebAudio API available?
  48209. * @default
  48210. */
  48211. this.webAudio = false;
  48212. /**
  48213. * @property {boolean} ogg - Can this device play ogg files?
  48214. * @default
  48215. */
  48216. this.ogg = false;
  48217. /**
  48218. * @property {boolean} opus - Can this device play opus files?
  48219. * @default
  48220. */
  48221. this.opus = false;
  48222. /**
  48223. * @property {boolean} mp3 - Can this device play mp3 files?
  48224. * @default
  48225. */
  48226. this.mp3 = false;
  48227. /**
  48228. * @property {boolean} wav - Can this device play wav files?
  48229. * @default
  48230. */
  48231. this.wav = false;
  48232. /**
  48233. * Can this device play m4a files?
  48234. * @property {boolean} m4a - True if this device can play m4a files.
  48235. * @default
  48236. */
  48237. this.m4a = false;
  48238. /**
  48239. * @property {boolean} webm - Can this device play webm files?
  48240. * @default
  48241. */
  48242. this.webm = false;
  48243. /**
  48244. * @property {boolean} dolby - Can this device play EC-3 Dolby Digital Plus files?
  48245. * @default
  48246. */
  48247. this.dolby = false;
  48248. // Video
  48249. /**
  48250. * @property {boolean} oggVideo - Can this device play ogg video files?
  48251. * @default
  48252. */
  48253. this.oggVideo = false;
  48254. /**
  48255. * @property {boolean} h264Video - Can this device play h264 mp4 video files?
  48256. * @default
  48257. */
  48258. this.h264Video = false;
  48259. /**
  48260. * @property {boolean} mp4Video - Can this device play h264 mp4 video files?
  48261. * @default
  48262. */
  48263. this.mp4Video = false;
  48264. /**
  48265. * @property {boolean} webmVideo - Can this device play webm video files?
  48266. * @default
  48267. */
  48268. this.webmVideo = false;
  48269. /**
  48270. * @property {boolean} vp9Video - Can this device play vp9 video files?
  48271. * @default
  48272. */
  48273. this.vp9Video = false;
  48274. /**
  48275. * @property {boolean} hlsVideo - Can this device play hls video files?
  48276. * @default
  48277. */
  48278. this.hlsVideo = false;
  48279. // Device
  48280. /**
  48281. * @property {boolean} iPhone - Is running on iPhone?
  48282. * @default
  48283. */
  48284. this.iPhone = false;
  48285. /**
  48286. * @property {boolean} iPhone4 - Is running on iPhone4?
  48287. * @default
  48288. */
  48289. this.iPhone4 = false;
  48290. /**
  48291. * @property {boolean} iPad - Is running on iPad?
  48292. * @default
  48293. */
  48294. this.iPad = false;
  48295. // Device features
  48296. /**
  48297. * @property {number} pixelRatio - PixelRatio of the host device?
  48298. * @default
  48299. */
  48300. this.pixelRatio = 0;
  48301. /**
  48302. * @property {boolean} littleEndian - Is the device big or little endian? (only detected if the browser supports TypedArrays)
  48303. * @default
  48304. */
  48305. this.littleEndian = false;
  48306. /**
  48307. * @property {boolean} LITTLE_ENDIAN - Same value as `littleEndian`.
  48308. * @default
  48309. */
  48310. this.LITTLE_ENDIAN = false;
  48311. /**
  48312. * @property {boolean} support32bit - Does the device context support 32bit pixel manipulation using array buffer views?
  48313. * @default
  48314. */
  48315. this.support32bit = false;
  48316. /**
  48317. * @property {boolean} fullscreen - Does the browser support the Full Screen API?
  48318. * @default
  48319. */
  48320. this.fullscreen = false;
  48321. /**
  48322. * @property {string} requestFullscreen - If the browser supports the Full Screen API this holds the call you need to use to activate it.
  48323. * @default
  48324. */
  48325. this.requestFullscreen = '';
  48326. /**
  48327. * @property {string} cancelFullscreen - If the browser supports the Full Screen API this holds the call you need to use to cancel it.
  48328. * @default
  48329. */
  48330. this.cancelFullscreen = '';
  48331. /**
  48332. * @property {boolean} fullscreenKeyboard - Does the browser support access to the Keyboard during Full Screen mode?
  48333. * @default
  48334. */
  48335. this.fullscreenKeyboard = false;
  48336. };
  48337. // Device is really a singleton/static entity; instantiate it
  48338. // and add new methods directly sans-prototype.
  48339. Phaser.Device = new Phaser.Device();
  48340. /**
  48341. * This signal is dispatched after device initialization occurs but before any of the ready
  48342. * callbacks (see {@link Phaser.Device.whenReady whenReady}) have been invoked.
  48343. *
  48344. * Local "patching" for a particular device can/should be done in this event.
  48345. *
  48346. * _Note_: This signal is removed after the device has been readied; if a handler has not been
  48347. * added _before_ `new Phaser.Game(..)` it is probably too late.
  48348. *
  48349. * @type {?Phaser.Signal}
  48350. * @static
  48351. */
  48352. Phaser.Device.onInitialized = new Phaser.Signal();
  48353. /**
  48354. * Add a device-ready handler and ensure the device ready sequence is started.
  48355. *
  48356. * Phaser.Device will _not_ activate or initialize until at least one `whenReady` handler is added,
  48357. * which is normally done automatically be calling `new Phaser.Game(..)`.
  48358. *
  48359. * The handler is invoked when the device is considered "ready", which may be immediately
  48360. * if the device is already "ready". See {@link Phaser.Device#deviceReadyAt deviceReadyAt}.
  48361. *
  48362. * @method
  48363. * @param {function} handler - Callback to invoke when the device is ready. It is invoked with the given context the Phaser.Device object is supplied as the first argument.
  48364. * @param {object} [context] - Context in which to invoke the handler
  48365. * @param {boolean} [nonPrimer=false] - If true the device ready check will not be started.
  48366. */
  48367. Phaser.Device.whenReady = function (callback, context, nonPrimer) {
  48368. var readyCheck = this._readyCheck;
  48369. if (this.deviceReadyAt || !readyCheck)
  48370. {
  48371. callback.call(context, this);
  48372. }
  48373. else if (readyCheck._monitor || nonPrimer)
  48374. {
  48375. readyCheck._queue = readyCheck._queue || [];
  48376. readyCheck._queue.push([callback, context]);
  48377. }
  48378. else
  48379. {
  48380. readyCheck._monitor = readyCheck.bind(this);
  48381. readyCheck._queue = readyCheck._queue || [];
  48382. readyCheck._queue.push([callback, context]);
  48383. var cordova = typeof window.cordova !== 'undefined';
  48384. var cocoonJS = navigator['isCocoonJS'];
  48385. if (document.readyState === 'complete' || document.readyState === 'interactive')
  48386. {
  48387. // Why is there an additional timeout here?
  48388. window.setTimeout(readyCheck._monitor, 0);
  48389. }
  48390. else if (cordova && !cocoonJS)
  48391. {
  48392. // Ref. http://docs.phonegap.com/en/3.5.0/cordova_events_events.md.html#deviceready
  48393. // Cordova, but NOT Cocoon?
  48394. document.addEventListener('deviceready', readyCheck._monitor, false);
  48395. }
  48396. else
  48397. {
  48398. document.addEventListener('DOMContentLoaded', readyCheck._monitor, false);
  48399. window.addEventListener('load', readyCheck._monitor, false);
  48400. }
  48401. }
  48402. };
  48403. /**
  48404. * Internal method used for checking when the device is ready.
  48405. * This function is removed from Phaser.Device when the device becomes ready.
  48406. *
  48407. * @method
  48408. * @private
  48409. */
  48410. Phaser.Device._readyCheck = function () {
  48411. var readyCheck = this._readyCheck;
  48412. if (!document.body)
  48413. {
  48414. window.setTimeout(readyCheck._monitor, 20);
  48415. }
  48416. else if (!this.deviceReadyAt)
  48417. {
  48418. this.deviceReadyAt = Date.now();
  48419. document.removeEventListener('deviceready', readyCheck._monitor);
  48420. document.removeEventListener('DOMContentLoaded', readyCheck._monitor);
  48421. window.removeEventListener('load', readyCheck._monitor);
  48422. this._initialize();
  48423. this.initialized = true;
  48424. this.onInitialized.dispatch(this);
  48425. var item;
  48426. while ((item = readyCheck._queue.shift()))
  48427. {
  48428. var callback = item[0];
  48429. var context = item[1];
  48430. callback.call(context, this);
  48431. }
  48432. // Remove no longer useful methods and properties.
  48433. this._readyCheck = null;
  48434. this._initialize = null;
  48435. this.onInitialized = null;
  48436. }
  48437. };
  48438. /**
  48439. * Internal method to initialize the capability checks.
  48440. * This function is removed from Phaser.Device once the device is initialized.
  48441. *
  48442. * @method
  48443. * @private
  48444. */
  48445. Phaser.Device._initialize = function () {
  48446. var device = this;
  48447. /**
  48448. * Check which OS is game running on.
  48449. */
  48450. function _checkOS () {
  48451. var ua = navigator.userAgent;
  48452. if (/Playstation Vita/.test(ua))
  48453. {
  48454. device.vita = true;
  48455. }
  48456. else if (/Kindle/.test(ua) || /\bKF[A-Z][A-Z]+/.test(ua) || /Silk.*Mobile Safari/.test(ua))
  48457. {
  48458. device.kindle = true;
  48459. // This will NOT detect early generations of Kindle Fire, I think there is no reliable way...
  48460. // E.g. "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_3; en-us; Silk/1.1.0-80) AppleWebKit/533.16 (KHTML, like Gecko) Version/5.0 Safari/533.16 Silk-Accelerated=true"
  48461. }
  48462. else if (/Android/.test(ua))
  48463. {
  48464. device.android = true;
  48465. }
  48466. else if (/CrOS/.test(ua))
  48467. {
  48468. device.chromeOS = true;
  48469. }
  48470. else if (/iP[ao]d|iPhone/i.test(ua))
  48471. {
  48472. device.iOS = true;
  48473. (navigator.appVersion).match(/OS (\d+)/);
  48474. device.iOSVersion = parseInt(RegExp.$1, 10);
  48475. }
  48476. else if (/Linux/.test(ua))
  48477. {
  48478. device.linux = true;
  48479. }
  48480. else if (/Mac OS/.test(ua))
  48481. {
  48482. device.macOS = true;
  48483. }
  48484. else if (/Windows/.test(ua))
  48485. {
  48486. device.windows = true;
  48487. }
  48488. if (/Windows Phone/i.test(ua) || /IEMobile/i.test(ua))
  48489. {
  48490. device.android = false;
  48491. device.iOS = false;
  48492. device.macOS = false;
  48493. device.windows = true;
  48494. device.windowsPhone = true;
  48495. }
  48496. var silk = /Silk/.test(ua); // detected in browsers
  48497. if (device.windows || device.macOS || (device.linux && !silk) || device.chromeOS)
  48498. {
  48499. device.desktop = true;
  48500. }
  48501. // Windows Phone / Table reset
  48502. if (device.windowsPhone || ((/Windows NT/i.test(ua)) && (/Touch/i.test(ua))))
  48503. {
  48504. device.desktop = false;
  48505. }
  48506. }
  48507. /**
  48508. * Check HTML5 features of the host environment.
  48509. */
  48510. function _checkFeatures () {
  48511. device.canvas = !!window['CanvasRenderingContext2D'] || device.cocoonJS;
  48512. try {
  48513. device.localStorage = !!localStorage.getItem;
  48514. } catch (error) {
  48515. device.localStorage = false;
  48516. }
  48517. device.file = !!window['File'] && !!window['FileReader'] && !!window['FileList'] && !!window['Blob'];
  48518. device.fileSystem = !!window['requestFileSystem'];
  48519. device.webGL = ( function () { try { var canvas = document.createElement( 'canvas' ); /*Force screencanvas to false*/ canvas.screencanvas = false; return !! window.WebGLRenderingContext && ( canvas.getContext( 'webgl' ) || canvas.getContext( 'experimental-webgl' ) ); } catch( e ) { return false; } } )();
  48520. device.webGL = !!device.webGL;
  48521. device.worker = !!window['Worker'];
  48522. device.pointerLock = 'pointerLockElement' in document || 'mozPointerLockElement' in document || 'webkitPointerLockElement' in document;
  48523. device.quirksMode = (document.compatMode === 'CSS1Compat') ? false : true;
  48524. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia || navigator.oGetUserMedia;
  48525. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  48526. device.getUserMedia = device.getUserMedia && !!navigator.getUserMedia && !!window.URL;
  48527. // Older versions of firefox (< 21) apparently claim support but user media does not actually work
  48528. if (device.firefox && device.firefoxVersion < 21)
  48529. {
  48530. device.getUserMedia = false;
  48531. }
  48532. // TODO: replace canvasBitBltShift detection with actual feature check
  48533. // Excludes iOS versions as they generally wrap UIWebView (eg. Safari WebKit) and it
  48534. // is safer to not try and use the fast copy-over method.
  48535. if (!device.iOS && (device.ie || device.firefox || device.chrome))
  48536. {
  48537. device.canvasBitBltShift = true;
  48538. }
  48539. // Known not to work
  48540. if (device.safari || device.mobileSafari)
  48541. {
  48542. device.canvasBitBltShift = false;
  48543. }
  48544. }
  48545. /**
  48546. * Checks/configures various input.
  48547. */
  48548. function _checkInput () {
  48549. if ('ontouchstart' in document.documentElement || (window.navigator.maxTouchPoints && window.navigator.maxTouchPoints >= 1))
  48550. {
  48551. device.touch = true;
  48552. }
  48553. if (window.navigator.msPointerEnabled || window.navigator.pointerEnabled)
  48554. {
  48555. device.mspointer = true;
  48556. }
  48557. if (!device.cocoonJS)
  48558. {
  48559. // See https://developer.mozilla.org/en-US/docs/Web/Events/wheel
  48560. if ('onwheel' in window || (device.ie && 'WheelEvent' in window))
  48561. {
  48562. // DOM3 Wheel Event: FF 17+, IE 9+, Chrome 31+, Safari 7+
  48563. device.wheelEvent = 'wheel';
  48564. }
  48565. else if ('onmousewheel' in window)
  48566. {
  48567. // Non-FF legacy: IE 6-9, Chrome 1-31, Safari 5-7.
  48568. device.wheelEvent = 'mousewheel';
  48569. }
  48570. else if (device.firefox && 'MouseScrollEvent' in window)
  48571. {
  48572. // FF prior to 17. This should probably be scrubbed.
  48573. device.wheelEvent = 'DOMMouseScroll';
  48574. }
  48575. }
  48576. }
  48577. /**
  48578. * Checks for support of the Full Screen API.
  48579. */
  48580. function _checkFullScreenSupport () {
  48581. var fs = [
  48582. 'requestFullscreen',
  48583. 'requestFullScreen',
  48584. 'webkitRequestFullscreen',
  48585. 'webkitRequestFullScreen',
  48586. 'msRequestFullscreen',
  48587. 'msRequestFullScreen',
  48588. 'mozRequestFullScreen',
  48589. 'mozRequestFullscreen'
  48590. ];
  48591. var element = document.createElement('div');
  48592. for (var i = 0; i < fs.length; i++)
  48593. {
  48594. if (element[fs[i]])
  48595. {
  48596. device.fullscreen = true;
  48597. device.requestFullscreen = fs[i];
  48598. break;
  48599. }
  48600. }
  48601. var cfs = [
  48602. 'cancelFullScreen',
  48603. 'exitFullscreen',
  48604. 'webkitCancelFullScreen',
  48605. 'webkitExitFullscreen',
  48606. 'msCancelFullScreen',
  48607. 'msExitFullscreen',
  48608. 'mozCancelFullScreen',
  48609. 'mozExitFullscreen'
  48610. ];
  48611. if (device.fullscreen)
  48612. {
  48613. for (var i = 0; i < cfs.length; i++)
  48614. {
  48615. if (document[cfs[i]])
  48616. {
  48617. device.cancelFullscreen = cfs[i];
  48618. break;
  48619. }
  48620. }
  48621. }
  48622. // Keyboard Input?
  48623. if (window['Element'] && Element['ALLOW_KEYBOARD_INPUT'])
  48624. {
  48625. device.fullscreenKeyboard = true;
  48626. }
  48627. }
  48628. /**
  48629. * Check what browser is game running in.
  48630. */
  48631. function _checkBrowser () {
  48632. var ua = navigator.userAgent;
  48633. if (/Arora/.test(ua))
  48634. {
  48635. device.arora = true;
  48636. }
  48637. else if (/Edge\/\d+/.test(ua))
  48638. {
  48639. device.edge = true;
  48640. }
  48641. else if (/Chrome\/(\d+)/.test(ua) && !device.windowsPhone)
  48642. {
  48643. device.chrome = true;
  48644. device.chromeVersion = parseInt(RegExp.$1, 10);
  48645. }
  48646. else if (/Epiphany/.test(ua))
  48647. {
  48648. device.epiphany = true;
  48649. }
  48650. else if (/Firefox\D+(\d+)/.test(ua))
  48651. {
  48652. device.firefox = true;
  48653. device.firefoxVersion = parseInt(RegExp.$1, 10);
  48654. }
  48655. else if (/AppleWebKit/.test(ua) && device.iOS)
  48656. {
  48657. device.mobileSafari = true;
  48658. }
  48659. else if (/MSIE (\d+\.\d+);/.test(ua))
  48660. {
  48661. device.ie = true;
  48662. device.ieVersion = parseInt(RegExp.$1, 10);
  48663. }
  48664. else if (/Midori/.test(ua))
  48665. {
  48666. device.midori = true;
  48667. }
  48668. else if (/Opera/.test(ua))
  48669. {
  48670. device.opera = true;
  48671. }
  48672. else if (/Safari\/(\d+)/.test(ua) && !device.windowsPhone)
  48673. {
  48674. device.safari = true;
  48675. if (/Version\/(\d+)\./.test(ua))
  48676. {
  48677. device.safariVersion = parseInt(RegExp.$1, 10);
  48678. }
  48679. }
  48680. else if (/Trident\/(\d+\.\d+)(.*)rv:(\d+\.\d+)/.test(ua))
  48681. {
  48682. device.ie = true;
  48683. device.trident = true;
  48684. device.tridentVersion = parseInt(RegExp.$1, 10);
  48685. device.ieVersion = parseInt(RegExp.$3, 10);
  48686. }
  48687. // Silk gets its own if clause because its ua also contains 'Safari'
  48688. if (/Silk/.test(ua))
  48689. {
  48690. device.silk = true;
  48691. }
  48692. // WebApp mode in iOS
  48693. if (navigator['standalone'])
  48694. {
  48695. device.webApp = true;
  48696. }
  48697. if (typeof window.cordova !== "undefined")
  48698. {
  48699. device.cordova = true;
  48700. }
  48701. if (typeof process !== "undefined" && typeof require !== "undefined")
  48702. {
  48703. device.node = true;
  48704. }
  48705. if (device.node && typeof process.versions === 'object')
  48706. {
  48707. device.nodeWebkit = !!process.versions['node-webkit'];
  48708. device.electron = !!process.versions.electron;
  48709. }
  48710. if (navigator['isCocoonJS'])
  48711. {
  48712. device.cocoonJS = true;
  48713. }
  48714. if (device.cocoonJS)
  48715. {
  48716. try {
  48717. device.cocoonJSApp = (typeof CocoonJS !== "undefined");
  48718. }
  48719. catch(error)
  48720. {
  48721. device.cocoonJSApp = false;
  48722. }
  48723. }
  48724. if (typeof window.ejecta !== "undefined")
  48725. {
  48726. device.ejecta = true;
  48727. }
  48728. if (/Crosswalk/.test(ua))
  48729. {
  48730. device.crosswalk = true;
  48731. }
  48732. }
  48733. /**
  48734. * Check video support.
  48735. */
  48736. function _checkVideo () {
  48737. var videoElement = document.createElement("video");
  48738. var result = false;
  48739. try {
  48740. if (result = !!videoElement.canPlayType)
  48741. {
  48742. if (videoElement.canPlayType('video/ogg; codecs="theora"').replace(/^no$/, ''))
  48743. {
  48744. device.oggVideo = true;
  48745. }
  48746. if (videoElement.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/, ''))
  48747. {
  48748. // Without QuickTime, this value will be `undefined`. github.com/Modernizr/Modernizr/issues/546
  48749. device.h264Video = true;
  48750. device.mp4Video = true;
  48751. }
  48752. if (videoElement.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/, ''))
  48753. {
  48754. device.webmVideo = true;
  48755. }
  48756. if (videoElement.canPlayType('video/webm; codecs="vp9"').replace(/^no$/, ''))
  48757. {
  48758. device.vp9Video = true;
  48759. }
  48760. if (videoElement.canPlayType('application/x-mpegURL; codecs="avc1.42E01E"').replace(/^no$/, ''))
  48761. {
  48762. device.hlsVideo = true;
  48763. }
  48764. }
  48765. } catch (e) {}
  48766. }
  48767. /**
  48768. * Check audio support.
  48769. */
  48770. function _checkAudio () {
  48771. device.audioData = !!(window['Audio']);
  48772. device.webAudio = !!(window['AudioContext'] || window['webkitAudioContext']);
  48773. var audioElement = document.createElement('audio');
  48774. var result = false;
  48775. try {
  48776. if (result = !!audioElement.canPlayType)
  48777. {
  48778. if (audioElement.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, ''))
  48779. {
  48780. device.ogg = true;
  48781. }
  48782. if (audioElement.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/, '') || audioElement.canPlayType('audio/opus;').replace(/^no$/, ''))
  48783. {
  48784. device.opus = true;
  48785. }
  48786. if (audioElement.canPlayType('audio/mpeg;').replace(/^no$/, ''))
  48787. {
  48788. device.mp3 = true;
  48789. }
  48790. // Mimetypes accepted:
  48791. // developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements
  48792. // bit.ly/iphoneoscodecs
  48793. if (audioElement.canPlayType('audio/wav; codecs="1"').replace(/^no$/, ''))
  48794. {
  48795. device.wav = true;
  48796. }
  48797. if (audioElement.canPlayType('audio/x-m4a;') || audioElement.canPlayType('audio/aac;').replace(/^no$/, ''))
  48798. {
  48799. device.m4a = true;
  48800. }
  48801. if (audioElement.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, ''))
  48802. {
  48803. device.webm = true;
  48804. }
  48805. if (audioElement.canPlayType('audio/mp4;codecs="ec-3"') !== '')
  48806. {
  48807. if (device.edge)
  48808. {
  48809. device.dolby = true;
  48810. }
  48811. else if (device.safari && device.safariVersion >= 9)
  48812. {
  48813. if (/Mac OS X (\d+)_(\d+)/.test(navigator.userAgent))
  48814. {
  48815. var major = parseInt(RegExp.$1, 10);
  48816. var minor = parseInt(RegExp.$2, 10);
  48817. if ((major === 10 && minor >= 11) || major > 10)
  48818. {
  48819. device.dolby = true;
  48820. }
  48821. }
  48822. }
  48823. }
  48824. }
  48825. } catch (e) {
  48826. }
  48827. }
  48828. /**
  48829. * Check PixelRatio, iOS device, Vibration API, ArrayBuffers and endianess.
  48830. */
  48831. function _checkDevice () {
  48832. device.pixelRatio = window['devicePixelRatio'] || 1;
  48833. device.iPhone = navigator.userAgent.toLowerCase().indexOf('iphone') != -1;
  48834. device.iPhone4 = (device.pixelRatio == 2 && device.iPhone);
  48835. device.iPad = navigator.userAgent.toLowerCase().indexOf('ipad') != -1;
  48836. if (typeof Int8Array !== 'undefined')
  48837. {
  48838. device.typedArray = true;
  48839. }
  48840. else
  48841. {
  48842. device.typedArray = false;
  48843. }
  48844. if (typeof ArrayBuffer !== 'undefined' && typeof Uint8Array !== 'undefined' && typeof Uint32Array !== 'undefined')
  48845. {
  48846. device.littleEndian = _checkIsLittleEndian();
  48847. device.LITTLE_ENDIAN = device.littleEndian;
  48848. }
  48849. device.support32bit = (typeof ArrayBuffer !== "undefined" && typeof Uint8ClampedArray !== "undefined" && typeof Int32Array !== "undefined" && device.littleEndian !== null && _checkIsUint8ClampedImageData());
  48850. navigator.vibrate = navigator.vibrate || navigator.webkitVibrate || navigator.mozVibrate || navigator.msVibrate;
  48851. if (navigator.vibrate)
  48852. {
  48853. device.vibration = true;
  48854. }
  48855. }
  48856. /**
  48857. * Check Little or Big Endian system.
  48858. *
  48859. * @author Matt DesLauriers (@mattdesl)
  48860. */
  48861. function _checkIsLittleEndian () {
  48862. var a = new ArrayBuffer(4);
  48863. var b = new Uint8Array(a);
  48864. var c = new Uint32Array(a);
  48865. b[0] = 0xa1;
  48866. b[1] = 0xb2;
  48867. b[2] = 0xc3;
  48868. b[3] = 0xd4;
  48869. if (c[0] == 0xd4c3b2a1)
  48870. {
  48871. return true;
  48872. }
  48873. if (c[0] == 0xa1b2c3d4)
  48874. {
  48875. return false;
  48876. }
  48877. else
  48878. {
  48879. // Could not determine endianness
  48880. return null;
  48881. }
  48882. }
  48883. /**
  48884. * Test to see if ImageData uses CanvasPixelArray or Uint8ClampedArray.
  48885. *
  48886. * @author Matt DesLauriers (@mattdesl)
  48887. */
  48888. function _checkIsUint8ClampedImageData () {
  48889. if (Uint8ClampedArray === undefined)
  48890. {
  48891. return false;
  48892. }
  48893. var elem = PIXI.CanvasPool.create(this, 1, 1);
  48894. var ctx = elem.getContext('2d');
  48895. if (!ctx)
  48896. {
  48897. return false;
  48898. }
  48899. var image = ctx.createImageData(1, 1);
  48900. PIXI.CanvasPool.remove(this);
  48901. return image.data instanceof Uint8ClampedArray;
  48902. }
  48903. /**
  48904. * Check whether the host environment support 3D CSS.
  48905. */
  48906. function _checkCSS3D () {
  48907. var el = document.createElement('p');
  48908. var has3d;
  48909. var transforms = {
  48910. 'webkitTransform': '-webkit-transform',
  48911. 'OTransform': '-o-transform',
  48912. 'msTransform': '-ms-transform',
  48913. 'MozTransform': '-moz-transform',
  48914. 'transform': 'transform'
  48915. };
  48916. // Add it to the body to get the computed style.
  48917. document.body.insertBefore(el, null);
  48918. for (var t in transforms)
  48919. {
  48920. if (el.style[t] !== undefined)
  48921. {
  48922. el.style[t] = "translate3d(1px,1px,1px)";
  48923. has3d = window.getComputedStyle(el).getPropertyValue(transforms[t]);
  48924. }
  48925. }
  48926. document.body.removeChild(el);
  48927. device.css3D = (has3d !== undefined && has3d.length > 0 && has3d !== "none");
  48928. }
  48929. // Run the checks
  48930. _checkOS();
  48931. _checkBrowser();
  48932. _checkAudio();
  48933. _checkVideo();
  48934. _checkCSS3D();
  48935. _checkDevice();
  48936. _checkFeatures();
  48937. _checkFullScreenSupport();
  48938. _checkInput();
  48939. };
  48940. /**
  48941. * Check whether the host environment can play audio.
  48942. *
  48943. * @method canPlayAudio
  48944. * @memberof Phaser.Device.prototype
  48945. * @param {string} type - One of 'mp3, 'ogg', 'm4a', 'wav', 'webm' or 'opus'.
  48946. * @return {boolean} True if the given file type is supported by the browser, otherwise false.
  48947. */
  48948. Phaser.Device.canPlayAudio = function (type) {
  48949. if (type === 'mp3' && this.mp3)
  48950. {
  48951. return true;
  48952. }
  48953. else if (type === 'ogg' && (this.ogg || this.opus))
  48954. {
  48955. return true;
  48956. }
  48957. else if (type === 'm4a' && this.m4a)
  48958. {
  48959. return true;
  48960. }
  48961. else if (type === 'opus' && this.opus)
  48962. {
  48963. return true;
  48964. }
  48965. else if (type === 'wav' && this.wav)
  48966. {
  48967. return true;
  48968. }
  48969. else if (type === 'webm' && this.webm)
  48970. {
  48971. return true;
  48972. }
  48973. else if (type === 'mp4' && this.dolby)
  48974. {
  48975. return true;
  48976. }
  48977. return false;
  48978. };
  48979. /**
  48980. * Check whether the host environment can play video files.
  48981. *
  48982. * @method canPlayVideo
  48983. * @memberof Phaser.Device.prototype
  48984. * @param {string} type - One of 'mp4, 'ogg', 'webm' or 'mpeg'.
  48985. * @return {boolean} True if the given file type is supported by the browser, otherwise false.
  48986. */
  48987. Phaser.Device.canPlayVideo = function (type) {
  48988. if (type === 'webm' && (this.webmVideo || this.vp9Video))
  48989. {
  48990. return true;
  48991. }
  48992. else if (type === 'mp4' && (this.mp4Video || this.h264Video))
  48993. {
  48994. return true;
  48995. }
  48996. else if ((type === 'ogg' || type === 'ogv') && this.oggVideo)
  48997. {
  48998. return true;
  48999. }
  49000. else if (type === 'mpeg' && this.hlsVideo)
  49001. {
  49002. return true;
  49003. }
  49004. return false;
  49005. };
  49006. /**
  49007. * Check whether the console is open.
  49008. * Note that this only works in Firefox with Firebug and earlier versions of Chrome.
  49009. * It used to work in Chrome, but then they removed the ability: {@link http://src.chromium.org/viewvc/blink?view=revision&revision=151136}
  49010. *
  49011. * @method isConsoleOpen
  49012. * @memberof Phaser.Device.prototype
  49013. */
  49014. Phaser.Device.isConsoleOpen = function () {
  49015. if (window.console && window.console['firebug'])
  49016. {
  49017. return true;
  49018. }
  49019. if (window.console)
  49020. {
  49021. console.profile();
  49022. console.profileEnd();
  49023. if (console.clear)
  49024. {
  49025. console.clear();
  49026. }
  49027. if (console['profiles'])
  49028. {
  49029. return console['profiles'].length > 0;
  49030. }
  49031. }
  49032. return false;
  49033. };
  49034. /**
  49035. * Detect if the host is a an Android Stock browser.
  49036. * This is available before the device "ready" event.
  49037. *
  49038. * Authors might want to scale down on effects and switch to the CANVAS rendering method on those devices.
  49039. *
  49040. * @example
  49041. * var defaultRenderingMode = Phaser.Device.isAndroidStockBrowser() ? Phaser.CANVAS : Phaser.AUTO;
  49042. *
  49043. * @method isAndroidStockBrowser
  49044. * @memberof Phaser.Device.prototype
  49045. */
  49046. Phaser.Device.isAndroidStockBrowser = function () {
  49047. var matches = window.navigator.userAgent.match(/Android.*AppleWebKit\/([\d.]+)/);
  49048. return matches && matches[1] < 537;
  49049. };
  49050. /**
  49051. * @author Richard Davey <rich@photonstorm.com>
  49052. * @copyright 2016 Photon Storm Ltd.
  49053. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  49054. */
  49055. /**
  49056. * The Canvas class handles everything related to creating the `canvas` DOM tag that Phaser will use,
  49057. * including styles, offset and aspect ratio.
  49058. *
  49059. * @class Phaser.Canvas
  49060. * @static
  49061. */
  49062. Phaser.Canvas = {
  49063. /**
  49064. * Creates a `canvas` DOM element. The element is not automatically added to the document.
  49065. *
  49066. * @method Phaser.Canvas.create
  49067. * @param {object} parent - The object that will own the canvas that is created.
  49068. * @param {number} [width=256] - The width of the canvas element.
  49069. * @param {number} [height=256] - The height of the canvas element..
  49070. * @param {string} [id=(none)] - If specified, and not the empty string, this will be set as the ID of the canvas element. Otherwise no ID will be set.
  49071. * @param {boolean} [skipPool=false] - If `true` the canvas will not be placed in the CanvasPool global.
  49072. * @return {HTMLCanvasElement} The newly created canvas element.
  49073. */
  49074. create: function (parent, width, height, id, skipPool) {
  49075. width = width || 256;
  49076. height = height || 256;
  49077. if (skipPool === undefined)
  49078. {
  49079. var canvas = PIXI.CanvasPool.create(parent, width, height);
  49080. }
  49081. else
  49082. {
  49083. var canvas = document.createElement('canvas');
  49084. }
  49085. if (typeof id === 'string' && id !== '')
  49086. {
  49087. canvas.id = id;
  49088. }
  49089. canvas.width = width;
  49090. canvas.height = height;
  49091. canvas.style.display = 'block';
  49092. return canvas;
  49093. },
  49094. /**
  49095. * Sets the background color behind the canvas. This changes the canvas style property.
  49096. *
  49097. * @method Phaser.Canvas.setBackgroundColor
  49098. * @param {HTMLCanvasElement} canvas - The canvas to set the background color on.
  49099. * @param {string} [color='rgb(0,0,0)'] - The color to set. Can be in the format 'rgb(r,g,b)', or '#RRGGBB' or any valid CSS color.
  49100. * @return {HTMLCanvasElement} Returns the source canvas.
  49101. */
  49102. setBackgroundColor: function (canvas, color) {
  49103. color = color || 'rgb(0,0,0)';
  49104. canvas.style.backgroundColor = color;
  49105. return canvas;
  49106. },
  49107. /**
  49108. * Sets the touch-action property on the canvas style. Can be used to disable default browser touch actions.
  49109. *
  49110. * @method Phaser.Canvas.setTouchAction
  49111. * @param {HTMLCanvasElement} canvas - The canvas to set the touch action on.
  49112. * @param {string} [value] - The touch action to set. Defaults to 'none'.
  49113. * @return {HTMLCanvasElement} The source canvas.
  49114. */
  49115. setTouchAction: function (canvas, value) {
  49116. value = value || 'none';
  49117. canvas.style.msTouchAction = value;
  49118. canvas.style['ms-touch-action'] = value;
  49119. canvas.style['touch-action'] = value;
  49120. return canvas;
  49121. },
  49122. /**
  49123. * Sets the user-select property on the canvas style. Can be used to disable default browser selection actions.
  49124. *
  49125. * @method Phaser.Canvas.setUserSelect
  49126. * @param {HTMLCanvasElement} canvas - The canvas to set the touch action on.
  49127. * @param {string} [value] - The touch action to set. Defaults to 'none'.
  49128. * @return {HTMLCanvasElement} The source canvas.
  49129. */
  49130. setUserSelect: function (canvas, value) {
  49131. value = value || 'none';
  49132. canvas.style['-webkit-touch-callout'] = value;
  49133. canvas.style['-webkit-user-select'] = value;
  49134. canvas.style['-khtml-user-select'] = value;
  49135. canvas.style['-moz-user-select'] = value;
  49136. canvas.style['-ms-user-select'] = value;
  49137. canvas.style['user-select'] = value;
  49138. canvas.style['-webkit-tap-highlight-color'] = 'rgba(0, 0, 0, 0)';
  49139. return canvas;
  49140. },
  49141. /**
  49142. * Adds the given canvas element to the DOM. The canvas will be added as a child of the given parent.
  49143. * If no parent is given it will be added as a child of the document.body.
  49144. *
  49145. * @method Phaser.Canvas.addToDOM
  49146. * @param {HTMLCanvasElement} canvas - The canvas to be added to the DOM.
  49147. * @param {string|HTMLElement} parent - The DOM element to add the canvas to.
  49148. * @param {boolean} [overflowHidden=true] - If set to true it will add the overflow='hidden' style to the parent DOM element.
  49149. * @return {HTMLCanvasElement} Returns the source canvas.
  49150. */
  49151. addToDOM: function (canvas, parent, overflowHidden) {
  49152. var target;
  49153. if (overflowHidden === undefined) { overflowHidden = true; }
  49154. if (parent)
  49155. {
  49156. if (typeof parent === 'string')
  49157. {
  49158. // hopefully an element ID
  49159. target = document.getElementById(parent);
  49160. }
  49161. else if (typeof parent === 'object' && parent.nodeType === 1)
  49162. {
  49163. // quick test for a HTMLelement
  49164. target = parent;
  49165. }
  49166. }
  49167. // Fallback, covers an invalid ID and a non HTMLelement object
  49168. if (!target)
  49169. {
  49170. target = document.body;
  49171. }
  49172. if (overflowHidden && target.style)
  49173. {
  49174. target.style.overflow = 'hidden';
  49175. }
  49176. target.appendChild(canvas);
  49177. return canvas;
  49178. },
  49179. /**
  49180. * Removes the given canvas element from the DOM.
  49181. *
  49182. * @method Phaser.Canvas.removeFromDOM
  49183. * @param {HTMLCanvasElement} canvas - The canvas to be removed from the DOM.
  49184. */
  49185. removeFromDOM: function (canvas) {
  49186. if (canvas.parentNode)
  49187. {
  49188. canvas.parentNode.removeChild(canvas);
  49189. }
  49190. },
  49191. /**
  49192. * Sets the transform of the given canvas to the matrix values provided.
  49193. *
  49194. * @method Phaser.Canvas.setTransform
  49195. * @param {CanvasRenderingContext2D} context - The context to set the transform on.
  49196. * @param {number} translateX - The value to translate horizontally by.
  49197. * @param {number} translateY - The value to translate vertically by.
  49198. * @param {number} scaleX - The value to scale horizontally by.
  49199. * @param {number} scaleY - The value to scale vertically by.
  49200. * @param {number} skewX - The value to skew horizontaly by.
  49201. * @param {number} skewY - The value to skew vertically by.
  49202. * @return {CanvasRenderingContext2D} Returns the source context.
  49203. */
  49204. setTransform: function (context, translateX, translateY, scaleX, scaleY, skewX, skewY) {
  49205. context.setTransform(scaleX, skewX, skewY, scaleY, translateX, translateY);
  49206. return context;
  49207. },
  49208. /**
  49209. * Sets the Image Smoothing property on the given context. Set to false to disable image smoothing.
  49210. * By default browsers have image smoothing enabled, which isn't always what you visually want, especially
  49211. * when using pixel art in a game. Note that this sets the property on the context itself, so that any image
  49212. * drawn to the context will be affected. This sets the property across all current browsers but support is
  49213. * patchy on earlier browsers, especially on mobile.
  49214. *
  49215. * @method Phaser.Canvas.setSmoothingEnabled
  49216. * @param {CanvasRenderingContext2D} context - The context to enable or disable the image smoothing on.
  49217. * @param {boolean} value - If set to true it will enable image smoothing, false will disable it.
  49218. * @return {CanvasRenderingContext2D} Returns the source context.
  49219. */
  49220. setSmoothingEnabled: function (context, value) {
  49221. var s = Phaser.Canvas.getSmoothingPrefix(context);
  49222. if (s)
  49223. {
  49224. context[s] = value;
  49225. }
  49226. return context;
  49227. },
  49228. /**
  49229. * Gets the Smoothing Enabled vendor prefix being used on the given context, or null if not set.
  49230. *
  49231. * @method Phaser.Canvas.getSmoothingPrefix
  49232. * @param {CanvasRenderingContext2D} context - The context to enable or disable the image smoothing on.
  49233. * @return {string|null} Returns the smoothingEnabled vendor prefix, or null if not set on the context.
  49234. */
  49235. getSmoothingPrefix: function (context) {
  49236. var vendor = [ 'i', 'webkitI', 'msI', 'mozI', 'oI' ];
  49237. for (var prefix in vendor)
  49238. {
  49239. var s = vendor[prefix] + 'mageSmoothingEnabled';
  49240. if (s in context)
  49241. {
  49242. return s;
  49243. }
  49244. }
  49245. return null;
  49246. },
  49247. /**
  49248. * Returns `true` if the given context has image smoothing enabled, otherwise returns `false`.
  49249. *
  49250. * @method Phaser.Canvas.getSmoothingEnabled
  49251. * @param {CanvasRenderingContext2D} context - The context to check for smoothing on.
  49252. * @return {boolean} True if the given context has image smoothing enabled, otherwise false.
  49253. */
  49254. getSmoothingEnabled: function (context) {
  49255. var s = Phaser.Canvas.getSmoothingPrefix(context);
  49256. if (s)
  49257. {
  49258. return context[s];
  49259. }
  49260. },
  49261. /**
  49262. * Sets the CSS image-rendering property on the given canvas to be 'crisp' (aka 'optimize contrast' on webkit).
  49263. * Note that if this doesn't given the desired result then see the setSmoothingEnabled.
  49264. *
  49265. * @method Phaser.Canvas.setImageRenderingCrisp
  49266. * @param {HTMLCanvasElement} canvas - The canvas to set image-rendering crisp on.
  49267. * @return {HTMLCanvasElement} Returns the source canvas.
  49268. */
  49269. setImageRenderingCrisp: function (canvas) {
  49270. var types = [ 'optimizeSpeed', 'crisp-edges', '-moz-crisp-edges', '-webkit-optimize-contrast', 'optimize-contrast', 'pixelated' ];
  49271. for (var i = 0; i < types.length; i++)
  49272. {
  49273. canvas.style['image-rendering'] = types[i];
  49274. }
  49275. canvas.style.msInterpolationMode = 'nearest-neighbor';
  49276. return canvas;
  49277. },
  49278. /**
  49279. * Sets the CSS image-rendering property on the given canvas to be 'bicubic' (aka 'auto').
  49280. * Note that if this doesn't given the desired result then see the CanvasUtils.setSmoothingEnabled method.
  49281. *
  49282. * @method Phaser.Canvas.setImageRenderingBicubic
  49283. * @param {HTMLCanvasElement} canvas The canvas to set image-rendering bicubic on.
  49284. * @return {HTMLCanvasElement} Returns the source canvas.
  49285. */
  49286. setImageRenderingBicubic: function (canvas) {
  49287. canvas.style['image-rendering'] = 'auto';
  49288. canvas.style.msInterpolationMode = 'bicubic';
  49289. return canvas;
  49290. }
  49291. };
  49292. /**
  49293. * @author Richard Davey <rich@photonstorm.com>
  49294. * @copyright 2016 Photon Storm Ltd.
  49295. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  49296. */
  49297. /**
  49298. * Abstracts away the use of RAF or setTimeOut for the core game update loop.
  49299. *
  49300. * @class Phaser.RequestAnimationFrame
  49301. * @constructor
  49302. * @param {Phaser.Game} game - A reference to the currently running game.
  49303. * @param {boolean} [forceSetTimeOut=false] - Tell Phaser to use setTimeOut even if raf is available.
  49304. */
  49305. Phaser.RequestAnimationFrame = function(game, forceSetTimeOut) {
  49306. if (forceSetTimeOut === undefined) { forceSetTimeOut = false; }
  49307. /**
  49308. * @property {Phaser.Game} game - The currently running game.
  49309. */
  49310. this.game = game;
  49311. /**
  49312. * @property {boolean} isRunning - true if RequestAnimationFrame is running, otherwise false.
  49313. * @default
  49314. */
  49315. this.isRunning = false;
  49316. /**
  49317. * @property {boolean} forceSetTimeOut - Tell Phaser to use setTimeOut even if raf is available.
  49318. */
  49319. this.forceSetTimeOut = forceSetTimeOut;
  49320. var vendors = [
  49321. 'ms',
  49322. 'moz',
  49323. 'webkit',
  49324. 'o'
  49325. ];
  49326. for (var x = 0; x < vendors.length && !window.requestAnimationFrame; x++)
  49327. {
  49328. window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
  49329. window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'];
  49330. }
  49331. /**
  49332. * @property {boolean} _isSetTimeOut - true if the browser is using setTimeout instead of raf.
  49333. * @private
  49334. */
  49335. this._isSetTimeOut = false;
  49336. /**
  49337. * @property {function} _onLoop - The function called by the update.
  49338. * @private
  49339. */
  49340. this._onLoop = null;
  49341. /**
  49342. * @property {number} _timeOutID - The callback ID used when calling cancel.
  49343. * @private
  49344. */
  49345. this._timeOutID = null;
  49346. };
  49347. Phaser.RequestAnimationFrame.prototype = {
  49348. /**
  49349. * Starts the requestAnimationFrame running or setTimeout if unavailable in browser
  49350. * @method Phaser.RequestAnimationFrame#start
  49351. */
  49352. start: function () {
  49353. this.isRunning = true;
  49354. var _this = this;
  49355. if (!window.requestAnimationFrame || this.forceSetTimeOut)
  49356. {
  49357. this._isSetTimeOut = true;
  49358. this._onLoop = function () {
  49359. return _this.updateSetTimeout();
  49360. };
  49361. this._timeOutID = window.setTimeout(this._onLoop, 0);
  49362. }
  49363. else
  49364. {
  49365. this._isSetTimeOut = false;
  49366. this._onLoop = function (time) {
  49367. return _this.updateRAF(time);
  49368. };
  49369. this._timeOutID = window.requestAnimationFrame(this._onLoop);
  49370. }
  49371. },
  49372. /**
  49373. * The update method for the requestAnimationFrame
  49374. * @method Phaser.RequestAnimationFrame#updateRAF
  49375. *
  49376. */
  49377. updateRAF: function (rafTime) {
  49378. // floor the rafTime to make it equivalent to the Date.now() provided by updateSetTimeout (just below)
  49379. this.game.update(Math.floor(rafTime));
  49380. this._timeOutID = window.requestAnimationFrame(this._onLoop);
  49381. },
  49382. /**
  49383. * The update method for the setTimeout.
  49384. * @method Phaser.RequestAnimationFrame#updateSetTimeout
  49385. */
  49386. updateSetTimeout: function () {
  49387. this.game.update(Date.now());
  49388. this._timeOutID = window.setTimeout(this._onLoop, this.game.time.timeToCall);
  49389. },
  49390. /**
  49391. * Stops the requestAnimationFrame from running.
  49392. * @method Phaser.RequestAnimationFrame#stop
  49393. */
  49394. stop: function () {
  49395. if (this._isSetTimeOut)
  49396. {
  49397. clearTimeout(this._timeOutID);
  49398. }
  49399. else
  49400. {
  49401. window.cancelAnimationFrame(this._timeOutID);
  49402. }
  49403. this.isRunning = false;
  49404. },
  49405. /**
  49406. * Is the browser using setTimeout?
  49407. * @method Phaser.RequestAnimationFrame#isSetTimeOut
  49408. * @return {boolean}
  49409. */
  49410. isSetTimeOut: function () {
  49411. return this._isSetTimeOut;
  49412. },
  49413. /**
  49414. * Is the browser using requestAnimationFrame?
  49415. * @method Phaser.RequestAnimationFrame#isRAF
  49416. * @return {boolean}
  49417. */
  49418. isRAF: function () {
  49419. return (this._isSetTimeOut === false);
  49420. }
  49421. };
  49422. Phaser.RequestAnimationFrame.prototype.constructor = Phaser.RequestAnimationFrame;
  49423. /**
  49424. * @author Richard Davey <rich@photonstorm.com>
  49425. * @copyright 2016 Photon Storm Ltd.
  49426. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  49427. */
  49428. /**
  49429. * A collection of useful mathematical functions.
  49430. *
  49431. * These are normally accessed through `game.math`.
  49432. *
  49433. * @class Phaser.Math
  49434. * @static
  49435. * @see {@link Phaser.Utils}
  49436. * @see {@link Phaser.ArrayUtils}
  49437. */
  49438. Phaser.Math = {
  49439. /**
  49440. * Twice PI.
  49441. * @property {number} Phaser.Math#PI2
  49442. * @default ~6.283
  49443. */
  49444. PI2: Math.PI * 2,
  49445. /**
  49446. * Two number are fuzzyEqual if their difference is less than epsilon.
  49447. *
  49448. * @method Phaser.Math#fuzzyEqual
  49449. * @param {number} a - The first number to compare.
  49450. * @param {number} b - The second number to compare.
  49451. * @param {number} [epsilon=0.0001] - The epsilon (a small value used in the calculation)
  49452. * @return {boolean} True if |a-b|<epsilon
  49453. */
  49454. fuzzyEqual: function (a, b, epsilon) {
  49455. if (epsilon === undefined) { epsilon = 0.0001; }
  49456. return Math.abs(a - b) < epsilon;
  49457. },
  49458. /**
  49459. * `a` is fuzzyLessThan `b` if it is less than b + epsilon.
  49460. *
  49461. * @method Phaser.Math#fuzzyLessThan
  49462. * @param {number} a - The first number to compare.
  49463. * @param {number} b - The second number to compare.
  49464. * @param {number} [epsilon=0.0001] - The epsilon (a small value used in the calculation)
  49465. * @return {boolean} True if a<b+epsilon
  49466. */
  49467. fuzzyLessThan: function (a, b, epsilon) {
  49468. if (epsilon === undefined) { epsilon = 0.0001; }
  49469. return a < b + epsilon;
  49470. },
  49471. /**
  49472. * `a` is fuzzyGreaterThan `b` if it is more than b - epsilon.
  49473. *
  49474. * @method Phaser.Math#fuzzyGreaterThan
  49475. * @param {number} a - The first number to compare.
  49476. * @param {number} b - The second number to compare.
  49477. * @param {number} [epsilon=0.0001] - The epsilon (a small value used in the calculation)
  49478. * @return {boolean} True if a>b+epsilon
  49479. */
  49480. fuzzyGreaterThan: function (a, b, epsilon) {
  49481. if (epsilon === undefined) { epsilon = 0.0001; }
  49482. return a > b - epsilon;
  49483. },
  49484. /**
  49485. * Applies a fuzzy ceil to the given value.
  49486. *
  49487. * @method Phaser.Math#fuzzyCeil
  49488. * @param {number} val - The value to ceil.
  49489. * @param {number} [epsilon=0.0001] - The epsilon (a small value used in the calculation)
  49490. * @return {number} ceiling(val-epsilon)
  49491. */
  49492. fuzzyCeil: function (val, epsilon) {
  49493. if (epsilon === undefined) { epsilon = 0.0001; }
  49494. return Math.ceil(val - epsilon);
  49495. },
  49496. /**
  49497. * Applies a fuzzy floor to the given value.
  49498. *
  49499. * @method Phaser.Math#fuzzyFloor
  49500. * @param {number} val - The value to floor.
  49501. * @param {number} [epsilon=0.0001] - The epsilon (a small value used in the calculation)
  49502. * @return {number} floor(val+epsilon)
  49503. */
  49504. fuzzyFloor: function (val, epsilon) {
  49505. if (epsilon === undefined) { epsilon = 0.0001; }
  49506. return Math.floor(val + epsilon);
  49507. },
  49508. /**
  49509. * Averages all values passed to the function and returns the result.
  49510. *
  49511. * @method Phaser.Math#average
  49512. * @params {...number} The numbers to average
  49513. * @return {number} The average of all given values.
  49514. */
  49515. average: function () {
  49516. var sum = 0;
  49517. var len = arguments.length;
  49518. for (var i = 0; i < len; i++)
  49519. {
  49520. sum += (+arguments[i]);
  49521. }
  49522. return sum / len;
  49523. },
  49524. /**
  49525. * @method Phaser.Math#shear
  49526. * @param {number} n
  49527. * @return {number} n mod 1
  49528. */
  49529. shear: function (n) {
  49530. return n % 1;
  49531. },
  49532. /**
  49533. * Snap a value to nearest grid slice, using rounding.
  49534. *
  49535. * 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.
  49536. *
  49537. * @method Phaser.Math#snapTo
  49538. * @param {number} input - The value to snap.
  49539. * @param {number} gap - The interval gap of the grid.
  49540. * @param {number} [start] - Optional starting offset for gap.
  49541. * @return {number}
  49542. */
  49543. snapTo: function (input, gap, start) {
  49544. if (start === undefined) { start = 0; }
  49545. if (gap === 0) {
  49546. return input;
  49547. }
  49548. input -= start;
  49549. input = gap * Math.round(input / gap);
  49550. return start + input;
  49551. },
  49552. /**
  49553. * Snap a value to nearest grid slice, using floor.
  49554. *
  49555. * Example: if you have an interval gap of 5 and a position of 12... you will snap to 10.
  49556. * As will 14 snap to 10... but 16 will snap to 15.
  49557. *
  49558. * @method Phaser.Math#snapToFloor
  49559. * @param {number} input - The value to snap.
  49560. * @param {number} gap - The interval gap of the grid.
  49561. * @param {number} [start] - Optional starting offset for gap.
  49562. * @return {number}
  49563. */
  49564. snapToFloor: function (input, gap, start) {
  49565. if (start === undefined) { start = 0; }
  49566. if (gap === 0) {
  49567. return input;
  49568. }
  49569. input -= start;
  49570. input = gap * Math.floor(input / gap);
  49571. return start + input;
  49572. },
  49573. /**
  49574. * Snap a value to nearest grid slice, using ceil.
  49575. *
  49576. * Example: if you have an interval gap of 5 and a position of 12... you will snap to 15.
  49577. * As will 14 will snap to 15... but 16 will snap to 20.
  49578. *
  49579. * @method Phaser.Math#snapToCeil
  49580. * @param {number} input - The value to snap.
  49581. * @param {number} gap - The interval gap of the grid.
  49582. * @param {number} [start] - Optional starting offset for gap.
  49583. * @return {number}
  49584. */
  49585. snapToCeil: function (input, gap, start) {
  49586. if (start === undefined) { start = 0; }
  49587. if (gap === 0) {
  49588. return input;
  49589. }
  49590. input -= start;
  49591. input = gap * Math.ceil(input / gap);
  49592. return start + input;
  49593. },
  49594. /**
  49595. * Round to some place comparative to a `base`, default is 10 for decimal place.
  49596. * The `place` is represented by the power applied to `base` to get that place.
  49597. *
  49598. * e.g. 2000/7 ~= 285.714285714285714285714 ~= (bin)100011101.1011011011011011
  49599. *
  49600. * roundTo(2000/7,3) === 0
  49601. * roundTo(2000/7,2) == 300
  49602. * roundTo(2000/7,1) == 290
  49603. * roundTo(2000/7,0) == 286
  49604. * roundTo(2000/7,-1) == 285.7
  49605. * roundTo(2000/7,-2) == 285.71
  49606. * roundTo(2000/7,-3) == 285.714
  49607. * roundTo(2000/7,-4) == 285.7143
  49608. * roundTo(2000/7,-5) == 285.71429
  49609. *
  49610. * roundTo(2000/7,3,2) == 288 -- 100100000
  49611. * roundTo(2000/7,2,2) == 284 -- 100011100
  49612. * roundTo(2000/7,1,2) == 286 -- 100011110
  49613. * roundTo(2000/7,0,2) == 286 -- 100011110
  49614. * roundTo(2000/7,-1,2) == 285.5 -- 100011101.1
  49615. * roundTo(2000/7,-2,2) == 285.75 -- 100011101.11
  49616. * roundTo(2000/7,-3,2) == 285.75 -- 100011101.11
  49617. * roundTo(2000/7,-4,2) == 285.6875 -- 100011101.1011
  49618. * roundTo(2000/7,-5,2) == 285.71875 -- 100011101.10111
  49619. *
  49620. * Note what occurs when we round to the 3rd space (8ths place), 100100000, this is to be assumed
  49621. * because we are rounding 100011.1011011011011011 which rounds up.
  49622. *
  49623. * @method Phaser.Math#roundTo
  49624. * @param {number} value - The value to round.
  49625. * @param {number} place - The place to round to.
  49626. * @param {number} base - The base to round in... default is 10 for decimal.
  49627. * @return {number}
  49628. */
  49629. roundTo: function (value, place, base) {
  49630. if (place === undefined) { place = 0; }
  49631. if (base === undefined) { base = 10; }
  49632. var p = Math.pow(base, -place);
  49633. return Math.round(value * p) / p;
  49634. },
  49635. /**
  49636. * @method Phaser.Math#floorTo
  49637. * @param {number} value - The value to round.
  49638. * @param {number} place - The place to round to.
  49639. * @param {number} base - The base to round in... default is 10 for decimal.
  49640. * @return {number}
  49641. */
  49642. floorTo: function (value, place, base) {
  49643. if (place === undefined) { place = 0; }
  49644. if (base === undefined) { base = 10; }
  49645. var p = Math.pow(base, -place);
  49646. return Math.floor(value * p) / p;
  49647. },
  49648. /**
  49649. * @method Phaser.Math#ceilTo
  49650. * @param {number} value - The value to round.
  49651. * @param {number} place - The place to round to.
  49652. * @param {number} base - The base to round in... default is 10 for decimal.
  49653. * @return {number}
  49654. */
  49655. ceilTo: function (value, place, base) {
  49656. if (place === undefined) { place = 0; }
  49657. if (base === undefined) { base = 10; }
  49658. var p = Math.pow(base, -place);
  49659. return Math.ceil(value * p) / p;
  49660. },
  49661. /**
  49662. * Find the angle of a segment from (x1, y1) -> (x2, y2).
  49663. * @method Phaser.Math#angleBetween
  49664. * @param {number} x1
  49665. * @param {number} y1
  49666. * @param {number} x2
  49667. * @param {number} y2
  49668. * @return {number} The angle, in radians.
  49669. */
  49670. angleBetween: function (x1, y1, x2, y2) {
  49671. return Math.atan2(y2 - y1, x2 - x1);
  49672. },
  49673. /**
  49674. * Find the angle of a segment from (x1, y1) -> (x2, y2).
  49675. * Note that the difference between this method and Math.angleBetween is that this assumes the y coordinate travels
  49676. * down the screen.
  49677. *
  49678. * @method Phaser.Math#angleBetweenY
  49679. * @param {number} x1
  49680. * @param {number} y1
  49681. * @param {number} x2
  49682. * @param {number} y2
  49683. * @return {number} The angle, in radians.
  49684. */
  49685. angleBetweenY: function (x1, y1, x2, y2) {
  49686. return Math.atan2(x2 - x1, y2 - y1);
  49687. },
  49688. /**
  49689. * Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y).
  49690. * @method Phaser.Math#angleBetweenPoints
  49691. * @param {Phaser.Point} point1
  49692. * @param {Phaser.Point} point2
  49693. * @return {number} The angle, in radians.
  49694. */
  49695. angleBetweenPoints: function (point1, point2) {
  49696. return Math.atan2(point2.y - point1.y, point2.x - point1.x);
  49697. },
  49698. /**
  49699. * Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y).
  49700. * @method Phaser.Math#angleBetweenPointsY
  49701. * @param {Phaser.Point} point1
  49702. * @param {Phaser.Point} point2
  49703. * @return {number} The angle, in radians.
  49704. */
  49705. angleBetweenPointsY: function (point1, point2) {
  49706. return Math.atan2(point2.x - point1.x, point2.y - point1.y);
  49707. },
  49708. /**
  49709. * Reverses an angle.
  49710. * @method Phaser.Math#reverseAngle
  49711. * @param {number} angleRad - The angle to reverse, in radians.
  49712. * @return {number} Returns the reverse angle, in radians.
  49713. */
  49714. reverseAngle: function (angleRad) {
  49715. return this.normalizeAngle(angleRad + Math.PI, true);
  49716. },
  49717. /**
  49718. * Normalizes an angle to the [0,2pi) range.
  49719. * @method Phaser.Math#normalizeAngle
  49720. * @param {number} angleRad - The angle to normalize, in radians.
  49721. * @return {number} Returns the angle, fit within the [0,2pi] range, in radians.
  49722. */
  49723. normalizeAngle: function (angleRad) {
  49724. angleRad = angleRad % (2 * Math.PI);
  49725. return angleRad >= 0 ? angleRad : angleRad + 2 * Math.PI;
  49726. },
  49727. /**
  49728. * Adds the given amount to the value, but never lets the value go over the specified maximum.
  49729. *
  49730. * @method Phaser.Math#maxAdd
  49731. * @param {number} value - The value to add the amount to.
  49732. * @param {number} amount - The amount to add to the value.
  49733. * @param {number} max - The maximum the value is allowed to be.
  49734. * @return {number}
  49735. */
  49736. maxAdd: function (value, amount, max) {
  49737. return Math.min(value + amount, max);
  49738. },
  49739. /**
  49740. * Subtracts the given amount from the value, but never lets the value go below the specified minimum.
  49741. *
  49742. * @method Phaser.Math#minSub
  49743. * @param {number} value - The base value.
  49744. * @param {number} amount - The amount to subtract from the base value.
  49745. * @param {number} min - The minimum the value is allowed to be.
  49746. * @return {number} The new value.
  49747. */
  49748. minSub: function (value, amount, min) {
  49749. return Math.max(value - amount, min);
  49750. },
  49751. /**
  49752. * Ensures that the value always stays between min and max, by wrapping the value around.
  49753. *
  49754. * If `max` is not larger than `min` the result is 0.
  49755. *
  49756. * @method Phaser.Math#wrap
  49757. * @param {number} value - The value to wrap.
  49758. * @param {number} min - The minimum the value is allowed to be.
  49759. * @param {number} max - The maximum the value is allowed to be, should be larger than `min`.
  49760. * @return {number} The wrapped value.
  49761. */
  49762. wrap: function (value, min, max) {
  49763. var range = max - min;
  49764. if (range <= 0)
  49765. {
  49766. return 0;
  49767. }
  49768. var result = (value - min) % range;
  49769. if (result < 0)
  49770. {
  49771. result += range;
  49772. }
  49773. return result + min;
  49774. },
  49775. /**
  49776. * Adds value to amount and ensures that the result always stays between 0 and max, by wrapping the value around.
  49777. *
  49778. * Values _must_ be positive integers, and are passed through Math.abs. See {@link Phaser.Math#wrap} for an alternative.
  49779. *
  49780. * @method Phaser.Math#wrapValue
  49781. * @param {number} value - The value to add the amount to.
  49782. * @param {number} amount - The amount to add to the value.
  49783. * @param {number} max - The maximum the value is allowed to be.
  49784. * @return {number} The wrapped value.
  49785. */
  49786. wrapValue: function (value, amount, max) {
  49787. var diff;
  49788. value = Math.abs(value);
  49789. amount = Math.abs(amount);
  49790. max = Math.abs(max);
  49791. diff = (value + amount) % max;
  49792. return diff;
  49793. },
  49794. /**
  49795. * Returns true if the number given is odd.
  49796. *
  49797. * @method Phaser.Math#isOdd
  49798. * @param {integer} n - The number to check.
  49799. * @return {boolean} True if the given number is odd. False if the given number is even.
  49800. */
  49801. isOdd: function (n) {
  49802. // Does not work with extremely large values
  49803. return !!(n & 1);
  49804. },
  49805. /**
  49806. * Returns true if the number given is even.
  49807. *
  49808. * @method Phaser.Math#isEven
  49809. * @param {integer} n - The number to check.
  49810. * @return {boolean} True if the given number is even. False if the given number is odd.
  49811. */
  49812. isEven: function (n) {
  49813. // Does not work with extremely large values
  49814. return !(n & 1);
  49815. },
  49816. /**
  49817. * Variation of Math.min that can be passed either an array of numbers or the numbers as parameters.
  49818. *
  49819. * Prefer the standard `Math.min` function when appropriate.
  49820. *
  49821. * @method Phaser.Math#min
  49822. * @return {number} The lowest value from those given.
  49823. * @see {@link http://jsperf.com/math-s-min-max-vs-homemade}
  49824. */
  49825. min: function () {
  49826. if (arguments.length === 1 && typeof arguments[0] === 'object')
  49827. {
  49828. var data = arguments[0];
  49829. }
  49830. else
  49831. {
  49832. var data = arguments;
  49833. }
  49834. for (var i = 1, min = 0, len = data.length; i < len; i++)
  49835. {
  49836. if (data[i] < data[min])
  49837. {
  49838. min = i;
  49839. }
  49840. }
  49841. return data[min];
  49842. },
  49843. /**
  49844. * Variation of Math.max that can be passed either an array of numbers or the numbers as parameters.
  49845. *
  49846. * Prefer the standard `Math.max` function when appropriate.
  49847. *
  49848. * @method Phaser.Math#max
  49849. * @return {number} The largest value from those given.
  49850. * @see {@link http://jsperf.com/math-s-min-max-vs-homemade}
  49851. */
  49852. max: function () {
  49853. if (arguments.length === 1 && typeof arguments[0] === 'object')
  49854. {
  49855. var data = arguments[0];
  49856. }
  49857. else
  49858. {
  49859. var data = arguments;
  49860. }
  49861. for (var i = 1, max = 0, len = data.length; i < len; i++)
  49862. {
  49863. if (data[i] > data[max])
  49864. {
  49865. max = i;
  49866. }
  49867. }
  49868. return data[max];
  49869. },
  49870. /**
  49871. * Variation of Math.min that can be passed a property and either an array of objects or the objects as parameters.
  49872. * It will find the lowest matching property value from the given objects.
  49873. *
  49874. * @method Phaser.Math#minProperty
  49875. * @return {number} The lowest value from those given.
  49876. */
  49877. minProperty: function (property) {
  49878. if (arguments.length === 2 && typeof arguments[1] === 'object')
  49879. {
  49880. var data = arguments[1];
  49881. }
  49882. else
  49883. {
  49884. var data = arguments.slice(1);
  49885. }
  49886. for (var i = 1, min = 0, len = data.length; i < len; i++)
  49887. {
  49888. if (data[i][property] < data[min][property])
  49889. {
  49890. min = i;
  49891. }
  49892. }
  49893. return data[min][property];
  49894. },
  49895. /**
  49896. * Variation of Math.max that can be passed a property and either an array of objects or the objects as parameters.
  49897. * It will find the largest matching property value from the given objects.
  49898. *
  49899. * @method Phaser.Math#maxProperty
  49900. * @return {number} The largest value from those given.
  49901. */
  49902. maxProperty: function (property) {
  49903. if (arguments.length === 2 && typeof arguments[1] === 'object')
  49904. {
  49905. var data = arguments[1];
  49906. }
  49907. else
  49908. {
  49909. var data = arguments.slice(1);
  49910. }
  49911. for (var i = 1, max = 0, len = data.length; i < len; i++)
  49912. {
  49913. if (data[i][property] > data[max][property])
  49914. {
  49915. max = i;
  49916. }
  49917. }
  49918. return data[max][property];
  49919. },
  49920. /**
  49921. * Keeps an angle value between -180 and +180; or -PI and PI if radians.
  49922. *
  49923. * @method Phaser.Math#wrapAngle
  49924. * @param {number} angle - The angle value to wrap
  49925. * @param {boolean} [radians=false] - Set to `true` if the angle is given in radians, otherwise degrees is expected.
  49926. * @return {number} The new angle value; will be the same as the input angle if it was within bounds.
  49927. */
  49928. wrapAngle: function (angle, radians) {
  49929. return radians ? this.wrap(angle, -Math.PI, Math.PI) : this.wrap(angle, -180, 180);
  49930. },
  49931. /**
  49932. * A Linear Interpolation Method, mostly used by Phaser.Tween.
  49933. *
  49934. * @method Phaser.Math#linearInterpolation
  49935. * @param {Array} v - The input array of values to interpolate between.
  49936. * @param {number} k - The percentage of interpolation, between 0 and 1.
  49937. * @return {number} The interpolated value
  49938. */
  49939. linearInterpolation: function (v, k) {
  49940. var m = v.length - 1;
  49941. var f = m * k;
  49942. var i = Math.floor(f);
  49943. if (k < 0)
  49944. {
  49945. return this.linear(v[0], v[1], f);
  49946. }
  49947. if (k > 1)
  49948. {
  49949. return this.linear(v[m], v[m - 1], m - f);
  49950. }
  49951. return this.linear(v[i], v[i + 1 > m ? m : i + 1], f - i);
  49952. },
  49953. /**
  49954. * A Bezier Interpolation Method, mostly used by Phaser.Tween.
  49955. *
  49956. * @method Phaser.Math#bezierInterpolation
  49957. * @param {Array} v - The input array of values to interpolate between.
  49958. * @param {number} k - The percentage of interpolation, between 0 and 1.
  49959. * @return {number} The interpolated value
  49960. */
  49961. bezierInterpolation: function (v, k) {
  49962. var b = 0;
  49963. var n = v.length - 1;
  49964. for (var i = 0; i <= n; i++)
  49965. {
  49966. b += Math.pow(1 - k, n - i) * Math.pow(k, i) * v[i] * this.bernstein(n, i);
  49967. }
  49968. return b;
  49969. },
  49970. /**
  49971. * A Catmull Rom Interpolation Method, mostly used by Phaser.Tween.
  49972. *
  49973. * @method Phaser.Math#catmullRomInterpolation
  49974. * @param {Array} v - The input array of values to interpolate between.
  49975. * @param {number} k - The percentage of interpolation, between 0 and 1.
  49976. * @return {number} The interpolated value
  49977. */
  49978. catmullRomInterpolation: function (v, k) {
  49979. var m = v.length - 1;
  49980. var f = m * k;
  49981. var i = Math.floor(f);
  49982. if (v[0] === v[m])
  49983. {
  49984. if (k < 0)
  49985. {
  49986. i = Math.floor(f = m * (1 + k));
  49987. }
  49988. return this.catmullRom(v[(i - 1 + m) % m], v[i], v[(i + 1) % m], v[(i + 2) % m], f - i);
  49989. }
  49990. else
  49991. {
  49992. if (k < 0)
  49993. {
  49994. return v[0] - (this.catmullRom(v[0], v[0], v[1], v[1], -f) - v[0]);
  49995. }
  49996. if (k > 1)
  49997. {
  49998. return v[m] - (this.catmullRom(v[m], v[m], v[m - 1], v[m - 1], f - m) - v[m]);
  49999. }
  50000. 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);
  50001. }
  50002. },
  50003. /**
  50004. * Calculates a linear (interpolation) value over t.
  50005. *
  50006. * @method Phaser.Math#linear
  50007. * @param {number} p0
  50008. * @param {number} p1
  50009. * @param {number} t
  50010. * @return {number}
  50011. */
  50012. linear: function (p0, p1, t) {
  50013. return (p1 - p0) * t + p0;
  50014. },
  50015. /**
  50016. * @method Phaser.Math#bernstein
  50017. * @protected
  50018. * @param {number} n
  50019. * @param {number} i
  50020. * @return {number}
  50021. */
  50022. bernstein: function (n, i) {
  50023. return this.factorial(n) / this.factorial(i) / this.factorial(n - i);
  50024. },
  50025. /**
  50026. * @method Phaser.Math#factorial
  50027. * @param {number} value - the number you want to evaluate
  50028. * @return {number}
  50029. */
  50030. factorial : function( value ){
  50031. if (value === 0)
  50032. {
  50033. return 1;
  50034. }
  50035. var res = value;
  50036. while(--value)
  50037. {
  50038. res *= value;
  50039. }
  50040. return res;
  50041. },
  50042. /**
  50043. * Calculates a catmum rom value.
  50044. *
  50045. * @method Phaser.Math#catmullRom
  50046. * @protected
  50047. * @param {number} p0
  50048. * @param {number} p1
  50049. * @param {number} p2
  50050. * @param {number} p3
  50051. * @param {number} t
  50052. * @return {number}
  50053. */
  50054. catmullRom: function (p0, p1, p2, p3, t) {
  50055. var v0 = (p2 - p0) * 0.5, v1 = (p3 - p1) * 0.5, t2 = t * t, t3 = t * t2;
  50056. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  50057. },
  50058. /**
  50059. * The (absolute) difference between two values.
  50060. *
  50061. * @method Phaser.Math#difference
  50062. * @param {number} a
  50063. * @param {number} b
  50064. * @return {number}
  50065. */
  50066. difference: function (a, b) {
  50067. return Math.abs(a - b);
  50068. },
  50069. /**
  50070. * Round to the next whole number _away_ from zero.
  50071. *
  50072. * @method Phaser.Math#roundAwayFromZero
  50073. * @param {number} value - Any number.
  50074. * @return {integer} The rounded value of that number.
  50075. */
  50076. roundAwayFromZero: function (value) {
  50077. // "Opposite" of truncate.
  50078. return (value > 0) ? Math.ceil(value) : Math.floor(value);
  50079. },
  50080. /**
  50081. * Generate a sine and cosine table simultaneously and extremely quickly.
  50082. * The parameters allow you to specify the length, amplitude and frequency of the wave.
  50083. * This generator is fast enough to be used in real-time.
  50084. * Code based on research by Franky of scene.at
  50085. *
  50086. * @method Phaser.Math#sinCosGenerator
  50087. * @param {number} length - The length of the wave
  50088. * @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
  50089. * @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
  50090. * @param {number} frequency - The frequency of the sine and cosine table data
  50091. * @return {{sin:number[], cos:number[]}} Returns the table data.
  50092. */
  50093. sinCosGenerator: function (length, sinAmplitude, cosAmplitude, frequency) {
  50094. if (sinAmplitude === undefined) { sinAmplitude = 1.0; }
  50095. if (cosAmplitude === undefined) { cosAmplitude = 1.0; }
  50096. if (frequency === undefined) { frequency = 1.0; }
  50097. var sin = sinAmplitude;
  50098. var cos = cosAmplitude;
  50099. var frq = frequency * Math.PI / length;
  50100. var cosTable = [];
  50101. var sinTable = [];
  50102. for (var c = 0; c < length; c++) {
  50103. cos -= sin * frq;
  50104. sin += cos * frq;
  50105. cosTable[c] = cos;
  50106. sinTable[c] = sin;
  50107. }
  50108. return { sin: sinTable, cos: cosTable, length: length };
  50109. },
  50110. /**
  50111. * Returns the euclidian distance between the two given set of coordinates.
  50112. *
  50113. * @method Phaser.Math#distance
  50114. * @param {number} x1
  50115. * @param {number} y1
  50116. * @param {number} x2
  50117. * @param {number} y2
  50118. * @return {number} The distance between the two sets of coordinates.
  50119. */
  50120. distance: function (x1, y1, x2, y2) {
  50121. var dx = x1 - x2;
  50122. var dy = y1 - y2;
  50123. return Math.sqrt(dx * dx + dy * dy);
  50124. },
  50125. /**
  50126. * Returns the euclidean distance squared between the two given set of
  50127. * coordinates (cuts out a square root operation before returning).
  50128. *
  50129. * @method Phaser.Math#distanceSq
  50130. * @param {number} x1
  50131. * @param {number} y1
  50132. * @param {number} x2
  50133. * @param {number} y2
  50134. * @return {number} The distance squared between the two sets of coordinates.
  50135. */
  50136. distanceSq: function (x1, y1, x2, y2) {
  50137. var dx = x1 - x2;
  50138. var dy = y1 - y2;
  50139. return dx * dx + dy * dy;
  50140. },
  50141. /**
  50142. * Returns the distance between the two given set of coordinates at the power given.
  50143. *
  50144. * @method Phaser.Math#distancePow
  50145. * @param {number} x1
  50146. * @param {number} y1
  50147. * @param {number} x2
  50148. * @param {number} y2
  50149. * @param {number} [pow=2]
  50150. * @return {number} The distance between the two sets of coordinates.
  50151. */
  50152. distancePow: function (x1, y1, x2, y2, pow) {
  50153. if (pow === undefined) { pow = 2; }
  50154. return Math.sqrt(Math.pow(x2 - x1, pow) + Math.pow(y2 - y1, pow));
  50155. },
  50156. /**
  50157. * Force a value within the boundaries by clamping it to the range `min`, `max`.
  50158. *
  50159. * @method Phaser.Math#clamp
  50160. * @param {float} v - The value to be clamped.
  50161. * @param {float} min - The minimum bounds.
  50162. * @param {float} max - The maximum bounds.
  50163. * @return {number} The clamped value.
  50164. */
  50165. clamp: function (v, min, max) {
  50166. if (v < min)
  50167. {
  50168. return min;
  50169. }
  50170. else if (max < v)
  50171. {
  50172. return max;
  50173. }
  50174. else
  50175. {
  50176. return v;
  50177. }
  50178. },
  50179. /**
  50180. * Clamp `x` to the range `[a, Infinity)`.
  50181. * Roughly the same as `Math.max(x, a)`, except for NaN handling.
  50182. *
  50183. * @method Phaser.Math#clampBottom
  50184. * @param {number} x
  50185. * @param {number} a
  50186. * @return {number}
  50187. */
  50188. clampBottom: function (x, a) {
  50189. return x < a ? a : x;
  50190. },
  50191. /**
  50192. * Checks if two values are within the given tolerance of each other.
  50193. *
  50194. * @method Phaser.Math#within
  50195. * @param {number} a - The first number to check
  50196. * @param {number} b - The second number to check
  50197. * @param {number} tolerance - The tolerance. Anything equal to or less than this is considered within the range.
  50198. * @return {boolean} True if a is <= tolerance of b.
  50199. * @see {@link Phaser.Math.fuzzyEqual}
  50200. */
  50201. within: function (a, b, tolerance) {
  50202. return (Math.abs(a - b) <= tolerance);
  50203. },
  50204. /**
  50205. * Linear mapping from range <a1, a2> to range <b1, b2>
  50206. *
  50207. * @method Phaser.Math#mapLinear
  50208. * @param {number} x the value to map
  50209. * @param {number} a1 first endpoint of the range <a1, a2>
  50210. * @param {number} a2 final endpoint of the range <a1, a2>
  50211. * @param {number} b1 first endpoint of the range <b1, b2>
  50212. * @param {number} b2 final endpoint of the range <b1, b2>
  50213. * @return {number}
  50214. */
  50215. mapLinear: function (x, a1, a2, b1, b2) {
  50216. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  50217. },
  50218. /**
  50219. * Smoothstep function as detailed at http://en.wikipedia.org/wiki/Smoothstep
  50220. *
  50221. * @method Phaser.Math#smoothstep
  50222. * @param {float} x - The input value.
  50223. * @param {float} min - The left edge. Should be smaller than the right edge.
  50224. * @param {float} max - The right edge.
  50225. * @return {float} A value between 0 and 1.
  50226. */
  50227. smoothstep: function (x, min, max) {
  50228. // Scale, bias and saturate x to 0..1 range
  50229. x = Math.max(0, Math.min(1, (x - min) / (max - min)));
  50230. // Evaluate polynomial
  50231. return x * x * (3 - 2 * x);
  50232. },
  50233. /**
  50234. * Smootherstep function as detailed at http://en.wikipedia.org/wiki/Smoothstep
  50235. *
  50236. * @method Phaser.Math#smootherstep
  50237. * @param {float} x - The input value.
  50238. * @param {float} min - The left edge. Should be smaller than the right edge.
  50239. * @param {float} max - The right edge.
  50240. * @return {float} A value between 0 and 1.
  50241. */
  50242. smootherstep: function (x, min, max) {
  50243. x = Math.max(0, Math.min(1, (x - min) / (max - min)));
  50244. return x * x * x * (x * (x * 6 - 15) + 10);
  50245. },
  50246. /**
  50247. * A value representing the sign of the value: -1 for negative, +1 for positive, 0 if value is 0.
  50248. *
  50249. * This works differently from `Math.sign` for values of NaN and -0, etc.
  50250. *
  50251. * @method Phaser.Math#sign
  50252. * @param {number} x
  50253. * @return {integer} An integer in {-1, 0, 1}
  50254. */
  50255. sign: function (x) {
  50256. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  50257. },
  50258. /**
  50259. * Work out what percentage value `a` is of value `b` using the given base.
  50260. *
  50261. * @method Phaser.Math#percent
  50262. * @param {number} a - The value to work out the percentage for.
  50263. * @param {number} b - The value you wish to get the percentage of.
  50264. * @param {number} [base=0] - The base value.
  50265. * @return {number} The percentage a is of b, between 0 and 1.
  50266. */
  50267. percent: function (a, b, base) {
  50268. if (base === undefined) { base = 0; }
  50269. if (a > b || base > b)
  50270. {
  50271. return 1;
  50272. }
  50273. else if (a < base || base > a)
  50274. {
  50275. return 0;
  50276. }
  50277. else
  50278. {
  50279. return (a - base) / b;
  50280. }
  50281. }
  50282. };
  50283. var degreeToRadiansFactor = Math.PI / 180;
  50284. var radianToDegreesFactor = 180 / Math.PI;
  50285. /**
  50286. * Convert degrees to radians.
  50287. *
  50288. * @method Phaser.Math#degToRad
  50289. * @param {number} degrees - Angle in degrees.
  50290. * @return {number} Angle in radians.
  50291. */
  50292. Phaser.Math.degToRad = function degToRad (degrees) {
  50293. return degrees * degreeToRadiansFactor;
  50294. };
  50295. /**
  50296. * Convert radians to degrees.
  50297. *
  50298. * @method Phaser.Math#radToDeg
  50299. * @param {number} radians - Angle in radians.
  50300. * @return {number} Angle in degrees
  50301. */
  50302. Phaser.Math.radToDeg = function radToDeg (radians) {
  50303. return radians * radianToDegreesFactor;
  50304. };
  50305. /* jshint noempty: false */
  50306. /**
  50307. * @author Richard Davey <rich@photonstorm.com>
  50308. * @copyright 2016 Photon Storm Ltd.
  50309. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  50310. */
  50311. /**
  50312. * An extremely useful repeatable random data generator.
  50313. *
  50314. * Based on Nonsense by Josh Faul https://github.com/jocafa/Nonsense.
  50315. *
  50316. * The random number genererator is based on the Alea PRNG, but is modified.
  50317. * - https://github.com/coverslide/node-alea
  50318. * - https://github.com/nquinlan/better-random-numbers-for-javascript-mirror
  50319. * - http://baagoe.org/en/wiki/Better_random_numbers_for_javascript (original, perm. 404)
  50320. *
  50321. * @class Phaser.RandomDataGenerator
  50322. * @constructor
  50323. * @param {any[]|string} [seeds] - An array of values to use as the seed, or a generator state (from {#state}).
  50324. */
  50325. Phaser.RandomDataGenerator = function (seeds) {
  50326. if (seeds === undefined) { seeds = []; }
  50327. /**
  50328. * @property {number} c - Internal var.
  50329. * @private
  50330. */
  50331. this.c = 1;
  50332. /**
  50333. * @property {number} s0 - Internal var.
  50334. * @private
  50335. */
  50336. this.s0 = 0;
  50337. /**
  50338. * @property {number} s1 - Internal var.
  50339. * @private
  50340. */
  50341. this.s1 = 0;
  50342. /**
  50343. * @property {number} s2 - Internal var.
  50344. * @private
  50345. */
  50346. this.s2 = 0;
  50347. if (typeof seeds === 'string')
  50348. {
  50349. this.state(seeds);
  50350. }
  50351. else
  50352. {
  50353. this.sow(seeds);
  50354. }
  50355. };
  50356. Phaser.RandomDataGenerator.prototype = {
  50357. /**
  50358. * Private random helper.
  50359. *
  50360. * @method Phaser.RandomDataGenerator#rnd
  50361. * @private
  50362. * @return {number}
  50363. */
  50364. rnd: function () {
  50365. var t = 2091639 * this.s0 + this.c * 2.3283064365386963e-10; // 2^-32
  50366. this.c = t | 0;
  50367. this.s0 = this.s1;
  50368. this.s1 = this.s2;
  50369. this.s2 = t - this.c;
  50370. return this.s2;
  50371. },
  50372. /**
  50373. * Reset the seed of the random data generator.
  50374. *
  50375. * _Note_: the seed array is only processed up to the first `undefined` (or `null`) value, should such be present.
  50376. *
  50377. * @method Phaser.RandomDataGenerator#sow
  50378. * @param {any[]} seeds - The array of seeds: the `toString()` of each value is used.
  50379. */
  50380. sow: function (seeds) {
  50381. // Always reset to default seed
  50382. this.s0 = this.hash(' ');
  50383. this.s1 = this.hash(this.s0);
  50384. this.s2 = this.hash(this.s1);
  50385. this.c = 1;
  50386. if (!seeds)
  50387. {
  50388. return;
  50389. }
  50390. // Apply any seeds
  50391. for (var i = 0; i < seeds.length && (seeds[i] != null); i++)
  50392. {
  50393. var seed = seeds[i];
  50394. this.s0 -= this.hash(seed);
  50395. this.s0 += ~~(this.s0 < 0);
  50396. this.s1 -= this.hash(seed);
  50397. this.s1 += ~~(this.s1 < 0);
  50398. this.s2 -= this.hash(seed);
  50399. this.s2 += ~~(this.s2 < 0);
  50400. }
  50401. },
  50402. /**
  50403. * Internal method that creates a seed hash.
  50404. *
  50405. * @method Phaser.RandomDataGenerator#hash
  50406. * @private
  50407. * @param {any} data
  50408. * @return {number} hashed value.
  50409. */
  50410. hash: function (data) {
  50411. var h, i, n;
  50412. n = 0xefc8249d;
  50413. data = data.toString();
  50414. for (i = 0; i < data.length; i++) {
  50415. n += data.charCodeAt(i);
  50416. h = 0.02519603282416938 * n;
  50417. n = h >>> 0;
  50418. h -= n;
  50419. h *= n;
  50420. n = h >>> 0;
  50421. h -= n;
  50422. n += h * 0x100000000;// 2^32
  50423. }
  50424. return (n >>> 0) * 2.3283064365386963e-10;// 2^-32
  50425. },
  50426. /**
  50427. * Returns a random integer between 0 and 2^32.
  50428. *
  50429. * @method Phaser.RandomDataGenerator#integer
  50430. * @return {number} A random integer between 0 and 2^32.
  50431. */
  50432. integer: function() {
  50433. return this.rnd.apply(this) * 0x100000000;// 2^32
  50434. },
  50435. /**
  50436. * Returns a random real number between 0 and 1.
  50437. *
  50438. * @method Phaser.RandomDataGenerator#frac
  50439. * @return {number} A random real number between 0 and 1.
  50440. */
  50441. frac: function() {
  50442. return this.rnd.apply(this) + (this.rnd.apply(this) * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53
  50443. },
  50444. /**
  50445. * Returns a random real number between 0 and 2^32.
  50446. *
  50447. * @method Phaser.RandomDataGenerator#real
  50448. * @return {number} A random real number between 0 and 2^32.
  50449. */
  50450. real: function() {
  50451. return this.integer() + this.frac();
  50452. },
  50453. /**
  50454. * Returns a random integer between and including min and max.
  50455. *
  50456. * @method Phaser.RandomDataGenerator#integerInRange
  50457. * @param {number} min - The minimum value in the range.
  50458. * @param {number} max - The maximum value in the range.
  50459. * @return {number} A random number between min and max.
  50460. */
  50461. integerInRange: function (min, max) {
  50462. return Math.floor(this.realInRange(0, max - min + 1) + min);
  50463. },
  50464. /**
  50465. * Returns a random integer between and including min and max.
  50466. * This method is an alias for RandomDataGenerator.integerInRange.
  50467. *
  50468. * @method Phaser.RandomDataGenerator#between
  50469. * @param {number} min - The minimum value in the range.
  50470. * @param {number} max - The maximum value in the range.
  50471. * @return {number} A random number between min and max.
  50472. */
  50473. between: function (min, max) {
  50474. return this.integerInRange(min, max);
  50475. },
  50476. /**
  50477. * Returns a random real number between min and max.
  50478. *
  50479. * @method Phaser.RandomDataGenerator#realInRange
  50480. * @param {number} min - The minimum value in the range.
  50481. * @param {number} max - The maximum value in the range.
  50482. * @return {number} A random number between min and max.
  50483. */
  50484. realInRange: function (min, max) {
  50485. return this.frac() * (max - min) + min;
  50486. },
  50487. /**
  50488. * Returns a random real number between -1 and 1.
  50489. *
  50490. * @method Phaser.RandomDataGenerator#normal
  50491. * @return {number} A random real number between -1 and 1.
  50492. */
  50493. normal: function () {
  50494. return 1 - 2 * this.frac();
  50495. },
  50496. /**
  50497. * Returns a valid RFC4122 version4 ID hex string from https://gist.github.com/1308368
  50498. *
  50499. * @method Phaser.RandomDataGenerator#uuid
  50500. * @return {string} A valid RFC4122 version4 ID hex string
  50501. */
  50502. uuid: function () {
  50503. var a = '';
  50504. var b = '';
  50505. for (b = a = ''; a++ < 36; b +=~a % 5 | a * 3&4 ? (a^15 ? 8^this.frac() * (a^20 ? 16 : 4) : 4).toString(16) : '-')
  50506. {
  50507. }
  50508. return b;
  50509. },
  50510. /**
  50511. * Returns a random member of `array`.
  50512. *
  50513. * @method Phaser.RandomDataGenerator#pick
  50514. * @param {Array} ary - An Array to pick a random member of.
  50515. * @return {any} A random member of the array.
  50516. */
  50517. pick: function (ary) {
  50518. return ary[this.integerInRange(0, ary.length - 1)];
  50519. },
  50520. /**
  50521. * Returns a sign to be used with multiplication operator.
  50522. *
  50523. * @method Phaser.RandomDataGenerator#sign
  50524. * @return {number} -1 or +1.
  50525. */
  50526. sign: function () {
  50527. return this.pick([-1, 1]);
  50528. },
  50529. /**
  50530. * Returns a random member of `array`, favoring the earlier entries.
  50531. *
  50532. * @method Phaser.RandomDataGenerator#weightedPick
  50533. * @param {Array} ary - An Array to pick a random member of.
  50534. * @return {any} A random member of the array.
  50535. */
  50536. weightedPick: function (ary) {
  50537. return ary[~~(Math.pow(this.frac(), 2) * (ary.length - 1) + 0.5)];
  50538. },
  50539. /**
  50540. * 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.
  50541. *
  50542. * @method Phaser.RandomDataGenerator#timestamp
  50543. * @param {number} min - The minimum value in the range.
  50544. * @param {number} max - The maximum value in the range.
  50545. * @return {number} A random timestamp between min and max.
  50546. */
  50547. timestamp: function (min, max) {
  50548. return this.realInRange(min || 946684800000, max || 1577862000000);
  50549. },
  50550. /**
  50551. * Returns a random angle between -180 and 180.
  50552. *
  50553. * @method Phaser.RandomDataGenerator#angle
  50554. * @return {number} A random number between -180 and 180.
  50555. */
  50556. angle: function() {
  50557. return this.integerInRange(-180, 180);
  50558. },
  50559. /**
  50560. * Gets or Sets the state of the generator. This allows you to retain the values
  50561. * that the generator is using between games, i.e. in a game save file.
  50562. *
  50563. * To seed this generator with a previously saved state you can pass it as the
  50564. * `seed` value in your game config, or call this method directly after Phaser has booted.
  50565. *
  50566. * Call this method with no parameters to return the current state.
  50567. *
  50568. * If providing a state it should match the same format that this method
  50569. * returns, which is a string with a header `!rnd` followed by the `c`,
  50570. * `s0`, `s1` and `s2` values respectively, each comma-delimited.
  50571. *
  50572. * @method Phaser.RandomDataGenerator#state
  50573. * @param {string} [state] - Generator state to be set.
  50574. * @return {string} The current state of the generator.
  50575. */
  50576. state: function (state) {
  50577. if (typeof state === 'string' && state.match(/^!rnd/))
  50578. {
  50579. state = state.split(',');
  50580. this.c = parseFloat(state[1]);
  50581. this.s0 = parseFloat(state[2]);
  50582. this.s1 = parseFloat(state[3]);
  50583. this.s2 = parseFloat(state[4]);
  50584. }
  50585. return ['!rnd', this.c, this.s0, this.s1, this.s2].join(',');
  50586. }
  50587. };
  50588. Phaser.RandomDataGenerator.prototype.constructor = Phaser.RandomDataGenerator;
  50589. /**
  50590. * @author Timo Hausmann
  50591. * @author Richard Davey <rich@photonstorm.com>
  50592. * @copyright 2016 Photon Storm Ltd.
  50593. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  50594. */
  50595. /**
  50596. * A QuadTree implementation. The original code was a conversion of the Java code posted to GameDevTuts.
  50597. * However I've tweaked it massively to add node indexing, removed lots of temp. var creation and significantly increased performance as a result.
  50598. * Original version at https://github.com/timohausmann/quadtree-js/
  50599. *
  50600. * @class Phaser.QuadTree
  50601. * @constructor
  50602. * @param {number} x - The top left coordinate of the quadtree.
  50603. * @param {number} y - The top left coordinate of the quadtree.
  50604. * @param {number} width - The width of the quadtree in pixels.
  50605. * @param {number} height - The height of the quadtree in pixels.
  50606. * @param {number} [maxObjects=10] - The maximum number of objects per node.
  50607. * @param {number} [maxLevels=4] - The maximum number of levels to iterate to.
  50608. * @param {number} [level=0] - Which level is this?
  50609. */
  50610. Phaser.QuadTree = function(x, y, width, height, maxObjects, maxLevels, level) {
  50611. /**
  50612. * @property {number} maxObjects - The maximum number of objects per node.
  50613. * @default
  50614. */
  50615. this.maxObjects = 10;
  50616. /**
  50617. * @property {number} maxLevels - The maximum number of levels to break down to.
  50618. * @default
  50619. */
  50620. this.maxLevels = 4;
  50621. /**
  50622. * @property {number} level - The current level.
  50623. */
  50624. this.level = 0;
  50625. /**
  50626. * @property {object} bounds - Object that contains the quadtree bounds.
  50627. */
  50628. this.bounds = {};
  50629. /**
  50630. * @property {array} objects - Array of quadtree children.
  50631. */
  50632. this.objects = [];
  50633. /**
  50634. * @property {array} nodes - Array of associated child nodes.
  50635. */
  50636. this.nodes = [];
  50637. /**
  50638. * @property {array} _empty - Internal empty array.
  50639. * @private
  50640. */
  50641. this._empty = [];
  50642. this.reset(x, y, width, height, maxObjects, maxLevels, level);
  50643. };
  50644. Phaser.QuadTree.prototype = {
  50645. /**
  50646. * Resets the QuadTree.
  50647. *
  50648. * @method Phaser.QuadTree#reset
  50649. * @param {number} x - The top left coordinate of the quadtree.
  50650. * @param {number} y - The top left coordinate of the quadtree.
  50651. * @param {number} width - The width of the quadtree in pixels.
  50652. * @param {number} height - The height of the quadtree in pixels.
  50653. * @param {number} [maxObjects=10] - The maximum number of objects per node.
  50654. * @param {number} [maxLevels=4] - The maximum number of levels to iterate to.
  50655. * @param {number} [level=0] - Which level is this?
  50656. */
  50657. reset: function (x, y, width, height, maxObjects, maxLevels, level) {
  50658. this.maxObjects = maxObjects || 10;
  50659. this.maxLevels = maxLevels || 4;
  50660. this.level = level || 0;
  50661. this.bounds = {
  50662. x: Math.round(x),
  50663. y: Math.round(y),
  50664. width: width,
  50665. height: height,
  50666. subWidth: Math.floor(width / 2),
  50667. subHeight: Math.floor(height / 2),
  50668. right: Math.round(x) + Math.floor(width / 2),
  50669. bottom: Math.round(y) + Math.floor(height / 2)
  50670. };
  50671. this.objects.length = 0;
  50672. this.nodes.length = 0;
  50673. },
  50674. /**
  50675. * Populates this quadtree with the children of the given Group. In order to be added the child must exist and have a body property.
  50676. *
  50677. * @method Phaser.QuadTree#populate
  50678. * @param {Phaser.Group} group - The Group to add to the quadtree.
  50679. */
  50680. populate: function (group) {
  50681. group.forEach(this.populateHandler, this, true);
  50682. },
  50683. /**
  50684. * Handler for the populate method.
  50685. *
  50686. * @method Phaser.QuadTree#populateHandler
  50687. * @param {Phaser.Sprite|object} sprite - The Sprite to check.
  50688. */
  50689. populateHandler: function (sprite) {
  50690. if (sprite.body && sprite.exists)
  50691. {
  50692. this.insert(sprite.body);
  50693. }
  50694. },
  50695. /**
  50696. * Split the node into 4 subnodes
  50697. *
  50698. * @method Phaser.QuadTree#split
  50699. */
  50700. split: function () {
  50701. // top right node
  50702. this.nodes[0] = new Phaser.QuadTree(this.bounds.right, this.bounds.y, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1));
  50703. // top left node
  50704. this.nodes[1] = new Phaser.QuadTree(this.bounds.x, this.bounds.y, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1));
  50705. // bottom left node
  50706. this.nodes[2] = new Phaser.QuadTree(this.bounds.x, this.bounds.bottom, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1));
  50707. // bottom right node
  50708. this.nodes[3] = new Phaser.QuadTree(this.bounds.right, this.bounds.bottom, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1));
  50709. },
  50710. /**
  50711. * Insert the object into the node. If the node exceeds the capacity, it will split and add all objects to their corresponding subnodes.
  50712. *
  50713. * @method Phaser.QuadTree#insert
  50714. * @param {Phaser.Physics.Arcade.Body|object} body - The Body object to insert into the quadtree. Can be any object so long as it exposes x, y, right and bottom properties.
  50715. */
  50716. insert: function (body) {
  50717. var i = 0;
  50718. var index;
  50719. // if we have subnodes ...
  50720. if (this.nodes[0] != null)
  50721. {
  50722. index = this.getIndex(body);
  50723. if (index !== -1)
  50724. {
  50725. this.nodes[index].insert(body);
  50726. return;
  50727. }
  50728. }
  50729. this.objects.push(body);
  50730. if (this.objects.length > this.maxObjects && this.level < this.maxLevels)
  50731. {
  50732. // Split if we don't already have subnodes
  50733. if (this.nodes[0] == null)
  50734. {
  50735. this.split();
  50736. }
  50737. // Add objects to subnodes
  50738. while (i < this.objects.length)
  50739. {
  50740. index = this.getIndex(this.objects[i]);
  50741. if (index !== -1)
  50742. {
  50743. // this is expensive - see what we can do about it
  50744. this.nodes[index].insert(this.objects.splice(i, 1)[0]);
  50745. }
  50746. else
  50747. {
  50748. i++;
  50749. }
  50750. }
  50751. }
  50752. },
  50753. /**
  50754. * Determine which node the object belongs to.
  50755. *
  50756. * @method Phaser.QuadTree#getIndex
  50757. * @param {Phaser.Rectangle|object} rect - The bounds in which to check.
  50758. * @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.
  50759. */
  50760. getIndex: function (rect) {
  50761. // default is that rect doesn't fit, i.e. it straddles the internal quadrants
  50762. var index = -1;
  50763. if (rect.x < this.bounds.right && rect.right < this.bounds.right)
  50764. {
  50765. if (rect.y < this.bounds.bottom && rect.bottom < this.bounds.bottom)
  50766. {
  50767. // rect fits within the top-left quadrant of this quadtree
  50768. index = 1;
  50769. }
  50770. else if (rect.y > this.bounds.bottom)
  50771. {
  50772. // rect fits within the bottom-left quadrant of this quadtree
  50773. index = 2;
  50774. }
  50775. }
  50776. else if (rect.x > this.bounds.right)
  50777. {
  50778. // rect can completely fit within the right quadrants
  50779. if (rect.y < this.bounds.bottom && rect.bottom < this.bounds.bottom)
  50780. {
  50781. // rect fits within the top-right quadrant of this quadtree
  50782. index = 0;
  50783. }
  50784. else if (rect.y > this.bounds.bottom)
  50785. {
  50786. // rect fits within the bottom-right quadrant of this quadtree
  50787. index = 3;
  50788. }
  50789. }
  50790. return index;
  50791. },
  50792. /**
  50793. * Return all objects that could collide with the given Sprite or Rectangle.
  50794. *
  50795. * @method Phaser.QuadTree#retrieve
  50796. * @param {Phaser.Sprite|Phaser.Rectangle} source - The source object to check the QuadTree against. Either a Sprite or Rectangle.
  50797. * @return {array} - Array with all detected objects.
  50798. */
  50799. retrieve: function (source) {
  50800. if (source instanceof Phaser.Rectangle)
  50801. {
  50802. var returnObjects = this.objects;
  50803. var index = this.getIndex(source);
  50804. }
  50805. else
  50806. {
  50807. if (!source.body)
  50808. {
  50809. return this._empty;
  50810. }
  50811. var returnObjects = this.objects;
  50812. var index = this.getIndex(source.body);
  50813. }
  50814. if (this.nodes[0])
  50815. {
  50816. // If rect fits into a subnode ..
  50817. if (index !== -1)
  50818. {
  50819. returnObjects = returnObjects.concat(this.nodes[index].retrieve(source));
  50820. }
  50821. else
  50822. {
  50823. // If rect does not fit into a subnode, check it against all subnodes (unrolled for speed)
  50824. returnObjects = returnObjects.concat(this.nodes[0].retrieve(source));
  50825. returnObjects = returnObjects.concat(this.nodes[1].retrieve(source));
  50826. returnObjects = returnObjects.concat(this.nodes[2].retrieve(source));
  50827. returnObjects = returnObjects.concat(this.nodes[3].retrieve(source));
  50828. }
  50829. }
  50830. return returnObjects;
  50831. },
  50832. /**
  50833. * Clear the quadtree.
  50834. * @method Phaser.QuadTree#clear
  50835. */
  50836. clear: function () {
  50837. this.objects.length = 0;
  50838. var i = this.nodes.length;
  50839. while (i--)
  50840. {
  50841. this.nodes[i].clear();
  50842. this.nodes.splice(i, 1);
  50843. }
  50844. this.nodes.length = 0;
  50845. }
  50846. };
  50847. Phaser.QuadTree.prototype.constructor = Phaser.QuadTree;
  50848. /**
  50849. * Javascript QuadTree
  50850. * @version 1.0
  50851. *
  50852. * @version 1.3, March 11th 2014
  50853. * @author Richard Davey
  50854. * The original code was a conversion of the Java code posted to GameDevTuts. However I've tweaked
  50855. * it massively to add node indexing, removed lots of temp. var creation and significantly
  50856. * increased performance as a result.
  50857. *
  50858. * Original version at https://github.com/timohausmann/quadtree-js/
  50859. */
  50860. /**
  50861. * @copyright © 2012 Timo Hausmann
  50862. *
  50863. * Permission is hereby granted, free of charge, to any person obtaining
  50864. * a copy of this software and associated documentation files (the
  50865. * "Software"), to deal in the Software without restriction, including
  50866. * without limitation the rights to use, copy, modify, merge, publish,
  50867. * distribute, sublicense, and/or sell copies of the Software, and to
  50868. * permit persons to whom the Software is furnished to do so, subject to
  50869. * the following conditions:
  50870. *
  50871. * The above copyright notice and this permission notice shall be
  50872. * included in all copies or substantial portions of the Software.
  50873. *
  50874. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  50875. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  50876. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  50877. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  50878. * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  50879. * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  50880. * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  50881. */
  50882. /**
  50883. * @author Richard Davey <rich@photonstorm.com>
  50884. * @copyright 2016 Photon Storm Ltd.
  50885. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  50886. */
  50887. /**
  50888. * Phaser.Net handles browser URL related tasks such as checking host names, domain names and query string manipulation.
  50889. *
  50890. * @class Phaser.Net
  50891. * @constructor
  50892. * @param {Phaser.Game} game - A reference to the currently running game.
  50893. */
  50894. Phaser.Net = function (game) {
  50895. this.game = game;
  50896. };
  50897. Phaser.Net.prototype = {
  50898. /**
  50899. * Returns the hostname given by the browser.
  50900. *
  50901. * @method Phaser.Net#getHostName
  50902. * @return {string}
  50903. */
  50904. getHostName: function () {
  50905. if (window.location && window.location.hostname) {
  50906. return window.location.hostname;
  50907. }
  50908. return null;
  50909. },
  50910. /**
  50911. * Compares the given domain name against the hostname of the browser containing the game.
  50912. * If the domain name is found it returns true.
  50913. * You can specify a part of a domain, for example 'google' would match 'google.com', 'google.co.uk', etc.
  50914. * Do not include 'http://' at the start.
  50915. *
  50916. * @method Phaser.Net#checkDomainName
  50917. * @param {string} domain
  50918. * @return {boolean} true if the given domain fragment can be found in the window.location.hostname
  50919. */
  50920. checkDomainName: function (domain) {
  50921. return window.location.hostname.indexOf(domain) !== -1;
  50922. },
  50923. /**
  50924. * Updates a value on the Query String and returns it in full.
  50925. * If the value doesn't already exist it is set.
  50926. * 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.
  50927. * Optionally you can redirect to the new url, or just return it as a string.
  50928. *
  50929. * @method Phaser.Net#updateQueryString
  50930. * @param {string} key - The querystring key to update.
  50931. * @param {string} value - The new value to be set. If it already exists it will be replaced.
  50932. * @param {boolean} redirect - If true the browser will issue a redirect to the url with the new querystring.
  50933. * @param {string} url - The URL to modify. If none is given it uses window.location.href.
  50934. * @return {string} If redirect is false then the modified url and query string is returned.
  50935. */
  50936. updateQueryString: function (key, value, redirect, url) {
  50937. if (redirect === undefined) { redirect = false; }
  50938. if (url === undefined || url === '') { url = window.location.href; }
  50939. var output = '';
  50940. var re = new RegExp("([?|&])" + key + "=.*?(&|#|$)(.*)", "gi");
  50941. if (re.test(url))
  50942. {
  50943. if (typeof value !== 'undefined' && value !== null)
  50944. {
  50945. output = url.replace(re, '$1' + key + "=" + value + '$2$3');
  50946. }
  50947. else
  50948. {
  50949. output = url.replace(re, '$1$3').replace(/(&|\?)$/, '');
  50950. }
  50951. }
  50952. else
  50953. {
  50954. if (typeof value !== 'undefined' && value !== null)
  50955. {
  50956. var separator = url.indexOf('?') !== -1 ? '&' : '?';
  50957. var hash = url.split('#');
  50958. url = hash[0] + separator + key + '=' + value;
  50959. if (hash[1]) {
  50960. url += '#' + hash[1];
  50961. }
  50962. output = url;
  50963. }
  50964. else
  50965. {
  50966. output = url;
  50967. }
  50968. }
  50969. if (redirect)
  50970. {
  50971. window.location.href = output;
  50972. }
  50973. else
  50974. {
  50975. return output;
  50976. }
  50977. },
  50978. /**
  50979. * Returns the Query String as an object.
  50980. * If you specify a parameter it will return just the value of that parameter, should it exist.
  50981. *
  50982. * @method Phaser.Net#getQueryString
  50983. * @param {string} [parameter=''] - If specified this will return just the value for that key.
  50984. * @return {string|object} An object containing the key value pairs found in the query string or just the value if a parameter was given.
  50985. */
  50986. getQueryString: function (parameter) {
  50987. if (parameter === undefined) { parameter = ''; }
  50988. var output = {};
  50989. var keyValues = location.search.substring(1).split('&');
  50990. for (var i in keyValues)
  50991. {
  50992. var key = keyValues[i].split('=');
  50993. if (key.length > 1)
  50994. {
  50995. if (parameter && parameter == this.decodeURI(key[0]))
  50996. {
  50997. return this.decodeURI(key[1]);
  50998. }
  50999. else
  51000. {
  51001. output[this.decodeURI(key[0])] = this.decodeURI(key[1]);
  51002. }
  51003. }
  51004. }
  51005. return output;
  51006. },
  51007. /**
  51008. * Takes a Uniform Resource Identifier (URI) component (previously created by encodeURIComponent or by a similar routine) and
  51009. * decodes it, replacing \ with spaces in the return. Used internally by the Net classes.
  51010. *
  51011. * @method Phaser.Net#decodeURI
  51012. * @param {string} value - The URI component to be decoded.
  51013. * @return {string} The decoded value.
  51014. */
  51015. decodeURI: function (value) {
  51016. return decodeURIComponent(value.replace(/\+/g, " "));
  51017. }
  51018. };
  51019. Phaser.Net.prototype.constructor = Phaser.Net;
  51020. /**
  51021. * @author Richard Davey <rich@photonstorm.com>
  51022. * @copyright 2016 Photon Storm Ltd.
  51023. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  51024. */
  51025. /**
  51026. * Phaser.Game has a single instance of the TweenManager through which all Tween objects are created and updated.
  51027. * Tweens are hooked into the game clock and pause system, adjusting based on the game state.
  51028. *
  51029. * TweenManager is based heavily on tween.js by http://soledadpenades.com.
  51030. * The difference being that tweens belong to a games instance of TweenManager, rather than to a global TWEEN object.
  51031. * It also has callbacks swapped for Signals and a few issues patched with regard to properties and completion errors.
  51032. * Please see https://github.com/sole/tween.js for a full list of contributors.
  51033. *
  51034. * @class Phaser.TweenManager
  51035. * @constructor
  51036. * @param {Phaser.Game} game - A reference to the currently running game.
  51037. */
  51038. Phaser.TweenManager = function (game) {
  51039. /**
  51040. * @property {Phaser.Game} game - Local reference to game.
  51041. */
  51042. this.game = game;
  51043. /**
  51044. * Are all newly created Tweens frame or time based? A frame based tween will use the physics elapsed timer when updating. This means
  51045. * it will retain the same consistent frame rate, regardless of the speed of the device. The duration value given should
  51046. * be given in frames.
  51047. *
  51048. * If the Tween uses a time based update (which is the default) then the duration is given in milliseconds.
  51049. * In this situation a 2000ms tween will last exactly 2 seconds, regardless of the device and how many visual updates the tween
  51050. * has actually been through. For very short tweens you may wish to experiment with a frame based update instead.
  51051. * @property {boolean} frameBased
  51052. * @default
  51053. */
  51054. this.frameBased = false;
  51055. /**
  51056. * @property {array<Phaser.Tween>} _tweens - All of the currently running tweens.
  51057. * @private
  51058. */
  51059. this._tweens = [];
  51060. /**
  51061. * @property {array<Phaser.Tween>} _add - All of the tweens queued to be added in the next update.
  51062. * @private
  51063. */
  51064. this._add = [];
  51065. this.easeMap = {
  51066. "Power0": Phaser.Easing.Power0,
  51067. "Power1": Phaser.Easing.Power1,
  51068. "Power2": Phaser.Easing.Power2,
  51069. "Power3": Phaser.Easing.Power3,
  51070. "Power4": Phaser.Easing.Power4,
  51071. "Linear": Phaser.Easing.Linear.None,
  51072. "Quad": Phaser.Easing.Quadratic.Out,
  51073. "Cubic": Phaser.Easing.Cubic.Out,
  51074. "Quart": Phaser.Easing.Quartic.Out,
  51075. "Quint": Phaser.Easing.Quintic.Out,
  51076. "Sine": Phaser.Easing.Sinusoidal.Out,
  51077. "Expo": Phaser.Easing.Exponential.Out,
  51078. "Circ": Phaser.Easing.Circular.Out,
  51079. "Elastic": Phaser.Easing.Elastic.Out,
  51080. "Back": Phaser.Easing.Back.Out,
  51081. "Bounce": Phaser.Easing.Bounce.Out,
  51082. "Quad.easeIn": Phaser.Easing.Quadratic.In,
  51083. "Cubic.easeIn": Phaser.Easing.Cubic.In,
  51084. "Quart.easeIn": Phaser.Easing.Quartic.In,
  51085. "Quint.easeIn": Phaser.Easing.Quintic.In,
  51086. "Sine.easeIn": Phaser.Easing.Sinusoidal.In,
  51087. "Expo.easeIn": Phaser.Easing.Exponential.In,
  51088. "Circ.easeIn": Phaser.Easing.Circular.In,
  51089. "Elastic.easeIn": Phaser.Easing.Elastic.In,
  51090. "Back.easeIn": Phaser.Easing.Back.In,
  51091. "Bounce.easeIn": Phaser.Easing.Bounce.In,
  51092. "Quad.easeOut": Phaser.Easing.Quadratic.Out,
  51093. "Cubic.easeOut": Phaser.Easing.Cubic.Out,
  51094. "Quart.easeOut": Phaser.Easing.Quartic.Out,
  51095. "Quint.easeOut": Phaser.Easing.Quintic.Out,
  51096. "Sine.easeOut": Phaser.Easing.Sinusoidal.Out,
  51097. "Expo.easeOut": Phaser.Easing.Exponential.Out,
  51098. "Circ.easeOut": Phaser.Easing.Circular.Out,
  51099. "Elastic.easeOut": Phaser.Easing.Elastic.Out,
  51100. "Back.easeOut": Phaser.Easing.Back.Out,
  51101. "Bounce.easeOut": Phaser.Easing.Bounce.Out,
  51102. "Quad.easeInOut": Phaser.Easing.Quadratic.InOut,
  51103. "Cubic.easeInOut": Phaser.Easing.Cubic.InOut,
  51104. "Quart.easeInOut": Phaser.Easing.Quartic.InOut,
  51105. "Quint.easeInOut": Phaser.Easing.Quintic.InOut,
  51106. "Sine.easeInOut": Phaser.Easing.Sinusoidal.InOut,
  51107. "Expo.easeInOut": Phaser.Easing.Exponential.InOut,
  51108. "Circ.easeInOut": Phaser.Easing.Circular.InOut,
  51109. "Elastic.easeInOut": Phaser.Easing.Elastic.InOut,
  51110. "Back.easeInOut": Phaser.Easing.Back.InOut,
  51111. "Bounce.easeInOut": Phaser.Easing.Bounce.InOut
  51112. };
  51113. this.game.onPause.add(this._pauseAll, this);
  51114. this.game.onResume.add(this._resumeAll, this);
  51115. };
  51116. Phaser.TweenManager.prototype = {
  51117. /**
  51118. * Get all the tween objects in an array.
  51119. * @method Phaser.TweenManager#getAll
  51120. * @returns {Phaser.Tween[]} Array with all tween objects.
  51121. */
  51122. getAll: function () {
  51123. return this._tweens;
  51124. },
  51125. /**
  51126. * Remove all tweens running and in the queue. Doesn't call any of the tween onComplete events.
  51127. * @method Phaser.TweenManager#removeAll
  51128. */
  51129. removeAll: function () {
  51130. for (var i = 0; i < this._tweens.length; i++)
  51131. {
  51132. this._tweens[i].pendingDelete = true;
  51133. }
  51134. this._add = [];
  51135. },
  51136. /**
  51137. * Remove all tweens from a specific object, array of objects or Group.
  51138. *
  51139. * @method Phaser.TweenManager#removeFrom
  51140. * @param {object|object[]|Phaser.Group} obj - The object you want to remove the tweens from.
  51141. * @param {boolean} [children=true] - If passing a group, setting this to true will remove the tweens from all of its children instead of the group itself.
  51142. */
  51143. removeFrom: function (obj, children) {
  51144. if (children === undefined) { children = true; }
  51145. var i;
  51146. var len;
  51147. if (Array.isArray(obj))
  51148. {
  51149. for (i = 0, len = obj.length; i < len; i++)
  51150. {
  51151. this.removeFrom(obj[i]);
  51152. }
  51153. }
  51154. else if (obj.type === Phaser.GROUP && children)
  51155. {
  51156. for (var i = 0, len = obj.children.length; i < len; i++)
  51157. {
  51158. this.removeFrom(obj.children[i]);
  51159. }
  51160. }
  51161. else
  51162. {
  51163. for (i = 0, len = this._tweens.length; i < len; i++)
  51164. {
  51165. if (obj === this._tweens[i].target)
  51166. {
  51167. this.remove(this._tweens[i]);
  51168. }
  51169. }
  51170. for (i = 0, len = this._add.length; i < len; i++)
  51171. {
  51172. if (obj === this._add[i].target)
  51173. {
  51174. this.remove(this._add[i]);
  51175. }
  51176. }
  51177. }
  51178. },
  51179. /**
  51180. * Add a new tween into the TweenManager.
  51181. *
  51182. * @method Phaser.TweenManager#add
  51183. * @param {Phaser.Tween} tween - The tween object you want to add.
  51184. * @returns {Phaser.Tween} The tween object you added to the manager.
  51185. */
  51186. add: function (tween) {
  51187. tween._manager = this;
  51188. this._add.push(tween);
  51189. },
  51190. /**
  51191. * Create a tween object for a specific object. The object can be any JavaScript object or Phaser object such as Sprite.
  51192. *
  51193. * @method Phaser.TweenManager#create
  51194. * @param {object} object - Object the tween will be run on.
  51195. * @returns {Phaser.Tween} The newly created tween object.
  51196. */
  51197. create: function (object) {
  51198. return new Phaser.Tween(object, this.game, this);
  51199. },
  51200. /**
  51201. * Remove a tween from this manager.
  51202. *
  51203. * @method Phaser.TweenManager#remove
  51204. * @param {Phaser.Tween} tween - The tween object you want to remove.
  51205. */
  51206. remove: function (tween) {
  51207. var i = this._tweens.indexOf(tween);
  51208. if (i !== -1)
  51209. {
  51210. this._tweens[i].pendingDelete = true;
  51211. }
  51212. else
  51213. {
  51214. i = this._add.indexOf(tween);
  51215. if (i !== -1)
  51216. {
  51217. this._add[i].pendingDelete = true;
  51218. }
  51219. }
  51220. },
  51221. /**
  51222. * Update all the tween objects you added to this manager.
  51223. *
  51224. * @method Phaser.TweenManager#update
  51225. * @returns {boolean} Return false if there's no tween to update, otherwise return true.
  51226. */
  51227. update: function () {
  51228. var addTweens = this._add.length;
  51229. var numTweens = this._tweens.length;
  51230. if (numTweens === 0 && addTweens === 0)
  51231. {
  51232. return false;
  51233. }
  51234. var i = 0;
  51235. while (i < numTweens)
  51236. {
  51237. if (this._tweens[i].update(this.game.time.time))
  51238. {
  51239. i++;
  51240. }
  51241. else
  51242. {
  51243. this._tweens.splice(i, 1);
  51244. numTweens--;
  51245. }
  51246. }
  51247. // If there are any new tweens to be added, do so now - otherwise they can be spliced out of the array before ever running
  51248. if (addTweens > 0)
  51249. {
  51250. this._tweens = this._tweens.concat(this._add);
  51251. this._add.length = 0;
  51252. }
  51253. return true;
  51254. },
  51255. /**
  51256. * Checks to see if a particular Sprite is currently being tweened.
  51257. *
  51258. * @method Phaser.TweenManager#isTweening
  51259. * @param {object} object - The object to check for tweens against.
  51260. * @returns {boolean} Returns true if the object is currently being tweened, false if not.
  51261. */
  51262. isTweening: function(object) {
  51263. return this._tweens.some(function(tween) {
  51264. return tween.target === object;
  51265. });
  51266. },
  51267. /**
  51268. * Private. Called by game focus loss. Pauses all currently running tweens.
  51269. *
  51270. * @method Phaser.TweenManager#_pauseAll
  51271. * @private
  51272. */
  51273. _pauseAll: function () {
  51274. for (var i = this._tweens.length - 1; i >= 0; i--)
  51275. {
  51276. this._tweens[i]._pause();
  51277. }
  51278. },
  51279. /**
  51280. * Private. Called by game focus loss. Resumes all currently paused tweens.
  51281. *
  51282. * @method Phaser.TweenManager#_resumeAll
  51283. * @private
  51284. */
  51285. _resumeAll: function () {
  51286. for (var i = this._tweens.length - 1; i >= 0; i--)
  51287. {
  51288. this._tweens[i]._resume();
  51289. }
  51290. },
  51291. /**
  51292. * Pauses all currently running tweens.
  51293. *
  51294. * @method Phaser.TweenManager#pauseAll
  51295. */
  51296. pauseAll: function () {
  51297. for (var i = this._tweens.length - 1; i >= 0; i--)
  51298. {
  51299. this._tweens[i].pause();
  51300. }
  51301. },
  51302. /**
  51303. * Resumes all currently paused tweens.
  51304. *
  51305. * @method Phaser.TweenManager#resumeAll
  51306. */
  51307. resumeAll: function () {
  51308. for (var i = this._tweens.length - 1; i >= 0; i--)
  51309. {
  51310. this._tweens[i].resume(true);
  51311. }
  51312. }
  51313. };
  51314. Phaser.TweenManager.prototype.constructor = Phaser.TweenManager;
  51315. /**
  51316. * @author Richard Davey <rich@photonstorm.com>
  51317. * @copyright 2016 Photon Storm Ltd.
  51318. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  51319. */
  51320. /**
  51321. * A Tween allows you to alter one or more properties of a target object over a defined period of time.
  51322. * This can be used for things such as alpha fading Sprites, scaling them or motion.
  51323. * Use `Tween.to` or `Tween.from` to set-up the tween values. You can create multiple tweens on the same object
  51324. * by calling Tween.to multiple times on the same Tween. Additional tweens specified in this way become "child" tweens and
  51325. * are played through in sequence. You can use Tween.timeScale and Tween.reverse to control the playback of this Tween and all of its children.
  51326. *
  51327. * @class Phaser.Tween
  51328. * @constructor
  51329. * @param {object} target - The target object, such as a Phaser.Sprite or Phaser.Sprite.scale.
  51330. * @param {Phaser.Game} game - Current game instance.
  51331. * @param {Phaser.TweenManager} manager - The TweenManager responsible for looking after this Tween.
  51332. */
  51333. Phaser.Tween = function (target, game, manager) {
  51334. /**
  51335. * @property {Phaser.Game} game - A reference to the currently running Game.
  51336. */
  51337. this.game = game;
  51338. /**
  51339. * @property {object} target - The target object, such as a Phaser.Sprite or property like Phaser.Sprite.scale.
  51340. */
  51341. this.target = target;
  51342. /**
  51343. * @property {Phaser.TweenManager} manager - Reference to the TweenManager responsible for updating this Tween.
  51344. */
  51345. this.manager = manager;
  51346. /**
  51347. * @property {Array} timeline - An Array of TweenData objects that comprise the different parts of this Tween.
  51348. */
  51349. this.timeline = [];
  51350. /**
  51351. * If set to `true` the current tween will play in reverse.
  51352. * If the tween hasn't yet started this has no effect.
  51353. * If there are child tweens then all child tweens will play in reverse from the current point.
  51354. * @property {boolean} reverse
  51355. * @default
  51356. */
  51357. this.reverse = false;
  51358. /**
  51359. * The speed at which the tweens will run. A value of 1 means it will match the game frame rate. 0.5 will run at half the frame rate. 2 at double the frame rate, etc.
  51360. * If a tweens duration is 1 second but timeScale is 0.5 then it will take 2 seconds to complete.
  51361. *
  51362. * @property {number} timeScale
  51363. * @default
  51364. */
  51365. this.timeScale = 1;
  51366. /**
  51367. * @property {number} repeatCounter - If the Tween and any child tweens are set to repeat this contains the current repeat count.
  51368. */
  51369. this.repeatCounter = 0;
  51370. /**
  51371. * @property {boolean} pendingDelete - True if this Tween is ready to be deleted by the TweenManager.
  51372. * @default
  51373. * @readonly
  51374. */
  51375. this.pendingDelete = false;
  51376. /**
  51377. * The onStart event is fired when the Tween begins. If there is a delay before the tween starts then onStart fires after the delay is finished.
  51378. * It will be sent 2 parameters: the target object and this tween.
  51379. * @property {Phaser.Signal} onStart
  51380. */
  51381. this.onStart = new Phaser.Signal();
  51382. /**
  51383. * The onLoop event is fired if the Tween, or any child tweens loop.
  51384. * It will be sent 2 parameters: the target object and this tween.
  51385. *
  51386. * @property {Phaser.Signal} onLoop
  51387. */
  51388. this.onLoop = new Phaser.Signal();
  51389. /**
  51390. * The onRepeat event is fired if the Tween and all of its children repeats. If this tween has no children this will never be fired.
  51391. * It will be sent 2 parameters: the target object and this tween.
  51392. * @property {Phaser.Signal} onRepeat
  51393. */
  51394. this.onRepeat = new Phaser.Signal();
  51395. /**
  51396. * The onChildComplete event is fired when the Tween or any of its children completes.
  51397. * Fires every time a child completes unless a child is set to repeat forever.
  51398. * It will be sent 2 parameters: the target object and this tween.
  51399. * @property {Phaser.Signal} onChildComplete
  51400. */
  51401. this.onChildComplete = new Phaser.Signal();
  51402. /**
  51403. * The onComplete event is fired when the Tween and all of its children completes. Does not fire if the Tween is set to loop or repeatAll(-1).
  51404. * It will be sent 2 parameters: the target object and this tween.
  51405. * @property {Phaser.Signal} onComplete
  51406. */
  51407. this.onComplete = new Phaser.Signal();
  51408. /**
  51409. * @property {boolean} isRunning - If the tween is running this is set to true, otherwise false. Tweens that are in a delayed state or waiting to start are considered as being running.
  51410. * @default
  51411. */
  51412. this.isRunning = false;
  51413. /**
  51414. * @property {number} current - The current Tween child being run.
  51415. * @default
  51416. * @readonly
  51417. */
  51418. this.current = 0;
  51419. /**
  51420. * @property {object} properties - Target property cache used when building the child data values.
  51421. */
  51422. this.properties = {};
  51423. /**
  51424. * @property {Phaser.Tween} chainedTween - If this Tween is chained to another this holds a reference to it.
  51425. */
  51426. this.chainedTween = null;
  51427. /**
  51428. * @property {boolean} isPaused - Is this Tween paused or not?
  51429. * @default
  51430. */
  51431. this.isPaused = false;
  51432. /**
  51433. * Is this Tween frame or time based? A frame based tween will use the physics elapsed timer when updating. This means
  51434. * it will retain the same consistent frame rate, regardless of the speed of the device. The duration value given should
  51435. * be given in frames.
  51436. *
  51437. * If the Tween uses a time based update (which is the default) then the duration is given in milliseconds.
  51438. * In this situation a 2000ms tween will last exactly 2 seconds, regardless of the device and how many visual updates the tween
  51439. * has actually been through. For very short tweens you may wish to experiment with a frame based update instead.
  51440. *
  51441. * The default value is whatever you've set in TweenManager.frameBased.
  51442. *
  51443. * @property {boolean} frameBased
  51444. * @default
  51445. */
  51446. this.frameBased = manager.frameBased;
  51447. /**
  51448. * @property {function} _onUpdateCallback - An onUpdate callback.
  51449. * @private
  51450. * @default null
  51451. */
  51452. this._onUpdateCallback = null;
  51453. /**
  51454. * @property {object} _onUpdateCallbackContext - The context in which to call the onUpdate callback.
  51455. * @private
  51456. * @default null
  51457. */
  51458. this._onUpdateCallbackContext = null;
  51459. /**
  51460. * @property {number} _pausedTime - Private pause timer.
  51461. * @private
  51462. * @default
  51463. */
  51464. this._pausedTime = 0;
  51465. /**
  51466. * @property {boolean} _codePaused - Was the Tween paused by code or by Game focus loss?
  51467. * @private
  51468. */
  51469. this._codePaused = false;
  51470. /**
  51471. * @property {boolean} _hasStarted - Internal var to track if the Tween has started yet or not.
  51472. * @private
  51473. */
  51474. this._hasStarted = false;
  51475. };
  51476. Phaser.Tween.prototype = {
  51477. /**
  51478. * Sets this tween to be a `to` tween on the properties given. A `to` tween starts at the current value and tweens to the destination value given.
  51479. * For example a Sprite with an `x` coordinate of 100 could be tweened to `x` 200 by giving a properties object of `{ x: 200 }`.
  51480. * The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as "Circ".
  51481. * ".easeIn", ".easeOut" and "easeInOut" variants are all supported for all ease types.
  51482. *
  51483. * @method Phaser.Tween#to
  51484. * @param {object} properties - An object containing the properties you want to tween, such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object.
  51485. * @param {number} [duration=1000] - Duration of this tween in ms. Or if `Tween.frameBased` is true this represents the number of frames that should elapse.
  51486. * @param {function|string} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden.
  51487. * @param {boolean} [autoStart=false] - Set to `true` to allow this tween to start automatically. Otherwise call Tween.start().
  51488. * @param {number} [delay=0] - Delay before this tween will start in milliseconds. Defaults to 0, no delay.
  51489. * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This only effects this individual tween, not any chained tweens.
  51490. * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead.
  51491. * @return {Phaser.Tween} This Tween object.
  51492. */
  51493. to: function (properties, duration, ease, autoStart, delay, repeat, yoyo) {
  51494. if (duration === undefined || duration <= 0) { duration = 1000; }
  51495. if (ease === undefined || ease === null) { ease = Phaser.Easing.Default; }
  51496. if (autoStart === undefined) { autoStart = false; }
  51497. if (delay === undefined) { delay = 0; }
  51498. if (repeat === undefined) { repeat = 0; }
  51499. if (yoyo === undefined) { yoyo = false; }
  51500. if (typeof ease === 'string' && this.manager.easeMap[ease])
  51501. {
  51502. ease = this.manager.easeMap[ease];
  51503. }
  51504. if (this.isRunning)
  51505. {
  51506. console.warn('Phaser.Tween.to cannot be called after Tween.start');
  51507. return this;
  51508. }
  51509. this.timeline.push(new Phaser.TweenData(this).to(properties, duration, ease, delay, repeat, yoyo));
  51510. if (autoStart)
  51511. {
  51512. this.start();
  51513. }
  51514. return this;
  51515. },
  51516. /**
  51517. * Sets this tween to be a `from` tween on the properties given. A `from` tween sets the target to the destination value and tweens to its current value.
  51518. * For example a Sprite with an `x` coordinate of 100 tweened from `x` 500 would be set to `x` 500 and then tweened to `x` 100 by giving a properties object of `{ x: 500 }`.
  51519. * The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as "Circ".
  51520. * ".easeIn", ".easeOut" and "easeInOut" variants are all supported for all ease types.
  51521. *
  51522. * @method Phaser.Tween#from
  51523. * @param {object} properties - An object containing the properties you want to tween., such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object.
  51524. * @param {number} [duration=1000] - Duration of this tween in ms. Or if `Tween.frameBased` is true this represents the number of frames that should elapse.
  51525. * @param {function|string} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden.
  51526. * @param {boolean} [autoStart=false] - Set to `true` to allow this tween to start automatically. Otherwise call Tween.start().
  51527. * @param {number} [delay=0] - Delay before this tween will start in milliseconds. Defaults to 0, no delay.
  51528. * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This only effects this individual tween, not any chained tweens.
  51529. * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead.
  51530. * @return {Phaser.Tween} This Tween object.
  51531. */
  51532. from: function (properties, duration, ease, autoStart, delay, repeat, yoyo) {
  51533. if (duration === undefined) { duration = 1000; }
  51534. if (ease === undefined || ease === null) { ease = Phaser.Easing.Default; }
  51535. if (autoStart === undefined) { autoStart = false; }
  51536. if (delay === undefined) { delay = 0; }
  51537. if (repeat === undefined) { repeat = 0; }
  51538. if (yoyo === undefined) { yoyo = false; }
  51539. if (typeof ease === 'string' && this.manager.easeMap[ease])
  51540. {
  51541. ease = this.manager.easeMap[ease];
  51542. }
  51543. if (this.isRunning)
  51544. {
  51545. console.warn('Phaser.Tween.from cannot be called after Tween.start');
  51546. return this;
  51547. }
  51548. this.timeline.push(new Phaser.TweenData(this).from(properties, duration, ease, delay, repeat, yoyo));
  51549. if (autoStart)
  51550. {
  51551. this.start();
  51552. }
  51553. return this;
  51554. },
  51555. /**
  51556. * Starts the tween running. Can also be called by the autoStart parameter of `Tween.to` or `Tween.from`.
  51557. * This sets the `Tween.isRunning` property to `true` and dispatches a `Tween.onStart` signal.
  51558. * If the Tween has a delay set then nothing will start tweening until the delay has expired.
  51559. *
  51560. * @method Phaser.Tween#start
  51561. * @param {number} [index=0] - If this Tween contains child tweens you can specify which one to start from. The default is zero, i.e. the first tween created.
  51562. * @return {Phaser.Tween} This tween. Useful for method chaining.
  51563. */
  51564. start: function (index) {
  51565. if (index === undefined) { index = 0; }
  51566. if (this.game === null || this.target === null || this.timeline.length === 0 || this.isRunning)
  51567. {
  51568. return this;
  51569. }
  51570. // Populate the tween data
  51571. for (var i = 0; i < this.timeline.length; i++)
  51572. {
  51573. // Build our master property list with the starting values
  51574. for (var property in this.timeline[i].vEnd)
  51575. {
  51576. this.properties[property] = this.target[property] || 0;
  51577. if (!Array.isArray(this.properties[property]))
  51578. {
  51579. // Ensures we're using numbers, not strings
  51580. this.properties[property] *= 1.0;
  51581. }
  51582. }
  51583. }
  51584. for (var i = 0; i < this.timeline.length; i++)
  51585. {
  51586. this.timeline[i].loadValues();
  51587. }
  51588. this.manager.add(this);
  51589. this.isRunning = true;
  51590. if (index < 0 || index > this.timeline.length - 1)
  51591. {
  51592. index = 0;
  51593. }
  51594. this.current = index;
  51595. this.timeline[this.current].start();
  51596. return this;
  51597. },
  51598. /**
  51599. * Stops the tween if running and flags it for deletion from the TweenManager.
  51600. * If called directly the `Tween.onComplete` signal is not dispatched and no chained tweens are started unless the complete parameter is set to `true`.
  51601. * If you just wish to pause a tween then use Tween.pause instead.
  51602. *
  51603. * @method Phaser.Tween#stop
  51604. * @param {boolean} [complete=false] - Set to `true` to dispatch the Tween.onComplete signal.
  51605. * @return {Phaser.Tween} This tween. Useful for method chaining.
  51606. */
  51607. stop: function (complete) {
  51608. if (complete === undefined) { complete = false; }
  51609. this.isRunning = false;
  51610. this._onUpdateCallback = null;
  51611. this._onUpdateCallbackContext = null;
  51612. if (complete)
  51613. {
  51614. this.onComplete.dispatch(this.target, this);
  51615. this._hasStarted = false;
  51616. if (this.chainedTween)
  51617. {
  51618. this.chainedTween.start();
  51619. }
  51620. }
  51621. this.manager.remove(this);
  51622. return this;
  51623. },
  51624. /**
  51625. * Updates either a single TweenData or all TweenData objects properties to the given value.
  51626. * Used internally by methods like Tween.delay, Tween.yoyo, etc. but can also be called directly if you know which property you want to tweak.
  51627. * The property is not checked, so if you pass an invalid one you'll generate a run-time error.
  51628. *
  51629. * @method Phaser.Tween#updateTweenData
  51630. * @param {string} property - The property to update.
  51631. * @param {number|function} value - The value to set the property to.
  51632. * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the delay on all the children.
  51633. * @return {Phaser.Tween} This tween. Useful for method chaining.
  51634. */
  51635. updateTweenData: function (property, value, index) {
  51636. if (this.timeline.length === 0) { return this; }
  51637. if (index === undefined) { index = 0; }
  51638. if (index === -1)
  51639. {
  51640. for (var i = 0; i < this.timeline.length; i++)
  51641. {
  51642. this.timeline[i][property] = value;
  51643. }
  51644. }
  51645. else
  51646. {
  51647. this.timeline[index][property] = value;
  51648. }
  51649. return this;
  51650. },
  51651. /**
  51652. * Sets the delay in milliseconds before this tween will start. If there are child tweens it sets the delay before the first child starts.
  51653. * The delay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween.
  51654. * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to delay.
  51655. * If you have child tweens and pass -1 as the index value it sets the delay across all of them.
  51656. *
  51657. * @method Phaser.Tween#delay
  51658. * @param {number} duration - The amount of time in ms that the Tween should wait until it begins once started is called. Set to zero to remove any active delay.
  51659. * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the delay on all the children.
  51660. * @return {Phaser.Tween} This tween. Useful for method chaining.
  51661. */
  51662. delay: function (duration, index) {
  51663. return this.updateTweenData('delay', duration, index);
  51664. },
  51665. /**
  51666. * Sets the number of times this tween will repeat.
  51667. * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to repeat.
  51668. * If you have child tweens and pass -1 as the index value it sets the number of times they'll repeat across all of them.
  51669. * If you wish to define how many times this Tween and all children will repeat see Tween.repeatAll.
  51670. *
  51671. * @method Phaser.Tween#repeat
  51672. * @param {number} total - How many times a tween should repeat before completing. Set to zero to remove an active repeat. Set to -1 to repeat forever.
  51673. * @param {number} [repeat=0] - This is the amount of time to pause (in ms) before the repeat will start.
  51674. * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the repeat value on all the children.
  51675. * @return {Phaser.Tween} This tween. Useful for method chaining.
  51676. */
  51677. repeat: function (total, repeatDelay, index) {
  51678. if (repeatDelay === undefined) { repeatDelay = 0; }
  51679. this.updateTweenData('repeatCounter', total, index);
  51680. return this.updateTweenData('repeatDelay', repeatDelay, index);
  51681. },
  51682. /**
  51683. * Sets the delay in milliseconds before this tween will repeat itself.
  51684. * The repeatDelay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween.
  51685. * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to set repeatDelay on.
  51686. * If you have child tweens and pass -1 as the index value it sets the repeatDelay across all of them.
  51687. *
  51688. * @method Phaser.Tween#repeatDelay
  51689. * @param {number} duration - The amount of time in ms that the Tween should wait until it repeats or yoyos once start is called. Set to zero to remove any active repeatDelay.
  51690. * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the repeatDelay on all the children.
  51691. * @return {Phaser.Tween} This tween. Useful for method chaining.
  51692. */
  51693. repeatDelay: function (duration, index) {
  51694. return this.updateTweenData('repeatDelay', duration, index);
  51695. },
  51696. /**
  51697. * A Tween that has yoyo set to true will run through from its starting values to its end values and then play back in reverse from end to start.
  51698. * Used in combination with repeat you can create endless loops.
  51699. * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to yoyo.
  51700. * If you have child tweens and pass -1 as the index value it sets the yoyo property across all of them.
  51701. * If you wish to yoyo this Tween and all of its children then see Tween.yoyoAll.
  51702. *
  51703. * @method Phaser.Tween#yoyo
  51704. * @param {boolean} enable - Set to true to yoyo this tween, or false to disable an already active yoyo.
  51705. * @param {number} [yoyoDelay=0] - This is the amount of time to pause (in ms) before the yoyo will start.
  51706. * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set yoyo on all the children.
  51707. * @return {Phaser.Tween} This tween. Useful for method chaining.
  51708. */
  51709. yoyo: function(enable, yoyoDelay, index) {
  51710. if (yoyoDelay === undefined) { yoyoDelay = 0; }
  51711. this.updateTweenData('yoyo', enable, index);
  51712. return this.updateTweenData('yoyoDelay', yoyoDelay, index);
  51713. },
  51714. /**
  51715. * Sets the delay in milliseconds before this tween will run a yoyo (only applies if yoyo is enabled).
  51716. * The repeatDelay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween.
  51717. * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to set repeatDelay on.
  51718. * If you have child tweens and pass -1 as the index value it sets the repeatDelay across all of them.
  51719. *
  51720. * @method Phaser.Tween#yoyoDelay
  51721. * @param {number} duration - The amount of time in ms that the Tween should wait until it repeats or yoyos once start is called. Set to zero to remove any active yoyoDelay.
  51722. * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the yoyoDelay on all the children.
  51723. * @return {Phaser.Tween} This tween. Useful for method chaining.
  51724. */
  51725. yoyoDelay: function (duration, index) {
  51726. return this.updateTweenData('yoyoDelay', duration, index);
  51727. },
  51728. /**
  51729. * Set easing function this tween will use, i.e. Phaser.Easing.Linear.None.
  51730. * The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as "Circ".
  51731. * ".easeIn", ".easeOut" and "easeInOut" variants are all supported for all ease types.
  51732. * If you have child tweens and pass -1 as the index value it sets the easing function defined here across all of them.
  51733. *
  51734. * @method Phaser.Tween#easing
  51735. * @param {function|string} ease - The easing function this tween will use, i.e. Phaser.Easing.Linear.None.
  51736. * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the easing function on all children.
  51737. * @return {Phaser.Tween} This tween. Useful for method chaining.
  51738. */
  51739. easing: function (ease, index) {
  51740. if (typeof ease === 'string' && this.manager.easeMap[ease])
  51741. {
  51742. ease = this.manager.easeMap[ease];
  51743. }
  51744. return this.updateTweenData('easingFunction', ease, index);
  51745. },
  51746. /**
  51747. * Sets the interpolation function the tween will use. By default it uses Phaser.Math.linearInterpolation.
  51748. * Also available: Phaser.Math.bezierInterpolation and Phaser.Math.catmullRomInterpolation.
  51749. * The interpolation function is only used if the target properties is an array.
  51750. * If you have child tweens and pass -1 as the index value and it will set the interpolation function across all of them.
  51751. *
  51752. * @method Phaser.Tween#interpolation
  51753. * @param {function} interpolation - The interpolation function to use (Phaser.Math.linearInterpolation by default)
  51754. * @param {object} [context] - The context under which the interpolation function will be run.
  51755. * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the interpolation function on all children.
  51756. * @return {Phaser.Tween} This tween. Useful for method chaining.
  51757. */
  51758. interpolation: function (interpolation, context, index) {
  51759. if (context === undefined) { context = Phaser.Math; }
  51760. this.updateTweenData('interpolationFunction', interpolation, index);
  51761. return this.updateTweenData('interpolationContext', context, index);
  51762. },
  51763. /**
  51764. * Set how many times this tween and all of its children will repeat.
  51765. * A tween (A) with 3 children (B,C,D) with a `repeatAll` value of 2 would play as: ABCDABCD before completing.
  51766. *
  51767. * @method Phaser.Tween#repeatAll
  51768. * @param {number} [total=0] - How many times this tween and all children should repeat before completing. Set to zero to remove an active repeat. Set to -1 to repeat forever.
  51769. * @return {Phaser.Tween} This tween. Useful for method chaining.
  51770. */
  51771. repeatAll: function (total) {
  51772. if (total === undefined) { total = 0; }
  51773. this.repeatCounter = total;
  51774. return this;
  51775. },
  51776. /**
  51777. * This method allows you to chain tweens together. Any tween chained to this tween will have its `Tween.start` method called
  51778. * as soon as this tween completes. If this tween never completes (i.e. repeatAll or loop is set) then the chain will never progress.
  51779. * Note that `Tween.onComplete` will fire when *this* tween completes, not when the whole chain completes.
  51780. * For that you should listen to `onComplete` on the final tween in your chain.
  51781. *
  51782. * If you pass multiple tweens to this method they will be joined into a single long chain.
  51783. * For example if this is Tween A and you pass in B, C and D then B will be chained to A, C will be chained to B and D will be chained to C.
  51784. * Any previously chained tweens that may have been set will be overwritten.
  51785. *
  51786. * @method Phaser.Tween#chain
  51787. * @param {...Phaser.Tween} tweens - One or more tweens that will be chained to this one.
  51788. * @return {Phaser.Tween} This tween. Useful for method chaining.
  51789. */
  51790. chain: function () {
  51791. var i = arguments.length;
  51792. while (i--)
  51793. {
  51794. if (i > 0)
  51795. {
  51796. arguments[i - 1].chainedTween = arguments[i];
  51797. }
  51798. else
  51799. {
  51800. this.chainedTween = arguments[i];
  51801. }
  51802. }
  51803. return this;
  51804. },
  51805. /**
  51806. * Enables the looping of this tween. The tween will loop forever, and onComplete will never fire.
  51807. *
  51808. * If `value` is `true` then this is the same as setting `Tween.repeatAll(-1)`.
  51809. * If `value` is `false` it is the same as setting `Tween.repeatAll(0)` and will reset the `repeatCounter` to zero.
  51810. *
  51811. * Usage:
  51812. * game.add.tween(p).to({ x: 700 }, 1000, Phaser.Easing.Linear.None, true)
  51813. * .to({ y: 300 }, 1000, Phaser.Easing.Linear.None)
  51814. * .to({ x: 0 }, 1000, Phaser.Easing.Linear.None)
  51815. * .to({ y: 0 }, 1000, Phaser.Easing.Linear.None)
  51816. * .loop();
  51817. * @method Phaser.Tween#loop
  51818. * @param {boolean} [value=true] - If `true` this tween will loop once it reaches the end. Set to `false` to remove an active loop.
  51819. * @return {Phaser.Tween} This tween. Useful for method chaining.
  51820. */
  51821. loop: function (value) {
  51822. if (value === undefined) { value = true; }
  51823. this.repeatCounter = (value) ? -1 : 0;
  51824. return this;
  51825. },
  51826. /**
  51827. * Sets a callback to be fired each time this tween updates.
  51828. *
  51829. * @method Phaser.Tween#onUpdateCallback
  51830. * @param {function} callback - The callback to invoke each time this tween is updated. Set to `null` to remove an already active callback.
  51831. * @param {object} callbackContext - The context in which to call the onUpdate callback.
  51832. * @return {Phaser.Tween} This tween. Useful for method chaining.
  51833. */
  51834. onUpdateCallback: function (callback, callbackContext) {
  51835. this._onUpdateCallback = callback;
  51836. this._onUpdateCallbackContext = callbackContext;
  51837. return this;
  51838. },
  51839. /**
  51840. * Pauses the tween. Resume playback with Tween.resume.
  51841. *
  51842. * @method Phaser.Tween#pause
  51843. */
  51844. pause: function () {
  51845. this.isPaused = true;
  51846. this._codePaused = true;
  51847. this._pausedTime = this.game.time.time;
  51848. },
  51849. /**
  51850. * This is called by the core Game loop. Do not call it directly, instead use Tween.pause.
  51851. *
  51852. * @private
  51853. * @method Phaser.Tween#_pause
  51854. */
  51855. _pause: function () {
  51856. if (!this._codePaused)
  51857. {
  51858. this.isPaused = true;
  51859. this._pausedTime = this.game.time.time;
  51860. }
  51861. },
  51862. /**
  51863. * Resumes a paused tween.
  51864. *
  51865. * @method Phaser.Tween#resume
  51866. */
  51867. resume: function () {
  51868. if (this.isPaused)
  51869. {
  51870. this.isPaused = false;
  51871. this._codePaused = false;
  51872. for (var i = 0; i < this.timeline.length; i++)
  51873. {
  51874. if (!this.timeline[i].isRunning)
  51875. {
  51876. this.timeline[i].startTime += (this.game.time.time - this._pausedTime);
  51877. }
  51878. }
  51879. }
  51880. },
  51881. /**
  51882. * This is called by the core Game loop. Do not call it directly, instead use Tween.pause.
  51883. * @method Phaser.Tween#_resume
  51884. * @private
  51885. */
  51886. _resume: function () {
  51887. if (this._codePaused)
  51888. {
  51889. return;
  51890. }
  51891. else
  51892. {
  51893. this.resume();
  51894. }
  51895. },
  51896. /**
  51897. * Core tween update function called by the TweenManager. Does not need to be invoked directly.
  51898. *
  51899. * @method Phaser.Tween#update
  51900. * @param {number} time - A timestamp passed in by the TweenManager.
  51901. * @return {boolean} false if the tween and all child tweens have completed and should be deleted from the manager, otherwise true (still active).
  51902. */
  51903. update: function (time) {
  51904. if (this.pendingDelete || !this.target)
  51905. {
  51906. return false;
  51907. }
  51908. if (this.isPaused)
  51909. {
  51910. return true;
  51911. }
  51912. var status = this.timeline[this.current].update(time);
  51913. if (status === Phaser.TweenData.PENDING)
  51914. {
  51915. return true;
  51916. }
  51917. else if (status === Phaser.TweenData.RUNNING)
  51918. {
  51919. if (!this._hasStarted)
  51920. {
  51921. this.onStart.dispatch(this.target, this);
  51922. this._hasStarted = true;
  51923. }
  51924. if (this._onUpdateCallback !== null)
  51925. {
  51926. this._onUpdateCallback.call(this._onUpdateCallbackContext, this, this.timeline[this.current].value, this.timeline[this.current]);
  51927. }
  51928. // In case the update callback modifies this tween
  51929. return this.isRunning;
  51930. }
  51931. else if (status === Phaser.TweenData.LOOPED)
  51932. {
  51933. if (this.timeline[this.current].repeatCounter === -1)
  51934. {
  51935. this.onLoop.dispatch(this.target, this);
  51936. }
  51937. else
  51938. {
  51939. this.onRepeat.dispatch(this.target, this);
  51940. }
  51941. return true;
  51942. }
  51943. else if (status === Phaser.TweenData.COMPLETE)
  51944. {
  51945. var complete = false;
  51946. // What now?
  51947. if (this.reverse)
  51948. {
  51949. this.current--;
  51950. if (this.current < 0)
  51951. {
  51952. this.current = this.timeline.length - 1;
  51953. complete = true;
  51954. }
  51955. }
  51956. else
  51957. {
  51958. this.current++;
  51959. if (this.current === this.timeline.length)
  51960. {
  51961. this.current = 0;
  51962. complete = true;
  51963. }
  51964. }
  51965. if (complete)
  51966. {
  51967. // We've reached the start or end of the child tweens (depending on Tween.reverse), should we repeat it?
  51968. if (this.repeatCounter === -1)
  51969. {
  51970. this.timeline[this.current].start();
  51971. this.onLoop.dispatch(this.target, this);
  51972. return true;
  51973. }
  51974. else if (this.repeatCounter > 0)
  51975. {
  51976. this.repeatCounter--;
  51977. this.timeline[this.current].start();
  51978. this.onRepeat.dispatch(this.target, this);
  51979. return true;
  51980. }
  51981. else
  51982. {
  51983. // No more repeats and no more children, so we're done
  51984. this.isRunning = false;
  51985. this.onComplete.dispatch(this.target, this);
  51986. this._hasStarted = false;
  51987. if (this.chainedTween)
  51988. {
  51989. this.chainedTween.start();
  51990. }
  51991. return false;
  51992. }
  51993. }
  51994. else
  51995. {
  51996. // We've still got some children to go
  51997. this.onChildComplete.dispatch(this.target, this);
  51998. this.timeline[this.current].start();
  51999. return true;
  52000. }
  52001. }
  52002. },
  52003. /**
  52004. * This will generate an array populated with the tweened object values from start to end.
  52005. * It works by running the tween simulation at the given frame rate based on the values set-up in Tween.to and Tween.from.
  52006. * It ignores delay and repeat counts and any chained tweens, but does include child tweens.
  52007. * Just one play through of the tween data is returned, including yoyo if set.
  52008. *
  52009. * @method Phaser.Tween#generateData
  52010. * @param {number} [frameRate=60] - The speed in frames per second that the data should be generated at. The higher the value, the larger the array it creates.
  52011. * @param {array} [data] - If given the generated data will be appended to this array, otherwise a new array will be returned.
  52012. * @return {array} An array of tweened values.
  52013. */
  52014. generateData: function (frameRate, data) {
  52015. if (this.game === null || this.target === null)
  52016. {
  52017. return null;
  52018. }
  52019. if (frameRate === undefined) { frameRate = 60; }
  52020. if (data === undefined) { data = []; }
  52021. // Populate the tween data
  52022. for (var i = 0; i < this.timeline.length; i++)
  52023. {
  52024. // Build our master property list with the starting values
  52025. for (var property in this.timeline[i].vEnd)
  52026. {
  52027. this.properties[property] = this.target[property] || 0;
  52028. if (!Array.isArray(this.properties[property]))
  52029. {
  52030. // Ensures we're using numbers, not strings
  52031. this.properties[property] *= 1.0;
  52032. }
  52033. }
  52034. }
  52035. for (var i = 0; i < this.timeline.length; i++)
  52036. {
  52037. this.timeline[i].loadValues();
  52038. }
  52039. for (var i = 0; i < this.timeline.length; i++)
  52040. {
  52041. data = data.concat(this.timeline[i].generateData(frameRate));
  52042. }
  52043. return data;
  52044. }
  52045. };
  52046. /**
  52047. * @name Phaser.Tween#totalDuration
  52048. * @property {Phaser.TweenData} totalDuration - Gets the total duration of this Tween, including all child tweens, in milliseconds.
  52049. */
  52050. Object.defineProperty(Phaser.Tween.prototype, 'totalDuration', {
  52051. get: function () {
  52052. var total = 0;
  52053. for (var i = 0; i < this.timeline.length; i++)
  52054. {
  52055. total += this.timeline[i].duration;
  52056. }
  52057. return total;
  52058. }
  52059. });
  52060. Phaser.Tween.prototype.constructor = Phaser.Tween;
  52061. /**
  52062. * @author Richard Davey <rich@photonstorm.com>
  52063. * @copyright 2016 Photon Storm Ltd.
  52064. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  52065. */
  52066. /**
  52067. * A Phaser.Tween contains at least one TweenData object. It contains all of the tween data values, such as the
  52068. * starting and ending values, the ease function, interpolation and duration. The Tween acts as a timeline manager for
  52069. * TweenData objects and can contain multiple TweenData objects.
  52070. *
  52071. * @class Phaser.TweenData
  52072. * @constructor
  52073. * @param {Phaser.Tween} parent - The Tween that owns this TweenData object.
  52074. */
  52075. Phaser.TweenData = function (parent) {
  52076. /**
  52077. * @property {Phaser.Tween} parent - The Tween which owns this TweenData.
  52078. */
  52079. this.parent = parent;
  52080. /**
  52081. * @property {Phaser.Game} game - A reference to the currently running Game.
  52082. */
  52083. this.game = parent.game;
  52084. /**
  52085. * @property {object} vStart - An object containing the values at the start of the tween.
  52086. * @private
  52087. */
  52088. this.vStart = {};
  52089. /**
  52090. * @property {object} vStartCache - Cached starting values.
  52091. * @private
  52092. */
  52093. this.vStartCache = {};
  52094. /**
  52095. * @property {object} vEnd - An object containing the values at the end of the tween.
  52096. * @private
  52097. */
  52098. this.vEnd = {};
  52099. /**
  52100. * @property {object} vEndCache - Cached ending values.
  52101. * @private
  52102. */
  52103. this.vEndCache = {};
  52104. /**
  52105. * @property {number} duration - The duration of the tween in ms.
  52106. * @default
  52107. */
  52108. this.duration = 1000;
  52109. /**
  52110. * @property {number} percent - A value between 0 and 1 that represents how far through the duration this tween is.
  52111. * @readonly
  52112. */
  52113. this.percent = 0;
  52114. /**
  52115. * @property {number} value - The current calculated value.
  52116. * @readonly
  52117. */
  52118. this.value = 0;
  52119. /**
  52120. * @property {number} repeatCounter - If the Tween is set to repeat this contains the current repeat count.
  52121. */
  52122. this.repeatCounter = 0;
  52123. /**
  52124. * @property {number} repeatDelay - The amount of time in ms between repeats of this tween.
  52125. */
  52126. this.repeatDelay = 0;
  52127. /**
  52128. * @property {number} repeatTotal - The total number of times this Tween will repeat.
  52129. * @readonly
  52130. */
  52131. this.repeatTotal = 0;
  52132. /**
  52133. * @property {boolean} interpolate - True if the Tween will use interpolation (i.e. is an Array to Array tween)
  52134. * @default
  52135. */
  52136. this.interpolate = false;
  52137. /**
  52138. * @property {boolean} yoyo - True if the Tween is set to yoyo, otherwise false.
  52139. * @default
  52140. */
  52141. this.yoyo = false;
  52142. /**
  52143. * @property {number} yoyoDelay - The amount of time in ms between yoyos of this tween.
  52144. */
  52145. this.yoyoDelay = 0;
  52146. /**
  52147. * @property {boolean} inReverse - When a Tween is yoyoing this value holds if it's currently playing forwards (false) or in reverse (true).
  52148. * @default
  52149. */
  52150. this.inReverse = false;
  52151. /**
  52152. * @property {number} delay - The amount to delay by until the Tween starts (in ms). Only applies to the start, use repeatDelay to handle repeats.
  52153. * @default
  52154. */
  52155. this.delay = 0;
  52156. /**
  52157. * @property {number} dt - Current time value.
  52158. */
  52159. this.dt = 0;
  52160. /**
  52161. * @property {number} startTime - The time the Tween started or null if it hasn't yet started.
  52162. */
  52163. this.startTime = null;
  52164. /**
  52165. * @property {function} easingFunction - The easing function used for the Tween.
  52166. * @default Phaser.Easing.Default
  52167. */
  52168. this.easingFunction = Phaser.Easing.Default;
  52169. /**
  52170. * @property {function} interpolationFunction - The interpolation function used for the Tween.
  52171. * @default Phaser.Math.linearInterpolation
  52172. */
  52173. this.interpolationFunction = Phaser.Math.linearInterpolation;
  52174. /**
  52175. * @property {object} interpolationContext - The interpolation function context used for the Tween.
  52176. * @default Phaser.Math
  52177. */
  52178. this.interpolationContext = Phaser.Math;
  52179. /**
  52180. * @property {boolean} isRunning - If the tween is running this is set to `true`. Unless Phaser.Tween a TweenData that is waiting for a delay to expire is *not* considered as running.
  52181. * @default
  52182. */
  52183. this.isRunning = false;
  52184. /**
  52185. * @property {boolean} isFrom - Is this a from tween or a to tween?
  52186. * @default
  52187. */
  52188. this.isFrom = false;
  52189. };
  52190. /**
  52191. * @constant
  52192. * @type {number}
  52193. */
  52194. Phaser.TweenData.PENDING = 0;
  52195. /**
  52196. * @constant
  52197. * @type {number}
  52198. */
  52199. Phaser.TweenData.RUNNING = 1;
  52200. /**
  52201. * @constant
  52202. * @type {number}
  52203. */
  52204. Phaser.TweenData.LOOPED = 2;
  52205. /**
  52206. * @constant
  52207. * @type {number}
  52208. */
  52209. Phaser.TweenData.COMPLETE = 3;
  52210. Phaser.TweenData.prototype = {
  52211. /**
  52212. * Sets this tween to be a `to` tween on the properties given. A `to` tween starts at the current value and tweens to the destination value given.
  52213. * For example a Sprite with an `x` coordinate of 100 could be tweened to `x` 200 by giving a properties object of `{ x: 200 }`.
  52214. *
  52215. * @method Phaser.TweenData#to
  52216. * @param {object} properties - The properties you want to tween, such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object.
  52217. * @param {number} [duration=1000] - Duration of this tween in ms.
  52218. * @param {function} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden at will.
  52219. * @param {number} [delay=0] - Delay before this tween will start, defaults to 0 (no delay). Value given is in ms.
  52220. * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This ignores any chained tweens.
  52221. * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead.
  52222. * @return {Phaser.TweenData} This Tween object.
  52223. */
  52224. to: function (properties, duration, ease, delay, repeat, yoyo) {
  52225. this.vEnd = properties;
  52226. this.duration = duration;
  52227. this.easingFunction = ease;
  52228. this.delay = delay;
  52229. this.repeatTotal = repeat;
  52230. this.yoyo = yoyo;
  52231. this.isFrom = false;
  52232. return this;
  52233. },
  52234. /**
  52235. * Sets this tween to be a `from` tween on the properties given. A `from` tween sets the target to the destination value and tweens to its current value.
  52236. * For example a Sprite with an `x` coordinate of 100 tweened from `x` 500 would be set to `x` 500 and then tweened to `x` 100 by giving a properties object of `{ x: 500 }`.
  52237. *
  52238. * @method Phaser.TweenData#from
  52239. * @param {object} properties - The properties you want to tween, such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object.
  52240. * @param {number} [duration=1000] - Duration of this tween in ms.
  52241. * @param {function} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden at will.
  52242. * @param {number} [delay=0] - Delay before this tween will start, defaults to 0 (no delay). Value given is in ms.
  52243. * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This ignores any chained tweens.
  52244. * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead.
  52245. * @return {Phaser.TweenData} This Tween object.
  52246. */
  52247. from: function (properties, duration, ease, delay, repeat, yoyo) {
  52248. this.vEnd = properties;
  52249. this.duration = duration;
  52250. this.easingFunction = ease;
  52251. this.delay = delay;
  52252. this.repeatTotal = repeat;
  52253. this.yoyo = yoyo;
  52254. this.isFrom = true;
  52255. return this;
  52256. },
  52257. /**
  52258. * Starts the Tween running.
  52259. *
  52260. * @method Phaser.TweenData#start
  52261. * @return {Phaser.TweenData} This Tween object.
  52262. */
  52263. start: function () {
  52264. this.startTime = this.game.time.time + this.delay;
  52265. if (this.parent.reverse)
  52266. {
  52267. this.dt = this.duration;
  52268. }
  52269. else
  52270. {
  52271. this.dt = 0;
  52272. }
  52273. if (this.delay > 0)
  52274. {
  52275. this.isRunning = false;
  52276. }
  52277. else
  52278. {
  52279. this.isRunning = true;
  52280. }
  52281. if (this.isFrom)
  52282. {
  52283. // Reverse them all and instant set them
  52284. for (var property in this.vStartCache)
  52285. {
  52286. this.vStart[property] = this.vEndCache[property];
  52287. this.vEnd[property] = this.vStartCache[property];
  52288. this.parent.target[property] = this.vStart[property];
  52289. }
  52290. }
  52291. this.value = 0;
  52292. this.yoyoCounter = 0;
  52293. this.repeatCounter = this.repeatTotal;
  52294. return this;
  52295. },
  52296. /**
  52297. * Loads the values from the target object into this Tween.
  52298. *
  52299. * @private
  52300. * @method Phaser.TweenData#loadValues
  52301. * @return {Phaser.TweenData} This Tween object.
  52302. */
  52303. loadValues: function () {
  52304. for (var property in this.parent.properties)
  52305. {
  52306. // Load the property from the parent object
  52307. this.vStart[property] = this.parent.properties[property];
  52308. // Check if an Array was provided as property value
  52309. if (Array.isArray(this.vEnd[property]))
  52310. {
  52311. if (this.vEnd[property].length === 0)
  52312. {
  52313. continue;
  52314. }
  52315. if (this.percent === 0)
  52316. {
  52317. // Put the start value at the beginning of the array
  52318. // but we only want to do this once, if the Tween hasn't run before
  52319. this.vEnd[property] = [this.vStart[property]].concat(this.vEnd[property]);
  52320. }
  52321. }
  52322. if (typeof this.vEnd[property] !== 'undefined')
  52323. {
  52324. if (typeof this.vEnd[property] === 'string')
  52325. {
  52326. // Parses relative end values with start as base (e.g.: +10, -3)
  52327. this.vEnd[property] = this.vStart[property] + parseFloat(this.vEnd[property], 10);
  52328. }
  52329. this.parent.properties[property] = this.vEnd[property];
  52330. }
  52331. else
  52332. {
  52333. // Null tween
  52334. this.vEnd[property] = this.vStart[property];
  52335. }
  52336. this.vStartCache[property] = this.vStart[property];
  52337. this.vEndCache[property] = this.vEnd[property];
  52338. }
  52339. return this;
  52340. },
  52341. /**
  52342. * Updates this Tween. This is called automatically by Phaser.Tween.
  52343. *
  52344. * @protected
  52345. * @method Phaser.TweenData#update
  52346. * @param {number} time - A timestamp passed in by the Tween parent.
  52347. * @return {number} The current status of this Tween. One of the Phaser.TweenData constants: PENDING, RUNNING, LOOPED or COMPLETE.
  52348. */
  52349. update: function (time) {
  52350. if (!this.isRunning)
  52351. {
  52352. if (time >= this.startTime)
  52353. {
  52354. this.isRunning = true;
  52355. }
  52356. else
  52357. {
  52358. return Phaser.TweenData.PENDING;
  52359. }
  52360. }
  52361. else
  52362. {
  52363. // Is Running, but is waiting to repeat
  52364. if (time < this.startTime)
  52365. {
  52366. return Phaser.TweenData.RUNNING;
  52367. }
  52368. }
  52369. var ms = (this.parent.frameBased) ? this.game.time.physicsElapsedMS : this.game.time.elapsedMS;
  52370. if (this.parent.reverse)
  52371. {
  52372. this.dt -= ms * this.parent.timeScale;
  52373. this.dt = Math.max(this.dt, 0);
  52374. }
  52375. else
  52376. {
  52377. this.dt += ms * this.parent.timeScale;
  52378. this.dt = Math.min(this.dt, this.duration);
  52379. }
  52380. this.percent = this.dt / this.duration;
  52381. this.value = this.easingFunction(this.percent);
  52382. for (var property in this.vEnd)
  52383. {
  52384. var start = this.vStart[property];
  52385. var end = this.vEnd[property];
  52386. if (Array.isArray(end))
  52387. {
  52388. this.parent.target[property] = this.interpolationFunction.call(this.interpolationContext, end, this.value);
  52389. }
  52390. else
  52391. {
  52392. this.parent.target[property] = start + ((end - start) * this.value);
  52393. }
  52394. }
  52395. if ((!this.parent.reverse && this.percent === 1) || (this.parent.reverse && this.percent === 0))
  52396. {
  52397. return this.repeat();
  52398. }
  52399. return Phaser.TweenData.RUNNING;
  52400. },
  52401. /**
  52402. * This will generate an array populated with the tweened object values from start to end.
  52403. * It works by running the tween simulation at the given frame rate based on the values set-up in Tween.to and Tween.from.
  52404. * Just one play through of the tween data is returned, including yoyo if set.
  52405. *
  52406. * @method Phaser.TweenData#generateData
  52407. * @param {number} [frameRate=60] - The speed in frames per second that the data should be generated at. The higher the value, the larger the array it creates.
  52408. * @return {array} An array of tweened values.
  52409. */
  52410. generateData: function (frameRate) {
  52411. if (this.parent.reverse)
  52412. {
  52413. this.dt = this.duration;
  52414. }
  52415. else
  52416. {
  52417. this.dt = 0;
  52418. }
  52419. var data = [];
  52420. var complete = false;
  52421. var fps = (1 / frameRate) * 1000;
  52422. do
  52423. {
  52424. if (this.parent.reverse)
  52425. {
  52426. this.dt -= fps;
  52427. this.dt = Math.max(this.dt, 0);
  52428. }
  52429. else
  52430. {
  52431. this.dt += fps;
  52432. this.dt = Math.min(this.dt, this.duration);
  52433. }
  52434. this.percent = this.dt / this.duration;
  52435. this.value = this.easingFunction(this.percent);
  52436. var blob = {};
  52437. for (var property in this.vEnd)
  52438. {
  52439. var start = this.vStart[property];
  52440. var end = this.vEnd[property];
  52441. if (Array.isArray(end))
  52442. {
  52443. blob[property] = this.interpolationFunction(end, this.value);
  52444. }
  52445. else
  52446. {
  52447. blob[property] = start + ((end - start) * this.value);
  52448. }
  52449. }
  52450. data.push(blob);
  52451. if ((!this.parent.reverse && this.percent === 1) || (this.parent.reverse && this.percent === 0))
  52452. {
  52453. complete = true;
  52454. }
  52455. } while (!complete);
  52456. if (this.yoyo)
  52457. {
  52458. var reversed = data.slice();
  52459. reversed.reverse();
  52460. data = data.concat(reversed);
  52461. }
  52462. return data;
  52463. },
  52464. /**
  52465. * Checks if this Tween is meant to repeat or yoyo and handles doing so.
  52466. *
  52467. * @private
  52468. * @method Phaser.TweenData#repeat
  52469. * @return {number} Either Phaser.TweenData.LOOPED or Phaser.TweenData.COMPLETE.
  52470. */
  52471. repeat: function () {
  52472. // If not a yoyo and repeatCounter = 0 then we're done
  52473. if (this.yoyo)
  52474. {
  52475. // We're already in reverse mode, which means the yoyo has finished and there's no repeats, so end
  52476. if (this.inReverse && this.repeatCounter === 0)
  52477. {
  52478. // Restore the properties
  52479. for (var property in this.vStartCache)
  52480. {
  52481. this.vStart[property] = this.vStartCache[property];
  52482. this.vEnd[property] = this.vEndCache[property];
  52483. }
  52484. this.inReverse = false;
  52485. return Phaser.TweenData.COMPLETE;
  52486. }
  52487. this.inReverse = !this.inReverse;
  52488. }
  52489. else
  52490. {
  52491. if (this.repeatCounter === 0)
  52492. {
  52493. return Phaser.TweenData.COMPLETE;
  52494. }
  52495. }
  52496. if (this.inReverse)
  52497. {
  52498. // If inReverse we're going from vEnd to vStartCache
  52499. for (var property in this.vStartCache)
  52500. {
  52501. this.vStart[property] = this.vEndCache[property];
  52502. this.vEnd[property] = this.vStartCache[property];
  52503. }
  52504. }
  52505. else
  52506. {
  52507. // If not inReverse we're just repopulating the cache again
  52508. for (var property in this.vStartCache)
  52509. {
  52510. this.vStart[property] = this.vStartCache[property];
  52511. this.vEnd[property] = this.vEndCache[property];
  52512. }
  52513. // -1 means repeat forever, otherwise decrement the repeatCounter
  52514. // We only decrement this counter if the tween isn't doing a yoyo, as that doesn't count towards the repeat total
  52515. if (this.repeatCounter > 0)
  52516. {
  52517. this.repeatCounter--;
  52518. }
  52519. }
  52520. this.startTime = this.game.time.time;
  52521. if (this.yoyo && this.inReverse)
  52522. {
  52523. this.startTime += this.yoyoDelay;
  52524. }
  52525. else if (!this.inReverse)
  52526. {
  52527. this.startTime += this.repeatDelay;
  52528. }
  52529. if (this.parent.reverse)
  52530. {
  52531. this.dt = this.duration;
  52532. }
  52533. else
  52534. {
  52535. this.dt = 0;
  52536. }
  52537. return Phaser.TweenData.LOOPED;
  52538. }
  52539. };
  52540. Phaser.TweenData.prototype.constructor = Phaser.TweenData;
  52541. /* jshint curly: false */
  52542. /**
  52543. * @author Richard Davey <rich@photonstorm.com>
  52544. * @copyright 2016 Photon Storm Ltd.
  52545. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  52546. */
  52547. /**
  52548. * A collection of easing methods defining ease-in and ease-out curves.
  52549. *
  52550. * @class Phaser.Easing
  52551. */
  52552. Phaser.Easing = {
  52553. /**
  52554. * Linear easing.
  52555. *
  52556. * @class Phaser.Easing.Linear
  52557. */
  52558. Linear: {
  52559. /**
  52560. * Linear Easing (no variation).
  52561. *
  52562. * @method Phaser.Easing.Linear#None
  52563. * @param {number} k - The value to be tweened.
  52564. * @returns {number} k.
  52565. */
  52566. None: function ( k ) {
  52567. return k;
  52568. }
  52569. },
  52570. /**
  52571. * Quadratic easing.
  52572. *
  52573. * @class Phaser.Easing.Quadratic
  52574. */
  52575. Quadratic: {
  52576. /**
  52577. * Ease-in.
  52578. *
  52579. * @method Phaser.Easing.Quadratic#In
  52580. * @param {number} k - The value to be tweened.
  52581. * @returns {number} k^2.
  52582. */
  52583. In: function ( k ) {
  52584. return k * k;
  52585. },
  52586. /**
  52587. * Ease-out.
  52588. *
  52589. * @method Phaser.Easing.Quadratic#Out
  52590. * @param {number} k - The value to be tweened.
  52591. * @returns {number} k* (2-k).
  52592. */
  52593. Out: function ( k ) {
  52594. return k * ( 2 - k );
  52595. },
  52596. /**
  52597. * Ease-in/out.
  52598. *
  52599. * @method Phaser.Easing.Quadratic#InOut
  52600. * @param {number} k - The value to be tweened.
  52601. * @returns {number} The tweened value.
  52602. */
  52603. InOut: function ( k ) {
  52604. if ( ( k *= 2 ) < 1 ) return 0.5 * k * k;
  52605. return - 0.5 * ( --k * ( k - 2 ) - 1 );
  52606. }
  52607. },
  52608. /**
  52609. * Cubic easing.
  52610. *
  52611. * @class Phaser.Easing.Cubic
  52612. */
  52613. Cubic: {
  52614. /**
  52615. * Cubic ease-in.
  52616. *
  52617. * @method Phaser.Easing.Cubic#In
  52618. * @param {number} k - The value to be tweened.
  52619. * @returns {number} The tweened value.
  52620. */
  52621. In: function ( k ) {
  52622. return k * k * k;
  52623. },
  52624. /**
  52625. * Cubic ease-out.
  52626. *
  52627. * @method Phaser.Easing.Cubic#Out
  52628. * @param {number} k - The value to be tweened.
  52629. * @returns {number} The tweened value.
  52630. */
  52631. Out: function ( k ) {
  52632. return --k * k * k + 1;
  52633. },
  52634. /**
  52635. * Cubic ease-in/out.
  52636. *
  52637. * @method Phaser.Easing.Cubic#InOut
  52638. * @param {number} k - The value to be tweened.
  52639. * @returns {number} The tweened value.
  52640. */
  52641. InOut: function ( k ) {
  52642. if ( ( k *= 2 ) < 1 ) return 0.5 * k * k * k;
  52643. return 0.5 * ( ( k -= 2 ) * k * k + 2 );
  52644. }
  52645. },
  52646. /**
  52647. * Quartic easing.
  52648. *
  52649. * @class Phaser.Easing.Quartic
  52650. */
  52651. Quartic: {
  52652. /**
  52653. * Quartic ease-in.
  52654. *
  52655. * @method Phaser.Easing.Quartic#In
  52656. * @param {number} k - The value to be tweened.
  52657. * @returns {number} The tweened value.
  52658. */
  52659. In: function ( k ) {
  52660. return k * k * k * k;
  52661. },
  52662. /**
  52663. * Quartic ease-out.
  52664. *
  52665. * @method Phaser.Easing.Quartic#Out
  52666. * @param {number} k - The value to be tweened.
  52667. * @returns {number} The tweened value.
  52668. */
  52669. Out: function ( k ) {
  52670. return 1 - ( --k * k * k * k );
  52671. },
  52672. /**
  52673. * Quartic ease-in/out.
  52674. *
  52675. * @method Phaser.Easing.Quartic#InOut
  52676. * @param {number} k - The value to be tweened.
  52677. * @returns {number} The tweened value.
  52678. */
  52679. InOut: function ( k ) {
  52680. if ( ( k *= 2 ) < 1) return 0.5 * k * k * k * k;
  52681. return - 0.5 * ( ( k -= 2 ) * k * k * k - 2 );
  52682. }
  52683. },
  52684. /**
  52685. * Quintic easing.
  52686. *
  52687. * @class Phaser.Easing.Quintic
  52688. */
  52689. Quintic: {
  52690. /**
  52691. * Quintic ease-in.
  52692. *
  52693. * @method Phaser.Easing.Quintic#In
  52694. * @param {number} k - The value to be tweened.
  52695. * @returns {number} The tweened value.
  52696. */
  52697. In: function ( k ) {
  52698. return k * k * k * k * k;
  52699. },
  52700. /**
  52701. * Quintic ease-out.
  52702. *
  52703. * @method Phaser.Easing.Quintic#Out
  52704. * @param {number} k - The value to be tweened.
  52705. * @returns {number} The tweened value.
  52706. */
  52707. Out: function ( k ) {
  52708. return --k * k * k * k * k + 1;
  52709. },
  52710. /**
  52711. * Quintic ease-in/out.
  52712. *
  52713. * @method Phaser.Easing.Quintic#InOut
  52714. * @param {number} k - The value to be tweened.
  52715. * @returns {number} The tweened value.
  52716. */
  52717. InOut: function ( k ) {
  52718. if ( ( k *= 2 ) < 1 ) return 0.5 * k * k * k * k * k;
  52719. return 0.5 * ( ( k -= 2 ) * k * k * k * k + 2 );
  52720. }
  52721. },
  52722. /**
  52723. * Sinusoidal easing.
  52724. *
  52725. * @class Phaser.Easing.Sinusoidal
  52726. */
  52727. Sinusoidal: {
  52728. /**
  52729. * Sinusoidal ease-in.
  52730. *
  52731. * @method Phaser.Easing.Sinusoidal#In
  52732. * @param {number} k - The value to be tweened.
  52733. * @returns {number} The tweened value.
  52734. */
  52735. In: function ( k ) {
  52736. if (k === 0) return 0;
  52737. if (k === 1) return 1;
  52738. return 1 - Math.cos( k * Math.PI / 2 );
  52739. },
  52740. /**
  52741. * Sinusoidal ease-out.
  52742. *
  52743. * @method Phaser.Easing.Sinusoidal#Out
  52744. * @param {number} k - The value to be tweened.
  52745. * @returns {number} The tweened value.
  52746. */
  52747. Out: function ( k ) {
  52748. if (k === 0) return 0;
  52749. if (k === 1) return 1;
  52750. return Math.sin( k * Math.PI / 2 );
  52751. },
  52752. /**
  52753. * Sinusoidal ease-in/out.
  52754. *
  52755. * @method Phaser.Easing.Sinusoidal#InOut
  52756. * @param {number} k - The value to be tweened.
  52757. * @returns {number} The tweened value.
  52758. */
  52759. InOut: function ( k ) {
  52760. if (k === 0) return 0;
  52761. if (k === 1) return 1;
  52762. return 0.5 * ( 1 - Math.cos( Math.PI * k ) );
  52763. }
  52764. },
  52765. /**
  52766. * Exponential easing.
  52767. *
  52768. * @class Phaser.Easing.Exponential
  52769. */
  52770. Exponential: {
  52771. /**
  52772. * Exponential ease-in.
  52773. *
  52774. * @method Phaser.Easing.Exponential#In
  52775. * @param {number} k - The value to be tweened.
  52776. * @returns {number} The tweened value.
  52777. */
  52778. In: function ( k ) {
  52779. return k === 0 ? 0 : Math.pow( 1024, k - 1 );
  52780. },
  52781. /**
  52782. * Exponential ease-out.
  52783. *
  52784. * @method Phaser.Easing.Exponential#Out
  52785. * @param {number} k - The value to be tweened.
  52786. * @returns {number} The tweened value.
  52787. */
  52788. Out: function ( k ) {
  52789. return k === 1 ? 1 : 1 - Math.pow( 2, - 10 * k );
  52790. },
  52791. /**
  52792. * Exponential ease-in/out.
  52793. *
  52794. * @method Phaser.Easing.Exponential#InOut
  52795. * @param {number} k - The value to be tweened.
  52796. * @returns {number} The tweened value.
  52797. */
  52798. InOut: function ( k ) {
  52799. if ( k === 0 ) return 0;
  52800. if ( k === 1 ) return 1;
  52801. if ( ( k *= 2 ) < 1 ) return 0.5 * Math.pow( 1024, k - 1 );
  52802. return 0.5 * ( - Math.pow( 2, - 10 * ( k - 1 ) ) + 2 );
  52803. }
  52804. },
  52805. /**
  52806. * Circular easing.
  52807. *
  52808. * @class Phaser.Easing.Circular
  52809. */
  52810. Circular: {
  52811. /**
  52812. * Circular ease-in.
  52813. *
  52814. * @method Phaser.Easing.Circular#In
  52815. * @param {number} k - The value to be tweened.
  52816. * @returns {number} The tweened value.
  52817. */
  52818. In: function ( k ) {
  52819. return 1 - Math.sqrt( 1 - k * k );
  52820. },
  52821. /**
  52822. * Circular ease-out.
  52823. *
  52824. * @method Phaser.Easing.Circular#Out
  52825. * @param {number} k - The value to be tweened.
  52826. * @returns {number} The tweened value.
  52827. */
  52828. Out: function ( k ) {
  52829. return Math.sqrt( 1 - ( --k * k ) );
  52830. },
  52831. /**
  52832. * Circular ease-in/out.
  52833. *
  52834. * @method Phaser.Easing.Circular#InOut
  52835. * @param {number} k - The value to be tweened.
  52836. * @returns {number} The tweened value.
  52837. */
  52838. InOut: function ( k ) {
  52839. if ( ( k *= 2 ) < 1) return - 0.5 * ( Math.sqrt( 1 - k * k) - 1);
  52840. return 0.5 * ( Math.sqrt( 1 - ( k -= 2) * k) + 1);
  52841. }
  52842. },
  52843. /**
  52844. * Elastic easing.
  52845. *
  52846. * @class Phaser.Easing.Elastic
  52847. */
  52848. Elastic: {
  52849. /**
  52850. * Elastic ease-in.
  52851. *
  52852. * @method Phaser.Easing.Elastic#In
  52853. * @param {number} k - The value to be tweened.
  52854. * @returns {number} The tweened value.
  52855. */
  52856. In: function ( k ) {
  52857. var s, a = 0.1, p = 0.4;
  52858. if ( k === 0 ) return 0;
  52859. if ( k === 1 ) return 1;
  52860. if ( !a || a < 1 ) { a = 1; s = p / 4; }
  52861. else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI );
  52862. return - ( a * Math.pow( 2, 10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) );
  52863. },
  52864. /**
  52865. * Elastic ease-out.
  52866. *
  52867. * @method Phaser.Easing.Elastic#Out
  52868. * @param {number} k - The value to be tweened.
  52869. * @returns {number} The tweened value.
  52870. */
  52871. Out: function ( k ) {
  52872. var s, a = 0.1, p = 0.4;
  52873. if ( k === 0 ) return 0;
  52874. if ( k === 1 ) return 1;
  52875. if ( !a || a < 1 ) { a = 1; s = p / 4; }
  52876. else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI );
  52877. return ( a * Math.pow( 2, - 10 * k) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) + 1 );
  52878. },
  52879. /**
  52880. * Elastic ease-in/out.
  52881. *
  52882. * @method Phaser.Easing.Elastic#InOut
  52883. * @param {number} k - The value to be tweened.
  52884. * @returns {number} The tweened value.
  52885. */
  52886. InOut: function ( k ) {
  52887. var s, a = 0.1, p = 0.4;
  52888. if ( k === 0 ) return 0;
  52889. if ( k === 1 ) return 1;
  52890. if ( !a || a < 1 ) { a = 1; s = p / 4; }
  52891. else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI );
  52892. if ( ( k *= 2 ) < 1 ) return - 0.5 * ( a * Math.pow( 2, 10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) );
  52893. return a * Math.pow( 2, -10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) * 0.5 + 1;
  52894. }
  52895. },
  52896. /**
  52897. * Back easing.
  52898. *
  52899. * @class Phaser.Easing.Back
  52900. */
  52901. Back: {
  52902. /**
  52903. * Back ease-in.
  52904. *
  52905. * @method Phaser.Easing.Back#In
  52906. * @param {number} k - The value to be tweened.
  52907. * @returns {number} The tweened value.
  52908. */
  52909. In: function ( k ) {
  52910. var s = 1.70158;
  52911. return k * k * ( ( s + 1 ) * k - s );
  52912. },
  52913. /**
  52914. * Back ease-out.
  52915. *
  52916. * @method Phaser.Easing.Back#Out
  52917. * @param {number} k - The value to be tweened.
  52918. * @returns {number} The tweened value.
  52919. */
  52920. Out: function ( k ) {
  52921. var s = 1.70158;
  52922. return --k * k * ( ( s + 1 ) * k + s ) + 1;
  52923. },
  52924. /**
  52925. * Back ease-in/out.
  52926. *
  52927. * @method Phaser.Easing.Back#InOut
  52928. * @param {number} k - The value to be tweened.
  52929. * @returns {number} The tweened value.
  52930. */
  52931. InOut: function ( k ) {
  52932. var s = 1.70158 * 1.525;
  52933. if ( ( k *= 2 ) < 1 ) return 0.5 * ( k * k * ( ( s + 1 ) * k - s ) );
  52934. return 0.5 * ( ( k -= 2 ) * k * ( ( s + 1 ) * k + s ) + 2 );
  52935. }
  52936. },
  52937. /**
  52938. * Bounce easing.
  52939. *
  52940. * @class Phaser.Easing.Bounce
  52941. */
  52942. Bounce: {
  52943. /**
  52944. * Bounce ease-in.
  52945. *
  52946. * @method Phaser.Easing.Bounce#In
  52947. * @param {number} k - The value to be tweened.
  52948. * @returns {number} The tweened value.
  52949. */
  52950. In: function ( k ) {
  52951. return 1 - Phaser.Easing.Bounce.Out( 1 - k );
  52952. },
  52953. /**
  52954. * Bounce ease-out.
  52955. *
  52956. * @method Phaser.Easing.Bounce#Out
  52957. * @param {number} k - The value to be tweened.
  52958. * @returns {number} The tweened value.
  52959. */
  52960. Out: function ( k ) {
  52961. if ( k < ( 1 / 2.75 ) ) {
  52962. return 7.5625 * k * k;
  52963. } else if ( k < ( 2 / 2.75 ) ) {
  52964. return 7.5625 * ( k -= ( 1.5 / 2.75 ) ) * k + 0.75;
  52965. } else if ( k < ( 2.5 / 2.75 ) ) {
  52966. return 7.5625 * ( k -= ( 2.25 / 2.75 ) ) * k + 0.9375;
  52967. } else {
  52968. return 7.5625 * ( k -= ( 2.625 / 2.75 ) ) * k + 0.984375;
  52969. }
  52970. },
  52971. /**
  52972. * Bounce ease-in/out.
  52973. *
  52974. * @method Phaser.Easing.Bounce#InOut
  52975. * @param {number} k - The value to be tweened.
  52976. * @returns {number} The tweened value.
  52977. */
  52978. InOut: function ( k ) {
  52979. if ( k < 0.5 ) return Phaser.Easing.Bounce.In( k * 2 ) * 0.5;
  52980. return Phaser.Easing.Bounce.Out( k * 2 - 1 ) * 0.5 + 0.5;
  52981. }
  52982. }
  52983. };
  52984. Phaser.Easing.Default = Phaser.Easing.Linear.None;
  52985. Phaser.Easing.Power0 = Phaser.Easing.Linear.None;
  52986. Phaser.Easing.Power1 = Phaser.Easing.Quadratic.Out;
  52987. Phaser.Easing.Power2 = Phaser.Easing.Cubic.Out;
  52988. Phaser.Easing.Power3 = Phaser.Easing.Quartic.Out;
  52989. Phaser.Easing.Power4 = Phaser.Easing.Quintic.Out;
  52990. /**
  52991. * @author Richard Davey <rich@photonstorm.com>
  52992. * @copyright 2016 Photon Storm Ltd.
  52993. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  52994. */
  52995. /**
  52996. * This is the core internal game clock.
  52997. *
  52998. * It manages the elapsed time and calculation of elapsed values, used for game object motion and tweens,
  52999. * and also handles the standard Timer pool.
  53000. *
  53001. * To create a general timed event, use the master {@link Phaser.Timer} accessible through {@link Phaser.Time.events events}.
  53002. *
  53003. * There are different *types* of time in Phaser:
  53004. *
  53005. * - ***Game time*** always runs at the speed of time in real life.
  53006. *
  53007. * Unlike wall-clock time, *game time stops when Phaser is paused*.
  53008. *
  53009. * Game time is used for {@link Phaser.Timer timer events}.
  53010. *
  53011. * - ***Physics time*** represents the amount of time given to physics calculations.
  53012. *
  53013. * *When {@link #slowMotion} is in effect physics time runs slower than game time.*
  53014. * Like game time, physics time stops when Phaser is paused.
  53015. *
  53016. * Physics time is used for physics calculations and {@link Phaser.Tween tweens}.
  53017. *
  53018. * - {@link https://en.wikipedia.org/wiki/Wall-clock_time ***Wall-clock time***} represents the duration between two events in real life time.
  53019. *
  53020. * This time is independent of Phaser and always progresses, regardless of if Phaser is paused.
  53021. *
  53022. * @class Phaser.Time
  53023. * @constructor
  53024. * @param {Phaser.Game} game A reference to the currently running game.
  53025. */
  53026. Phaser.Time = function (game) {
  53027. /**
  53028. * @property {Phaser.Game} game - Local reference to game.
  53029. * @protected
  53030. */
  53031. this.game = game;
  53032. /**
  53033. * The `Date.now()` value when the time was last updated.
  53034. * @property {integer} time
  53035. * @protected
  53036. */
  53037. this.time = 0;
  53038. /**
  53039. * The `now` when the previous update occurred.
  53040. * @property {number} prevTime
  53041. * @protected
  53042. */
  53043. this.prevTime = 0;
  53044. /**
  53045. * An increasing value representing cumulative milliseconds since an undisclosed epoch.
  53046. *
  53047. * While this value is in milliseconds and can be used to compute time deltas,
  53048. * it must must _not_ be used with `Date.now()` as it may not use the same epoch / starting reference.
  53049. *
  53050. * The source may either be from a high-res source (eg. if RAF is available) or the standard Date.now;
  53051. * the value can only be relied upon within a particular game instance.
  53052. *
  53053. * @property {number} now
  53054. * @protected
  53055. */
  53056. this.now = 0;
  53057. /**
  53058. * Elapsed time since the last time update, in milliseconds, based on `now`.
  53059. *
  53060. * This value _may_ include time that the game is paused/inactive.
  53061. *
  53062. * _Note:_ This is updated only once per game loop - even if multiple logic update steps are done.
  53063. * Use {@link Phaser.Timer#physicsTime physicsTime} as a basis of game/logic calculations instead.
  53064. *
  53065. * @property {number} elapsed
  53066. * @see Phaser.Time.time
  53067. * @protected
  53068. */
  53069. this.elapsed = 0;
  53070. /**
  53071. * The time in ms since the last time update, in milliseconds, based on `time`.
  53072. *
  53073. * This value is corrected for game pauses and will be "about zero" after a game is resumed.
  53074. *
  53075. * _Note:_ This is updated once per game loop - even if multiple logic update steps are done.
  53076. * Use {@link Phaser.Timer#physicsTime physicsTime} as a basis of game/logic calculations instead.
  53077. *
  53078. * @property {integer} elapsedMS
  53079. * @protected
  53080. */
  53081. this.elapsedMS = 0;
  53082. /**
  53083. * The physics update delta, in fractional seconds.
  53084. *
  53085. * This should be used as an applicable multiplier by all logic update steps (eg. `preUpdate/postUpdate/update`)
  53086. * to ensure consistent game timing. Game/logic timing can drift from real-world time if the system
  53087. * is unable to consistently maintain the desired FPS.
  53088. *
  53089. * With fixed-step updates this is normally equivalent to `1.0 / desiredFps`.
  53090. *
  53091. * @property {number} physicsElapsed
  53092. */
  53093. this.physicsElapsed = 1 / 60;
  53094. /**
  53095. * The physics update delta, in milliseconds - equivalent to `physicsElapsed * 1000`.
  53096. *
  53097. * @property {number} physicsElapsedMS
  53098. */
  53099. this.physicsElapsedMS = (1 / 60) * 1000;
  53100. /**
  53101. * The desiredFps multiplier as used by Game.update.
  53102. * @property {integer} desiredFpsMult
  53103. * @protected
  53104. */
  53105. this.desiredFpsMult = 1.0 / 60;
  53106. /**
  53107. * The desired frame rate of the game.
  53108. *
  53109. * This is used is used to calculate the physic/logic multiplier and how to apply catch-up logic updates.
  53110. *
  53111. * @property {number} _desiredFps
  53112. * @private
  53113. * @default
  53114. */
  53115. this._desiredFps = 60;
  53116. /**
  53117. * The suggested frame rate for your game, based on an averaged real frame rate.
  53118. * This value is only populated if `Time.advancedTiming` is enabled.
  53119. *
  53120. * _Note:_ This is not available until after a few frames have passed; until then
  53121. * it's set to the same value as desiredFps.
  53122. *
  53123. * @property {number} suggestedFps
  53124. * @default
  53125. */
  53126. this.suggestedFps = this.desiredFps;
  53127. /**
  53128. * Scaling factor to make the game move smoothly in slow motion
  53129. * - 1.0 = normal speed
  53130. * - 2.0 = half speed
  53131. * @property {number} slowMotion
  53132. * @default
  53133. */
  53134. this.slowMotion = 1.0;
  53135. /**
  53136. * If true then advanced profiling, including the fps rate, fps min/max, suggestedFps and msMin/msMax are updated.
  53137. * @property {boolean} advancedTiming
  53138. * @default
  53139. */
  53140. this.advancedTiming = false;
  53141. /**
  53142. * Advanced timing result: The number of render frames record in the last second.
  53143. *
  53144. * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled.
  53145. * @property {integer} frames
  53146. * @readonly
  53147. */
  53148. this.frames = 0;
  53149. /**
  53150. * Advanced timing result: Frames per second.
  53151. *
  53152. * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled.
  53153. * @property {number} fps
  53154. * @readonly
  53155. */
  53156. this.fps = 0;
  53157. /**
  53158. * Advanced timing result: The lowest rate the fps has dropped to.
  53159. *
  53160. * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled.
  53161. * This value can be manually reset.
  53162. * @property {number} fpsMin
  53163. */
  53164. this.fpsMin = 1000;
  53165. /**
  53166. * Advanced timing result: The highest rate the fps has reached (usually no higher than 60fps).
  53167. *
  53168. * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled.
  53169. * This value can be manually reset.
  53170. * @property {number} fpsMax
  53171. */
  53172. this.fpsMax = 0;
  53173. /**
  53174. * Advanced timing result: The minimum amount of time the game has taken between consecutive frames.
  53175. *
  53176. * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled.
  53177. * This value can be manually reset.
  53178. * @property {number} msMin
  53179. * @default
  53180. */
  53181. this.msMin = 1000;
  53182. /**
  53183. * Advanced timing result: The maximum amount of time the game has taken between consecutive frames.
  53184. *
  53185. * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled.
  53186. * This value can be manually reset.
  53187. * @property {number} msMax
  53188. */
  53189. this.msMax = 0;
  53190. /**
  53191. * Records how long the game was last paused, in milliseconds.
  53192. * (This is not updated until the game is resumed.)
  53193. * @property {number} pauseDuration
  53194. */
  53195. this.pauseDuration = 0;
  53196. /**
  53197. * @property {number} timeToCall - The value that setTimeout needs to work out when to next update
  53198. * @protected
  53199. */
  53200. this.timeToCall = 0;
  53201. /**
  53202. * @property {number} timeExpected - The time when the next call is expected when using setTimer to control the update loop
  53203. * @protected
  53204. */
  53205. this.timeExpected = 0;
  53206. /**
  53207. * A {@link Phaser.Timer} object bound to the master clock (this Time object) which events can be added to.
  53208. * @property {Phaser.Timer} events
  53209. */
  53210. this.events = new Phaser.Timer(this.game, false);
  53211. /**
  53212. * @property {number} _frameCount - count the number of calls to time.update since the last suggestedFps was calculated
  53213. * @private
  53214. */
  53215. this._frameCount = 0;
  53216. /**
  53217. * @property {number} _elapsedAcumulator - sum of the elapsed time since the last suggestedFps was calculated
  53218. * @private
  53219. */
  53220. this._elapsedAccumulator = 0;
  53221. /**
  53222. * @property {number} _started - The time at which the Game instance started.
  53223. * @private
  53224. */
  53225. this._started = 0;
  53226. /**
  53227. * @property {number} _timeLastSecond - The time (in ms) that the last second counter ticked over.
  53228. * @private
  53229. */
  53230. this._timeLastSecond = 0;
  53231. /**
  53232. * @property {number} _pauseStarted - The time the game started being paused.
  53233. * @private
  53234. */
  53235. this._pauseStarted = 0;
  53236. /**
  53237. * @property {boolean} _justResumed - Internal value used to recover from the game pause state.
  53238. * @private
  53239. */
  53240. this._justResumed = false;
  53241. /**
  53242. * @property {Phaser.Timer[]} _timers - Internal store of Phaser.Timer objects.
  53243. * @private
  53244. */
  53245. this._timers = [];
  53246. };
  53247. Phaser.Time.prototype = {
  53248. /**
  53249. * Called automatically by Phaser.Game after boot. Should not be called directly.
  53250. *
  53251. * @method Phaser.Time#boot
  53252. * @protected
  53253. */
  53254. boot: function () {
  53255. this._started = Date.now();
  53256. this.time = Date.now();
  53257. this.events.start();
  53258. this.timeExpected = this.time;
  53259. },
  53260. /**
  53261. * Adds an existing Phaser.Timer object to the Timer pool.
  53262. *
  53263. * @method Phaser.Time#add
  53264. * @param {Phaser.Timer} timer - An existing Phaser.Timer object.
  53265. * @return {Phaser.Timer} The given Phaser.Timer object.
  53266. */
  53267. add: function (timer) {
  53268. this._timers.push(timer);
  53269. return timer;
  53270. },
  53271. /**
  53272. * Creates a new stand-alone Phaser.Timer object.
  53273. *
  53274. * @method Phaser.Time#create
  53275. * @param {boolean} [autoDestroy=true] - A Timer that is set to automatically destroy itself will do so after all of its events have been dispatched (assuming no looping events).
  53276. * @return {Phaser.Timer} The Timer object that was created.
  53277. */
  53278. create: function (autoDestroy) {
  53279. if (autoDestroy === undefined) { autoDestroy = true; }
  53280. var timer = new Phaser.Timer(this.game, autoDestroy);
  53281. this._timers.push(timer);
  53282. return timer;
  53283. },
  53284. /**
  53285. * Remove all Timer objects, regardless of their state and clears all Timers from the {@link Phaser.Time#events events} timer.
  53286. *
  53287. * @method Phaser.Time#removeAll
  53288. */
  53289. removeAll: function () {
  53290. for (var i = 0; i < this._timers.length; i++)
  53291. {
  53292. this._timers[i].destroy();
  53293. }
  53294. this._timers = [];
  53295. this.events.removeAll();
  53296. },
  53297. /**
  53298. * Refreshes the Time.time and Time.elapsedMS properties from the system clock.
  53299. *
  53300. * @method Phaser.Time#refresh
  53301. */
  53302. refresh: function () {
  53303. // Set to the old Date.now value
  53304. var previousDateNow = this.time;
  53305. // this.time always holds a Date.now value
  53306. this.time = Date.now();
  53307. // Adjust accordingly.
  53308. this.elapsedMS = this.time - previousDateNow;
  53309. },
  53310. /**
  53311. * Updates the game clock and if enabled the advanced timing data. This is called automatically by Phaser.Game.
  53312. *
  53313. * @method Phaser.Time#update
  53314. * @protected
  53315. * @param {number} time - The current relative timestamp; see {@link Phaser.Time#now now}.
  53316. */
  53317. update: function (time) {
  53318. // Set to the old Date.now value
  53319. var previousDateNow = this.time;
  53320. // this.time always holds a Date.now value
  53321. this.time = Date.now();
  53322. // Adjust accordingly.
  53323. this.elapsedMS = this.time - previousDateNow;
  53324. // 'now' is currently still holding the time of the last call, move it into prevTime
  53325. this.prevTime = this.now;
  53326. // update 'now' to hold the current time
  53327. // this.now may hold the RAF high resolution time value if RAF is available (otherwise it also holds Date.now)
  53328. this.now = time;
  53329. // elapsed time between previous call and now - this could be a high resolution value
  53330. this.elapsed = this.now - this.prevTime;
  53331. if (this.game.raf._isSetTimeOut)
  53332. {
  53333. // console.log('Time isSet', this._desiredFps, 'te', this.timeExpected, 'time', time);
  53334. // time to call this function again in ms in case we're using timers instead of RequestAnimationFrame to update the game
  53335. this.timeToCall = Math.floor(Math.max(0, (1000.0 / this._desiredFps) - (this.timeExpected - time)));
  53336. // time when the next call is expected if using timers
  53337. this.timeExpected = time + this.timeToCall;
  53338. // console.log('Time expect', this.timeExpected);
  53339. }
  53340. if (this.advancedTiming)
  53341. {
  53342. this.updateAdvancedTiming();
  53343. }
  53344. // Paused but still running?
  53345. if (!this.game.paused)
  53346. {
  53347. // Our internal Phaser.Timer
  53348. this.events.update(this.time);
  53349. if (this._timers.length)
  53350. {
  53351. this.updateTimers();
  53352. }
  53353. }
  53354. },
  53355. /**
  53356. * Handles the updating of the Phaser.Timers (if any)
  53357. * Called automatically by Time.update.
  53358. *
  53359. * @method Phaser.Time#updateTimers
  53360. * @private
  53361. */
  53362. updateTimers: function () {
  53363. // Any game level timers
  53364. var i = 0;
  53365. var len = this._timers.length;
  53366. while (i < len)
  53367. {
  53368. if (this._timers[i].update(this.time))
  53369. {
  53370. i++;
  53371. }
  53372. else
  53373. {
  53374. // Timer requests to be removed
  53375. this._timers.splice(i, 1);
  53376. len--;
  53377. }
  53378. }
  53379. },
  53380. /**
  53381. * Handles the updating of the advanced timing values (if enabled)
  53382. * Called automatically by Time.update.
  53383. *
  53384. * @method Phaser.Time#updateAdvancedTiming
  53385. * @private
  53386. */
  53387. updateAdvancedTiming: function () {
  53388. // count the number of time.update calls
  53389. this._frameCount++;
  53390. this._elapsedAccumulator += this.elapsed;
  53391. // occasionally recalculate the suggestedFps based on the accumulated elapsed time
  53392. if (this._frameCount >= this._desiredFps * 2)
  53393. {
  53394. // this formula calculates suggestedFps in multiples of 5 fps
  53395. this.suggestedFps = Math.floor(200 / (this._elapsedAccumulator / this._frameCount)) * 5;
  53396. this._frameCount = 0;
  53397. this._elapsedAccumulator = 0;
  53398. }
  53399. this.msMin = Math.min(this.msMin, this.elapsed);
  53400. this.msMax = Math.max(this.msMax, this.elapsed);
  53401. this.frames++;
  53402. if (this.now > this._timeLastSecond + 1000)
  53403. {
  53404. this.fps = Math.round((this.frames * 1000) / (this.now - this._timeLastSecond));
  53405. this.fpsMin = Math.min(this.fpsMin, this.fps);
  53406. this.fpsMax = Math.max(this.fpsMax, this.fps);
  53407. this._timeLastSecond = this.now;
  53408. this.frames = 0;
  53409. }
  53410. },
  53411. /**
  53412. * Called when the game enters a paused state.
  53413. *
  53414. * @method Phaser.Time#gamePaused
  53415. * @private
  53416. */
  53417. gamePaused: function () {
  53418. this._pauseStarted = Date.now();
  53419. this.events.pause();
  53420. var i = this._timers.length;
  53421. while (i--)
  53422. {
  53423. this._timers[i]._pause();
  53424. }
  53425. },
  53426. /**
  53427. * Called when the game resumes from a paused state.
  53428. *
  53429. * @method Phaser.Time#gameResumed
  53430. * @private
  53431. */
  53432. gameResumed: function () {
  53433. // Set the parameter which stores Date.now() to make sure it's correct on resume
  53434. this.time = Date.now();
  53435. this.pauseDuration = this.time - this._pauseStarted;
  53436. this.events.resume();
  53437. var i = this._timers.length;
  53438. while (i--)
  53439. {
  53440. this._timers[i]._resume();
  53441. }
  53442. },
  53443. /**
  53444. * The number of seconds that have elapsed since the game was started.
  53445. *
  53446. * @method Phaser.Time#totalElapsedSeconds
  53447. * @return {number} The number of seconds that have elapsed since the game was started.
  53448. */
  53449. totalElapsedSeconds: function() {
  53450. return (this.time - this._started) * 0.001;
  53451. },
  53452. /**
  53453. * How long has passed since the given time.
  53454. *
  53455. * @method Phaser.Time#elapsedSince
  53456. * @param {number} since - The time you want to measure against.
  53457. * @return {number} The difference between the given time and now.
  53458. */
  53459. elapsedSince: function (since) {
  53460. return this.time - since;
  53461. },
  53462. /**
  53463. * How long has passed since the given time (in seconds).
  53464. *
  53465. * @method Phaser.Time#elapsedSecondsSince
  53466. * @param {number} since - The time you want to measure (in seconds).
  53467. * @return {number} Duration between given time and now (in seconds).
  53468. */
  53469. elapsedSecondsSince: function (since) {
  53470. return (this.time - since) * 0.001;
  53471. },
  53472. /**
  53473. * Resets the private _started value to now and removes all currently running Timers.
  53474. *
  53475. * @method Phaser.Time#reset
  53476. */
  53477. reset: function () {
  53478. this._started = this.time;
  53479. this.removeAll();
  53480. }
  53481. };
  53482. /**
  53483. * The desired frame rate of the game.
  53484. *
  53485. * This is used is used to calculate the physic / logic multiplier and how to apply catch-up logic updates.
  53486. *
  53487. * @name Phaser.Time#desiredFps
  53488. * @property {integer} desiredFps - The desired frame rate of the game. Defaults to 60.
  53489. */
  53490. Object.defineProperty(Phaser.Time.prototype, "desiredFps", {
  53491. get: function () {
  53492. return this._desiredFps;
  53493. },
  53494. set: function (value) {
  53495. this._desiredFps = value;
  53496. // Set the physics elapsed time... this will always be 1 / this.desiredFps
  53497. // because we're using fixed time steps in game.update
  53498. this.physicsElapsed = 1 / value;
  53499. this.physicsElapsedMS = this.physicsElapsed * 1000;
  53500. this.desiredFpsMult = 1.0 / value;
  53501. }
  53502. });
  53503. Phaser.Time.prototype.constructor = Phaser.Time;
  53504. /**
  53505. * @author Richard Davey <rich@photonstorm.com>
  53506. * @copyright 2016 Photon Storm Ltd.
  53507. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  53508. */
  53509. /**
  53510. * A Timer is a way to create and manage {@link Phaser.TimerEvent timer events} that wait for a specific duration and then run a callback.
  53511. * Many different timer events, with individual delays, can be added to the same Timer.
  53512. *
  53513. * All Timer delays are in milliseconds (there are 1000 ms in 1 second); so a delay value of 250 represents a quarter of a second.
  53514. *
  53515. * Timers are based on real life time, adjusted for game pause durations.
  53516. * That is, *timer events are based on elapsed {@link Phaser.Time game time}* and do *not* take physics time or slow motion into account.
  53517. *
  53518. * @class Phaser.Timer
  53519. * @constructor
  53520. * @param {Phaser.Game} game - A reference to the currently running game.
  53521. * @param {boolean} [autoDestroy=true] - If true, the timer will automatically destroy itself after all the events have been dispatched (assuming no looping events).
  53522. */
  53523. Phaser.Timer = function (game, autoDestroy) {
  53524. if (autoDestroy === undefined) { autoDestroy = true; }
  53525. /**
  53526. * @property {Phaser.Game} game - Local reference to game.
  53527. * @protected
  53528. */
  53529. this.game = game;
  53530. /**
  53531. * True if the Timer is actively running.
  53532. *
  53533. * Do not modify this boolean - use {@link Phaser.Timer#pause pause} (and {@link Phaser.Timer#resume resume}) to pause the timer.
  53534. * @property {boolean} running
  53535. * @default
  53536. * @readonly
  53537. */
  53538. this.running = false;
  53539. /**
  53540. * If true, the timer will automatically destroy itself after all the events have been dispatched (assuming no looping events).
  53541. * @property {boolean} autoDestroy
  53542. */
  53543. this.autoDestroy = autoDestroy;
  53544. /**
  53545. * @property {boolean} expired - An expired Timer is one in which all of its events have been dispatched and none are pending.
  53546. * @readonly
  53547. * @default
  53548. */
  53549. this.expired = false;
  53550. /**
  53551. * @property {number} elapsed - Elapsed time since the last frame (in ms).
  53552. * @protected
  53553. */
  53554. this.elapsed = 0;
  53555. /**
  53556. * @property {Phaser.TimerEvent[]} events - An array holding all of this timers Phaser.TimerEvent objects. Use the methods add, repeat and loop to populate it.
  53557. */
  53558. this.events = [];
  53559. /**
  53560. * This signal will be dispatched when this Timer has completed which means that there are no more events in the queue.
  53561. *
  53562. * The signal is supplied with one argument, `timer`, which is this Timer object.
  53563. *
  53564. * @property {Phaser.Signal} onComplete
  53565. */
  53566. this.onComplete = new Phaser.Signal();
  53567. /**
  53568. * @property {number} nextTick - The time the next tick will occur.
  53569. * @readonly
  53570. * @protected
  53571. */
  53572. this.nextTick = 0;
  53573. /**
  53574. * @property {number} timeCap - If the difference in time between two frame updates exceeds this value, the event times are reset to avoid catch-up situations.
  53575. */
  53576. this.timeCap = 1000;
  53577. /**
  53578. * @property {boolean} paused - The paused state of the Timer. You can pause the timer by calling Timer.pause() and Timer.resume() or by the game pausing.
  53579. * @readonly
  53580. * @default
  53581. */
  53582. this.paused = false;
  53583. /**
  53584. * @property {boolean} _codePaused - Was the Timer paused by code or by Game focus loss?
  53585. * @private
  53586. */
  53587. this._codePaused = false;
  53588. /**
  53589. * @property {number} _started - The time at which this Timer instance started running.
  53590. * @private
  53591. * @default
  53592. */
  53593. this._started = 0;
  53594. /**
  53595. * @property {number} _pauseStarted - The time the game started being paused.
  53596. * @private
  53597. */
  53598. this._pauseStarted = 0;
  53599. /**
  53600. * @property {number} _pauseTotal - Total paused time.
  53601. * @private
  53602. */
  53603. this._pauseTotal = 0;
  53604. /**
  53605. * @property {number} _now - The current start-time adjusted time.
  53606. * @private
  53607. */
  53608. this._now = Date.now();
  53609. /**
  53610. * @property {number} _len - Temp. array length variable.
  53611. * @private
  53612. */
  53613. this._len = 0;
  53614. /**
  53615. * @property {number} _marked - Temp. counter variable.
  53616. * @private
  53617. */
  53618. this._marked = 0;
  53619. /**
  53620. * @property {number} _i - Temp. array counter variable.
  53621. * @private
  53622. */
  53623. this._i = 0;
  53624. /**
  53625. * @property {number} _diff - Internal cache var.
  53626. * @private
  53627. */
  53628. this._diff = 0;
  53629. /**
  53630. * @property {number} _newTick - Internal cache var.
  53631. * @private
  53632. */
  53633. this._newTick = 0;
  53634. };
  53635. /**
  53636. * Number of milliseconds in a minute.
  53637. * @constant
  53638. * @type {integer}
  53639. */
  53640. Phaser.Timer.MINUTE = 60000;
  53641. /**
  53642. * Number of milliseconds in a second.
  53643. * @constant
  53644. * @type {integer}
  53645. */
  53646. Phaser.Timer.SECOND = 1000;
  53647. /**
  53648. * Number of milliseconds in half a second.
  53649. * @constant
  53650. * @type {integer}
  53651. */
  53652. Phaser.Timer.HALF = 500;
  53653. /**
  53654. * Number of milliseconds in a quarter of a second.
  53655. * @constant
  53656. * @type {integer}
  53657. */
  53658. Phaser.Timer.QUARTER = 250;
  53659. Phaser.Timer.prototype = {
  53660. /**
  53661. * Creates a new TimerEvent on this Timer.
  53662. *
  53663. * Use {@link Phaser.Timer#add}, {@link Phaser.Timer#add}, or {@link Phaser.Timer#add} methods to create a new event.
  53664. *
  53665. * @method Phaser.Timer#create
  53666. * @private
  53667. * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs.
  53668. * @param {boolean} loop - Should the event loop or not?
  53669. * @param {number} repeatCount - The number of times the event will repeat.
  53670. * @param {function} callback - The callback that will be called when the timer event occurs.
  53671. * @param {object} callbackContext - The context in which the callback will be called.
  53672. * @param {any[]} arguments - The values to be sent to your callback function when it is called.
  53673. * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created.
  53674. */
  53675. create: function (delay, loop, repeatCount, callback, callbackContext, args) {
  53676. delay = Math.round(delay);
  53677. var tick = delay;
  53678. if (this._now === 0)
  53679. {
  53680. tick += this.game.time.time;
  53681. }
  53682. else
  53683. {
  53684. tick += this._now;
  53685. }
  53686. var event = new Phaser.TimerEvent(this, delay, tick, repeatCount, loop, callback, callbackContext, args);
  53687. this.events.push(event);
  53688. this.order();
  53689. this.expired = false;
  53690. return event;
  53691. },
  53692. /**
  53693. * Adds a new Event to this Timer.
  53694. *
  53695. * The event will fire after the given amount of `delay` in milliseconds has passed, once the Timer has started running.
  53696. * The delay is in relation to when the Timer starts, not the time it was added. If the Timer is already running the delay will be calculated based on the timers current time.
  53697. *
  53698. * Make sure to call {@link Phaser.Timer#start start} after adding all of the Events you require for this Timer.
  53699. *
  53700. * @method Phaser.Timer#add
  53701. * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs.
  53702. * @param {function} callback - The callback that will be called when the timer event occurs.
  53703. * @param {object} callbackContext - The context in which the callback will be called.
  53704. * @param {...*} arguments - Additional arguments that will be supplied to the callback.
  53705. * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created.
  53706. */
  53707. add: function (delay, callback, callbackContext) {
  53708. return this.create(delay, false, 0, callback, callbackContext, Array.prototype.slice.call(arguments, 3));
  53709. },
  53710. /**
  53711. * Adds a new TimerEvent that will always play through once and then repeat for the given number of iterations.
  53712. *
  53713. * The event will fire after the given amount of `delay` in milliseconds has passed, once the Timer has started running.
  53714. * The delay is in relation to when the Timer starts, not the time it was added.
  53715. * If the Timer is already running the delay will be calculated based on the timers current time.
  53716. *
  53717. * Make sure to call {@link Phaser.Timer#start start} after adding all of the Events you require for this Timer.
  53718. *
  53719. * @method Phaser.Timer#repeat
  53720. * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs.
  53721. * @param {number} repeatCount - The number of times the event will repeat once is has finished playback. A repeatCount of 1 means it will repeat itself once, playing the event twice in total.
  53722. * @param {function} callback - The callback that will be called when the timer event occurs.
  53723. * @param {object} callbackContext - The context in which the callback will be called.
  53724. * @param {...*} arguments - Additional arguments that will be supplied to the callback.
  53725. * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created.
  53726. */
  53727. repeat: function (delay, repeatCount, callback, callbackContext) {
  53728. return this.create(delay, false, repeatCount, callback, callbackContext, Array.prototype.slice.call(arguments, 4));
  53729. },
  53730. /**
  53731. * Adds a new looped Event to this Timer that will repeat forever or until the Timer is stopped.
  53732. *
  53733. * The event will fire after the given amount of `delay` in milliseconds has passed, once the Timer has started running.
  53734. * The delay is in relation to when the Timer starts, not the time it was added. If the Timer is already running the delay will be calculated based on the timers current time.
  53735. *
  53736. * Make sure to call {@link Phaser.Timer#start start} after adding all of the Events you require for this Timer.
  53737. *
  53738. * @method Phaser.Timer#loop
  53739. * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs.
  53740. * @param {function} callback - The callback that will be called when the timer event occurs.
  53741. * @param {object} callbackContext - The context in which the callback will be called.
  53742. * @param {...*} arguments - Additional arguments that will be supplied to the callback.
  53743. * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created.
  53744. */
  53745. loop: function (delay, callback, callbackContext) {
  53746. return this.create(delay, true, 0, callback, callbackContext, Array.prototype.slice.call(arguments, 3));
  53747. },
  53748. /**
  53749. * Starts this Timer running.
  53750. * @method Phaser.Timer#start
  53751. * @param {integer} [delay=0] - The number of milliseconds, in {@link Phaser.Time game time}, that should elapse before the Timer will start.
  53752. */
  53753. start: function (delay) {
  53754. if (this.running)
  53755. {
  53756. return;
  53757. }
  53758. this._started = this.game.time.time + (delay || 0);
  53759. this.running = true;
  53760. for (var i = 0; i < this.events.length; i++)
  53761. {
  53762. this.events[i].tick = this.events[i].delay + this._started;
  53763. }
  53764. },
  53765. /**
  53766. * Stops this Timer from running. Does not cause it to be destroyed if autoDestroy is set to true.
  53767. * @method Phaser.Timer#stop
  53768. * @param {boolean} [clearEvents=true] - If true all the events in Timer will be cleared, otherwise they will remain.
  53769. */
  53770. stop: function (clearEvents) {
  53771. this.running = false;
  53772. if (clearEvents === undefined) { clearEvents = true; }
  53773. if (clearEvents)
  53774. {
  53775. this.events.length = 0;
  53776. }
  53777. },
  53778. /**
  53779. * Removes a pending TimerEvent from the queue.
  53780. * @param {Phaser.TimerEvent} event - The event to remove from the queue.
  53781. * @method Phaser.Timer#remove
  53782. */
  53783. remove: function (event) {
  53784. for (var i = 0; i < this.events.length; i++)
  53785. {
  53786. if (this.events[i] === event)
  53787. {
  53788. this.events[i].pendingDelete = true;
  53789. return true;
  53790. }
  53791. }
  53792. return false;
  53793. },
  53794. /**
  53795. * Orders the events on this Timer so they are in tick order.
  53796. * This is called automatically when new events are created.
  53797. * @method Phaser.Timer#order
  53798. * @protected
  53799. */
  53800. order: function () {
  53801. if (this.events.length > 0)
  53802. {
  53803. // Sort the events so the one with the lowest tick is first
  53804. this.events.sort(this.sortHandler);
  53805. this.nextTick = this.events[0].tick;
  53806. }
  53807. },
  53808. /**
  53809. * Sort handler used by Phaser.Timer.order.
  53810. * @method Phaser.Timer#sortHandler
  53811. * @private
  53812. */
  53813. sortHandler: function (a, b) {
  53814. if (a.tick < b.tick)
  53815. {
  53816. return -1;
  53817. }
  53818. else if (a.tick > b.tick)
  53819. {
  53820. return 1;
  53821. }
  53822. return 0;
  53823. },
  53824. /**
  53825. * Clears any events from the Timer which have pendingDelete set to true and then resets the private _len and _i values.
  53826. *
  53827. * @method Phaser.Timer#clearPendingEvents
  53828. * @protected
  53829. */
  53830. clearPendingEvents: function () {
  53831. this._i = this.events.length;
  53832. while (this._i--)
  53833. {
  53834. if (this.events[this._i].pendingDelete)
  53835. {
  53836. this.events.splice(this._i, 1);
  53837. }
  53838. }
  53839. this._len = this.events.length;
  53840. this._i = 0;
  53841. },
  53842. /**
  53843. * The main Timer update event, called automatically by Phaser.Time.update.
  53844. *
  53845. * @method Phaser.Timer#update
  53846. * @protected
  53847. * @param {number} time - The time from the core game clock.
  53848. * @return {boolean} True if there are still events waiting to be dispatched, otherwise false if this Timer can be destroyed.
  53849. */
  53850. update: function (time) {
  53851. if (this.paused)
  53852. {
  53853. return true;
  53854. }
  53855. this.elapsed = time - this._now;
  53856. this._now = time;
  53857. // spike-dislike
  53858. if (this.elapsed > this.timeCap)
  53859. {
  53860. // For some reason the time between now and the last time the game was updated was larger than our timeCap.
  53861. // This can happen if the Stage.disableVisibilityChange is true and you swap tabs, which makes the raf pause.
  53862. // In this case we need to adjust the TimerEvents and nextTick.
  53863. this.adjustEvents(time - this.elapsed);
  53864. }
  53865. this._marked = 0;
  53866. // Clears events marked for deletion and resets _len and _i to 0.
  53867. this.clearPendingEvents();
  53868. if (this.running && this._now >= this.nextTick && this._len > 0)
  53869. {
  53870. while (this._i < this._len && this.running)
  53871. {
  53872. if (this._now >= this.events[this._i].tick && !this.events[this._i].pendingDelete)
  53873. {
  53874. // (now + delay) - (time difference from last tick to now)
  53875. this._newTick = (this._now + this.events[this._i].delay) - (this._now - this.events[this._i].tick);
  53876. if (this._newTick < 0)
  53877. {
  53878. this._newTick = this._now + this.events[this._i].delay;
  53879. }
  53880. if (this.events[this._i].loop === true)
  53881. {
  53882. this.events[this._i].tick = this._newTick;
  53883. this.events[this._i].callback.apply(this.events[this._i].callbackContext, this.events[this._i].args);
  53884. }
  53885. else if (this.events[this._i].repeatCount > 0)
  53886. {
  53887. this.events[this._i].repeatCount--;
  53888. this.events[this._i].tick = this._newTick;
  53889. this.events[this._i].callback.apply(this.events[this._i].callbackContext, this.events[this._i].args);
  53890. }
  53891. else
  53892. {
  53893. this._marked++;
  53894. this.events[this._i].pendingDelete = true;
  53895. this.events[this._i].callback.apply(this.events[this._i].callbackContext, this.events[this._i].args);
  53896. }
  53897. this._i++;
  53898. }
  53899. else
  53900. {
  53901. break;
  53902. }
  53903. }
  53904. // Are there any events left?
  53905. if (this.events.length > this._marked)
  53906. {
  53907. this.order();
  53908. }
  53909. else
  53910. {
  53911. this.expired = true;
  53912. this.onComplete.dispatch(this);
  53913. }
  53914. }
  53915. if (this.expired && this.autoDestroy)
  53916. {
  53917. return false;
  53918. }
  53919. else
  53920. {
  53921. return true;
  53922. }
  53923. },
  53924. /**
  53925. * Pauses the Timer and all events in the queue.
  53926. * @method Phaser.Timer#pause
  53927. */
  53928. pause: function () {
  53929. if (!this.running)
  53930. {
  53931. return;
  53932. }
  53933. this._codePaused = true;
  53934. if (this.paused)
  53935. {
  53936. return;
  53937. }
  53938. this._pauseStarted = this.game.time.time;
  53939. this.paused = true;
  53940. },
  53941. /**
  53942. * Internal pause/resume control - user code should use Timer.pause instead.
  53943. * @method Phaser.Timer#_pause
  53944. * @private
  53945. */
  53946. _pause: function () {
  53947. if (this.paused || !this.running)
  53948. {
  53949. return;
  53950. }
  53951. this._pauseStarted = this.game.time.time;
  53952. this.paused = true;
  53953. },
  53954. /**
  53955. * Adjusts the time of all pending events and the nextTick by the given baseTime.
  53956. *
  53957. * @method Phaser.Timer#adjustEvents
  53958. * @protected
  53959. */
  53960. adjustEvents: function (baseTime) {
  53961. for (var i = 0; i < this.events.length; i++)
  53962. {
  53963. if (!this.events[i].pendingDelete)
  53964. {
  53965. // Work out how long there would have been from when the game paused until the events next tick
  53966. var t = this.events[i].tick - baseTime;
  53967. if (t < 0)
  53968. {
  53969. t = 0;
  53970. }
  53971. // Add the difference on to the time now
  53972. this.events[i].tick = this._now + t;
  53973. }
  53974. }
  53975. var d = this.nextTick - baseTime;
  53976. if (d < 0)
  53977. {
  53978. this.nextTick = this._now;
  53979. }
  53980. else
  53981. {
  53982. this.nextTick = this._now + d;
  53983. }
  53984. },
  53985. /**
  53986. * Resumes the Timer and updates all pending events.
  53987. *
  53988. * @method Phaser.Timer#resume
  53989. */
  53990. resume: function () {
  53991. if (!this.paused)
  53992. {
  53993. return;
  53994. }
  53995. var now = this.game.time.time;
  53996. this._pauseTotal += now - this._now;
  53997. this._now = now;
  53998. this.adjustEvents(this._pauseStarted);
  53999. this.paused = false;
  54000. this._codePaused = false;
  54001. },
  54002. /**
  54003. * Internal pause/resume control - user code should use Timer.resume instead.
  54004. * @method Phaser.Timer#_resume
  54005. * @private
  54006. */
  54007. _resume: function () {
  54008. if (this._codePaused)
  54009. {
  54010. return;
  54011. }
  54012. else
  54013. {
  54014. this.resume();
  54015. }
  54016. },
  54017. /**
  54018. * Removes all Events from this Timer and all callbacks linked to onComplete, but leaves the Timer running.
  54019. * The onComplete callbacks won't be called.
  54020. *
  54021. * @method Phaser.Timer#removeAll
  54022. */
  54023. removeAll: function () {
  54024. this.onComplete.removeAll();
  54025. this.events.length = 0;
  54026. this._len = 0;
  54027. this._i = 0;
  54028. },
  54029. /**
  54030. * Destroys this Timer. Any pending Events are not dispatched.
  54031. * The onComplete callbacks won't be called.
  54032. *
  54033. * @method Phaser.Timer#destroy
  54034. */
  54035. destroy: function () {
  54036. this.onComplete.removeAll();
  54037. this.running = false;
  54038. this.events = [];
  54039. this._len = 0;
  54040. this._i = 0;
  54041. }
  54042. };
  54043. /**
  54044. * @name Phaser.Timer#next
  54045. * @property {number} next - The time at which the next event will occur.
  54046. * @readonly
  54047. */
  54048. Object.defineProperty(Phaser.Timer.prototype, "next", {
  54049. get: function () {
  54050. return this.nextTick;
  54051. }
  54052. });
  54053. /**
  54054. * @name Phaser.Timer#duration
  54055. * @property {number} duration - The duration in ms remaining until the next event will occur.
  54056. * @readonly
  54057. */
  54058. Object.defineProperty(Phaser.Timer.prototype, "duration", {
  54059. get: function () {
  54060. if (this.running && this.nextTick > this._now)
  54061. {
  54062. return this.nextTick - this._now;
  54063. }
  54064. else
  54065. {
  54066. return 0;
  54067. }
  54068. }
  54069. });
  54070. /**
  54071. * @name Phaser.Timer#length
  54072. * @property {number} length - The number of pending events in the queue.
  54073. * @readonly
  54074. */
  54075. Object.defineProperty(Phaser.Timer.prototype, "length", {
  54076. get: function () {
  54077. return this.events.length;
  54078. }
  54079. });
  54080. /**
  54081. * @name Phaser.Timer#ms
  54082. * @property {number} ms - The duration in milliseconds that this Timer has been running for.
  54083. * @readonly
  54084. */
  54085. Object.defineProperty(Phaser.Timer.prototype, "ms", {
  54086. get: function () {
  54087. if (this.running)
  54088. {
  54089. return this._now - this._started - this._pauseTotal;
  54090. }
  54091. else
  54092. {
  54093. return 0;
  54094. }
  54095. }
  54096. });
  54097. /**
  54098. * @name Phaser.Timer#seconds
  54099. * @property {number} seconds - The duration in seconds that this Timer has been running for.
  54100. * @readonly
  54101. */
  54102. Object.defineProperty(Phaser.Timer.prototype, "seconds", {
  54103. get: function () {
  54104. if (this.running)
  54105. {
  54106. return this.ms * 0.001;
  54107. }
  54108. else
  54109. {
  54110. return 0;
  54111. }
  54112. }
  54113. });
  54114. Phaser.Timer.prototype.constructor = Phaser.Timer;
  54115. /**
  54116. * @author Richard Davey <rich@photonstorm.com>
  54117. * @copyright 2016 Photon Storm Ltd.
  54118. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  54119. */
  54120. /**
  54121. * A TimerEvent is a single event that is processed by a Phaser.Timer.
  54122. *
  54123. * It consists of a delay, which is a value in milliseconds after which the event will fire.
  54124. * When the event fires it calls a specific callback with the specified arguments.
  54125. *
  54126. * Use {@link Phaser.Timer#add}, {@link Phaser.Timer#repeat}, or {@link Phaser.Timer#loop} methods to create a new event.
  54127. *
  54128. * @class Phaser.TimerEvent
  54129. * @constructor
  54130. * @param {Phaser.Timer} timer - The Timer object that this TimerEvent belongs to.
  54131. * @param {number} delay - The delay in ms at which this TimerEvent fires.
  54132. * @param {number} tick - The tick is the next game clock time that this event will fire at.
  54133. * @param {number} repeatCount - If this TimerEvent repeats it will do so this many times.
  54134. * @param {boolean} loop - True if this TimerEvent loops, otherwise false.
  54135. * @param {function} callback - The callback that will be called when the TimerEvent occurs.
  54136. * @param {object} callbackContext - The context in which the callback will be called.
  54137. * @param {any[]} arguments - Additional arguments to be passed to the callback.
  54138. */
  54139. Phaser.TimerEvent = function (timer, delay, tick, repeatCount, loop, callback, callbackContext, args) {
  54140. /**
  54141. * @property {Phaser.Timer} timer - The Timer object that this TimerEvent belongs to.
  54142. * @protected
  54143. * @readonly
  54144. */
  54145. this.timer = timer;
  54146. /**
  54147. * @property {number} delay - The delay in ms at which this TimerEvent fires.
  54148. */
  54149. this.delay = delay;
  54150. /**
  54151. * @property {number} tick - The tick is the next game clock time that this event will fire at.
  54152. */
  54153. this.tick = tick;
  54154. /**
  54155. * @property {number} repeatCount - If this TimerEvent repeats it will do so this many times.
  54156. */
  54157. this.repeatCount = repeatCount - 1;
  54158. /**
  54159. * @property {boolean} loop - True if this TimerEvent loops, otherwise false.
  54160. */
  54161. this.loop = loop;
  54162. /**
  54163. * @property {function} callback - The callback that will be called when the TimerEvent occurs.
  54164. */
  54165. this.callback = callback;
  54166. /**
  54167. * @property {object} callbackContext - The context in which the callback will be called.
  54168. */
  54169. this.callbackContext = callbackContext;
  54170. /**
  54171. * @property {any[]} arguments - Additional arguments to be passed to the callback.
  54172. */
  54173. this.args = args;
  54174. /**
  54175. * @property {boolean} pendingDelete - A flag that controls if the TimerEvent is pending deletion.
  54176. * @protected
  54177. */
  54178. this.pendingDelete = false;
  54179. };
  54180. Phaser.TimerEvent.prototype.constructor = Phaser.TimerEvent;
  54181. /**
  54182. * @author Richard Davey <rich@photonstorm.com>
  54183. * @copyright 2016 Photon Storm Ltd.
  54184. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  54185. */
  54186. /**
  54187. * The Animation Manager is used to add, play and update Phaser Animations.
  54188. * Any Game Object such as Phaser.Sprite that supports animation contains a single AnimationManager instance.
  54189. *
  54190. * @class Phaser.AnimationManager
  54191. * @constructor
  54192. * @param {Phaser.Sprite} sprite - A reference to the Game Object that owns this AnimationManager.
  54193. */
  54194. Phaser.AnimationManager = function (sprite) {
  54195. /**
  54196. * @property {Phaser.Sprite} sprite - A reference to the parent Sprite that owns this AnimationManager.
  54197. */
  54198. this.sprite = sprite;
  54199. /**
  54200. * @property {Phaser.Game} game - A reference to the currently running Game.
  54201. */
  54202. this.game = sprite.game;
  54203. /**
  54204. * The currently displayed Frame of animation, if any.
  54205. * This property is only set once an Animation starts playing. Until that point it remains set as `null`.
  54206. *
  54207. * @property {Phaser.Frame} currentFrame
  54208. * @default
  54209. */
  54210. this.currentFrame = null;
  54211. /**
  54212. * @property {Phaser.Animation} currentAnim - The currently displayed animation, if any.
  54213. * @default
  54214. */
  54215. this.currentAnim = null;
  54216. /**
  54217. * @property {boolean} updateIfVisible - Should the animation data continue to update even if the Sprite.visible is set to false.
  54218. * @default
  54219. */
  54220. this.updateIfVisible = true;
  54221. /**
  54222. * @property {boolean} isLoaded - Set to true once animation data has been loaded.
  54223. * @default
  54224. */
  54225. this.isLoaded = false;
  54226. /**
  54227. * @property {Phaser.FrameData} _frameData - A temp. var for holding the currently playing Animations FrameData.
  54228. * @private
  54229. * @default
  54230. */
  54231. this._frameData = null;
  54232. /**
  54233. * @property {object} _anims - An internal object that stores all of the Animation instances.
  54234. * @private
  54235. */
  54236. this._anims = {};
  54237. /**
  54238. * @property {object} _outputFrames - An internal object to help avoid gc.
  54239. * @private
  54240. */
  54241. this._outputFrames = [];
  54242. };
  54243. Phaser.AnimationManager.prototype = {
  54244. /**
  54245. * Loads FrameData into the internal temporary vars and resets the frame index to zero.
  54246. * This is called automatically when a new Sprite is created.
  54247. *
  54248. * @method Phaser.AnimationManager#loadFrameData
  54249. * @private
  54250. * @param {Phaser.FrameData} frameData - The FrameData set to load.
  54251. * @param {string|number} frame - The frame to default to.
  54252. * @return {boolean} Returns `true` if the frame data was loaded successfully, otherwise `false`
  54253. */
  54254. loadFrameData: function (frameData, frame) {
  54255. if (frameData === undefined)
  54256. {
  54257. return false;
  54258. }
  54259. if (this.isLoaded)
  54260. {
  54261. // We need to update the frameData that the animations are using
  54262. for (var anim in this._anims)
  54263. {
  54264. this._anims[anim].updateFrameData(frameData);
  54265. }
  54266. }
  54267. this._frameData = frameData;
  54268. if (frame === undefined || frame === null)
  54269. {
  54270. this.frame = 0;
  54271. }
  54272. else
  54273. {
  54274. if (typeof frame === 'string')
  54275. {
  54276. this.frameName = frame;
  54277. }
  54278. else
  54279. {
  54280. this.frame = frame;
  54281. }
  54282. }
  54283. this.isLoaded = true;
  54284. return true;
  54285. },
  54286. /**
  54287. * Loads FrameData into the internal temporary vars and resets the frame index to zero.
  54288. * This is called automatically when a new Sprite is created.
  54289. *
  54290. * @method Phaser.AnimationManager#copyFrameData
  54291. * @private
  54292. * @param {Phaser.FrameData} frameData - The FrameData set to load.
  54293. * @param {string|number} frame - The frame to default to.
  54294. * @return {boolean} Returns `true` if the frame data was loaded successfully, otherwise `false`
  54295. */
  54296. copyFrameData: function (frameData, frame) {
  54297. this._frameData = frameData.clone();
  54298. if (this.isLoaded)
  54299. {
  54300. // We need to update the frameData that the animations are using
  54301. for (var anim in this._anims)
  54302. {
  54303. this._anims[anim].updateFrameData(this._frameData);
  54304. }
  54305. }
  54306. if (frame === undefined || frame === null)
  54307. {
  54308. this.frame = 0;
  54309. }
  54310. else
  54311. {
  54312. if (typeof frame === 'string')
  54313. {
  54314. this.frameName = frame;
  54315. }
  54316. else
  54317. {
  54318. this.frame = frame;
  54319. }
  54320. }
  54321. this.isLoaded = true;
  54322. return true;
  54323. },
  54324. /**
  54325. * Adds a new animation under the given key. Optionally set the frames, frame rate and loop.
  54326. * Animations added in this way are played back with the play function.
  54327. *
  54328. * @method Phaser.AnimationManager#add
  54329. * @param {string} name - The unique (within this Sprite) name for the animation, i.e. "run", "fire", "walk".
  54330. * @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.
  54331. * @param {number} [frameRate=60] - The speed at which the animation should play. The speed is given in frames per second.
  54332. * @param {boolean} [loop=false] - Whether or not the animation is looped or just plays once.
  54333. * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings?
  54334. * @return {Phaser.Animation} The Animation object that was created.
  54335. */
  54336. add: function (name, frames, frameRate, loop, useNumericIndex) {
  54337. frames = frames || [];
  54338. frameRate = frameRate || 60;
  54339. if (loop === undefined) { loop = false; }
  54340. // If they didn't set the useNumericIndex then let's at least try and guess it
  54341. if (useNumericIndex === undefined)
  54342. {
  54343. if (frames && typeof frames[0] === 'number')
  54344. {
  54345. useNumericIndex = true;
  54346. }
  54347. else
  54348. {
  54349. useNumericIndex = false;
  54350. }
  54351. }
  54352. this._outputFrames = [];
  54353. this._frameData.getFrameIndexes(frames, useNumericIndex, this._outputFrames);
  54354. this._anims[name] = new Phaser.Animation(this.game, this.sprite, name, this._frameData, this._outputFrames, frameRate, loop);
  54355. this.currentAnim = this._anims[name];
  54356. // This shouldn't be set until the Animation is played, surely?
  54357. // this.currentFrame = this.currentAnim.currentFrame;
  54358. if (this.sprite.tilingTexture)
  54359. {
  54360. this.sprite.refreshTexture = true;
  54361. }
  54362. return this._anims[name];
  54363. },
  54364. /**
  54365. * Check whether the frames in the given array are valid and exist.
  54366. *
  54367. * @method Phaser.AnimationManager#validateFrames
  54368. * @param {Array} frames - An array of frames to be validated.
  54369. * @param {boolean} [useNumericIndex=true] - Validate the frames based on their numeric index (true) or string index (false)
  54370. * @return {boolean} True if all given Frames are valid, otherwise false.
  54371. */
  54372. validateFrames: function (frames, useNumericIndex) {
  54373. if (useNumericIndex === undefined) { useNumericIndex = true; }
  54374. for (var i = 0; i < frames.length; i++)
  54375. {
  54376. if (useNumericIndex === true)
  54377. {
  54378. if (frames[i] > this._frameData.total)
  54379. {
  54380. return false;
  54381. }
  54382. }
  54383. else
  54384. {
  54385. if (this._frameData.checkFrameName(frames[i]) === false)
  54386. {
  54387. return false;
  54388. }
  54389. }
  54390. }
  54391. return true;
  54392. },
  54393. /**
  54394. * Play an animation based on the given key. The animation should previously have been added via `animations.add`
  54395. *
  54396. * If the requested animation is already playing this request will be ignored.
  54397. * If you need to reset an already running animation do so directly on the Animation object itself.
  54398. *
  54399. * @method Phaser.AnimationManager#play
  54400. * @param {string} name - The name of the animation to be played, e.g. "fire", "walk", "jump".
  54401. * @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.
  54402. * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used.
  54403. * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed.
  54404. * @return {Phaser.Animation} A reference to playing Animation instance.
  54405. */
  54406. play: function (name, frameRate, loop, killOnComplete) {
  54407. if (this._anims[name])
  54408. {
  54409. if (this.currentAnim === this._anims[name])
  54410. {
  54411. if (this.currentAnim.isPlaying === false)
  54412. {
  54413. this.currentAnim.paused = false;
  54414. return this.currentAnim.play(frameRate, loop, killOnComplete);
  54415. }
  54416. return this.currentAnim;
  54417. }
  54418. else
  54419. {
  54420. if (this.currentAnim && this.currentAnim.isPlaying)
  54421. {
  54422. this.currentAnim.stop();
  54423. }
  54424. this.currentAnim = this._anims[name];
  54425. this.currentAnim.paused = false;
  54426. this.currentFrame = this.currentAnim.currentFrame;
  54427. return this.currentAnim.play(frameRate, loop, killOnComplete);
  54428. }
  54429. }
  54430. },
  54431. /**
  54432. * Stop playback of an animation. If a name is given that specific animation is stopped, otherwise the current animation is stopped.
  54433. * The currentAnim property of the AnimationManager is automatically set to the animation given.
  54434. *
  54435. * @method Phaser.AnimationManager#stop
  54436. * @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.
  54437. * @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)
  54438. */
  54439. stop: function (name, resetFrame) {
  54440. if (resetFrame === undefined) { resetFrame = false; }
  54441. if (this.currentAnim && (typeof name !== 'string' || name === this.currentAnim.name))
  54442. {
  54443. this.currentAnim.stop(resetFrame);
  54444. }
  54445. },
  54446. /**
  54447. * The main update function is called by the Sprites update loop. It's responsible for updating animation frames and firing related events.
  54448. *
  54449. * @method Phaser.AnimationManager#update
  54450. * @protected
  54451. * @return {boolean} True if a new animation frame has been set, otherwise false.
  54452. */
  54453. update: function () {
  54454. if (this.updateIfVisible && !this.sprite.visible)
  54455. {
  54456. return false;
  54457. }
  54458. if (this.currentAnim && this.currentAnim.update())
  54459. {
  54460. this.currentFrame = this.currentAnim.currentFrame;
  54461. return true;
  54462. }
  54463. return false;
  54464. },
  54465. /**
  54466. * Advances by the given number of frames in the current animation, taking the loop value into consideration.
  54467. *
  54468. * @method Phaser.AnimationManager#next
  54469. * @param {number} [quantity=1] - The number of frames to advance.
  54470. */
  54471. next: function (quantity) {
  54472. if (this.currentAnim)
  54473. {
  54474. this.currentAnim.next(quantity);
  54475. this.currentFrame = this.currentAnim.currentFrame;
  54476. }
  54477. },
  54478. /**
  54479. * Moves backwards the given number of frames in the current animation, taking the loop value into consideration.
  54480. *
  54481. * @method Phaser.AnimationManager#previous
  54482. * @param {number} [quantity=1] - The number of frames to move back.
  54483. */
  54484. previous: function (quantity) {
  54485. if (this.currentAnim)
  54486. {
  54487. this.currentAnim.previous(quantity);
  54488. this.currentFrame = this.currentAnim.currentFrame;
  54489. }
  54490. },
  54491. /**
  54492. * Returns an animation that was previously added by name.
  54493. *
  54494. * @method Phaser.AnimationManager#getAnimation
  54495. * @param {string} name - The name of the animation to be returned, e.g. "fire".
  54496. * @return {Phaser.Animation} The Animation instance, if found, otherwise null.
  54497. */
  54498. getAnimation: function (name) {
  54499. if (typeof name === 'string')
  54500. {
  54501. if (this._anims[name])
  54502. {
  54503. return this._anims[name];
  54504. }
  54505. }
  54506. return null;
  54507. },
  54508. /**
  54509. * Refreshes the current frame data back to the parent Sprite and also resets the texture data.
  54510. *
  54511. * @method Phaser.AnimationManager#refreshFrame
  54512. */
  54513. refreshFrame: function () {
  54514. // TODO
  54515. this.sprite.setTexture(PIXI.TextureCache[this.currentFrame.uuid]);
  54516. },
  54517. /**
  54518. * Destroys all references this AnimationManager contains.
  54519. * Iterates through the list of animations stored in this manager and calls destroy on each of them.
  54520. *
  54521. * @method Phaser.AnimationManager#destroy
  54522. */
  54523. destroy: function () {
  54524. var anim = null;
  54525. for (var anim in this._anims)
  54526. {
  54527. if (this._anims.hasOwnProperty(anim))
  54528. {
  54529. this._anims[anim].destroy();
  54530. }
  54531. }
  54532. this._anims = {};
  54533. this._outputFrames = [];
  54534. this._frameData = null;
  54535. this.currentAnim = null;
  54536. this.currentFrame = null;
  54537. this.sprite = null;
  54538. this.game = null;
  54539. }
  54540. };
  54541. Phaser.AnimationManager.prototype.constructor = Phaser.AnimationManager;
  54542. /**
  54543. * @name Phaser.AnimationManager#frameData
  54544. * @property {Phaser.FrameData} frameData - The current animations FrameData.
  54545. * @readonly
  54546. */
  54547. Object.defineProperty(Phaser.AnimationManager.prototype, 'frameData', {
  54548. get: function () {
  54549. return this._frameData;
  54550. }
  54551. });
  54552. /**
  54553. * @name Phaser.AnimationManager#frameTotal
  54554. * @property {number} frameTotal - The total number of frames in the currently loaded FrameData, or -1 if no FrameData is loaded.
  54555. * @readonly
  54556. */
  54557. Object.defineProperty(Phaser.AnimationManager.prototype, 'frameTotal', {
  54558. get: function () {
  54559. return this._frameData.total;
  54560. }
  54561. });
  54562. /**
  54563. * @name Phaser.AnimationManager#paused
  54564. * @property {boolean} paused - Gets and sets the paused state of the current animation.
  54565. */
  54566. Object.defineProperty(Phaser.AnimationManager.prototype, 'paused', {
  54567. get: function () {
  54568. return this.currentAnim.isPaused;
  54569. },
  54570. set: function (value) {
  54571. this.currentAnim.paused = value;
  54572. }
  54573. });
  54574. /**
  54575. * @name Phaser.AnimationManager#name
  54576. * @property {string} name - Gets the current animation name, if set.
  54577. */
  54578. Object.defineProperty(Phaser.AnimationManager.prototype, 'name', {
  54579. get: function () {
  54580. if (this.currentAnim)
  54581. {
  54582. return this.currentAnim.name;
  54583. }
  54584. }
  54585. });
  54586. /**
  54587. * @name Phaser.AnimationManager#frame
  54588. * @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display.
  54589. */
  54590. Object.defineProperty(Phaser.AnimationManager.prototype, 'frame', {
  54591. get: function () {
  54592. if (this.currentFrame)
  54593. {
  54594. return this.currentFrame.index;
  54595. }
  54596. },
  54597. set: function (value) {
  54598. if (typeof value === 'number' && this._frameData && this._frameData.getFrame(value) !== null)
  54599. {
  54600. this.currentFrame = this._frameData.getFrame(value);
  54601. if (this.currentFrame)
  54602. {
  54603. this.sprite.setFrame(this.currentFrame);
  54604. }
  54605. }
  54606. }
  54607. });
  54608. /**
  54609. * @name Phaser.AnimationManager#frameName
  54610. * @property {string} frameName - Gets or sets the current frame name and updates the Texture Cache for display.
  54611. */
  54612. Object.defineProperty(Phaser.AnimationManager.prototype, 'frameName', {
  54613. get: function () {
  54614. if (this.currentFrame)
  54615. {
  54616. return this.currentFrame.name;
  54617. }
  54618. },
  54619. set: function (value) {
  54620. if (typeof value === 'string' && this._frameData && this._frameData.getFrameByName(value) !== null)
  54621. {
  54622. this.currentFrame = this._frameData.getFrameByName(value);
  54623. if (this.currentFrame)
  54624. {
  54625. this._frameIndex = this.currentFrame.index;
  54626. this.sprite.setFrame(this.currentFrame);
  54627. }
  54628. }
  54629. else
  54630. {
  54631. console.warn('Cannot set frameName: ' + value);
  54632. }
  54633. }
  54634. });
  54635. /**
  54636. * @author Richard Davey <rich@photonstorm.com>
  54637. * @copyright 2016 Photon Storm Ltd.
  54638. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  54639. */
  54640. /**
  54641. * An Animation instance contains a single animation and the controls to play it.
  54642. *
  54643. * It is created by the AnimationManager, consists of Animation.Frame objects and belongs to a single Game Object such as a Sprite.
  54644. *
  54645. * @class Phaser.Animation
  54646. * @constructor
  54647. * @param {Phaser.Game} game - A reference to the currently running game.
  54648. * @param {Phaser.Sprite} parent - A reference to the owner of this Animation.
  54649. * @param {string} name - The unique name for this animation, used in playback commands.
  54650. * @param {Phaser.FrameData} frameData - The FrameData object that contains all frames used by this Animation.
  54651. * @param {number[]|string[]} frames - An array of numbers or strings indicating which frames to play in which order.
  54652. * @param {number} [frameRate=60] - The speed at which the animation should play. The speed is given in frames per second.
  54653. * @param {boolean} [loop=false] - Whether or not the animation is looped or just plays once.
  54654. */
  54655. Phaser.Animation = function (game, parent, name, frameData, frames, frameRate, loop) {
  54656. if (loop === undefined) { loop = false; }
  54657. /**
  54658. * @property {Phaser.Game} game - A reference to the currently running Game.
  54659. */
  54660. this.game = game;
  54661. /**
  54662. * @property {Phaser.Sprite} _parent - A reference to the parent Sprite that owns this Animation.
  54663. * @private
  54664. */
  54665. this._parent = parent;
  54666. /**
  54667. * @property {Phaser.FrameData} _frameData - The FrameData the Animation uses.
  54668. * @private
  54669. */
  54670. this._frameData = frameData;
  54671. /**
  54672. * @property {string} name - The user defined name given to this Animation.
  54673. */
  54674. this.name = name;
  54675. /**
  54676. * @property {array} _frames
  54677. * @private
  54678. */
  54679. this._frames = [];
  54680. this._frames = this._frames.concat(frames);
  54681. /**
  54682. * @property {number} delay - The delay in ms between each frame of the Animation, based on the given frameRate.
  54683. */
  54684. this.delay = 1000 / frameRate;
  54685. /**
  54686. * @property {boolean} loop - The loop state of the Animation.
  54687. */
  54688. this.loop = loop;
  54689. /**
  54690. * @property {number} loopCount - The number of times the animation has looped since it was last started.
  54691. */
  54692. this.loopCount = 0;
  54693. /**
  54694. * @property {boolean} killOnComplete - Should the parent of this Animation be killed when the animation completes?
  54695. * @default
  54696. */
  54697. this.killOnComplete = false;
  54698. /**
  54699. * @property {boolean} isFinished - The finished state of the Animation. Set to true once playback completes, false during playback.
  54700. * @default
  54701. */
  54702. this.isFinished = false;
  54703. /**
  54704. * @property {boolean} isPlaying - The playing state of the Animation. Set to false once playback completes, true during playback.
  54705. * @default
  54706. */
  54707. this.isPlaying = false;
  54708. /**
  54709. * @property {boolean} isPaused - The paused state of the Animation.
  54710. * @default
  54711. */
  54712. this.isPaused = false;
  54713. /**
  54714. * @property {boolean} _pauseStartTime - The time the animation paused.
  54715. * @private
  54716. * @default
  54717. */
  54718. this._pauseStartTime = 0;
  54719. /**
  54720. * @property {number} _frameIndex
  54721. * @private
  54722. * @default
  54723. */
  54724. this._frameIndex = 0;
  54725. /**
  54726. * @property {number} _frameDiff
  54727. * @private
  54728. * @default
  54729. */
  54730. this._frameDiff = 0;
  54731. /**
  54732. * @property {number} _frameSkip
  54733. * @private
  54734. * @default
  54735. */
  54736. this._frameSkip = 1;
  54737. /**
  54738. * @property {Phaser.Frame} currentFrame - The currently displayed frame of the Animation.
  54739. */
  54740. this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]);
  54741. /**
  54742. * @property {Phaser.Signal} onStart - This event is dispatched when this Animation starts playback.
  54743. */
  54744. this.onStart = new Phaser.Signal();
  54745. /**
  54746. * This event is dispatched when the Animation changes frame.
  54747. * By default this event is disabled due to its intensive nature. Enable it with: `Animation.enableUpdate = true`.
  54748. * Note that the event is only dispatched with the current frame. In a low-FPS environment Animations
  54749. * will automatically frame-skip to try and claw back time, so do not base your code on expecting to
  54750. * receive a perfectly sequential set of frames from this event.
  54751. * @property {Phaser.Signal|null} onUpdate
  54752. * @default
  54753. */
  54754. this.onUpdate = null;
  54755. /**
  54756. * @property {Phaser.Signal} onComplete - This event is dispatched when this Animation completes playback. If the animation is set to loop this is never fired, listen for onLoop instead.
  54757. */
  54758. this.onComplete = new Phaser.Signal();
  54759. /**
  54760. * @property {Phaser.Signal} onLoop - This event is dispatched when this Animation loops.
  54761. */
  54762. this.onLoop = new Phaser.Signal();
  54763. // Set-up some event listeners
  54764. this.game.onPause.add(this.onPause, this);
  54765. this.game.onResume.add(this.onResume, this);
  54766. };
  54767. Phaser.Animation.prototype = {
  54768. /**
  54769. * Plays this animation.
  54770. *
  54771. * @method Phaser.Animation#play
  54772. * @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.
  54773. * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used.
  54774. * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed.
  54775. * @return {Phaser.Animation} - A reference to this Animation instance.
  54776. */
  54777. play: function (frameRate, loop, killOnComplete) {
  54778. if (typeof frameRate === 'number')
  54779. {
  54780. // If they set a new frame rate then use it, otherwise use the one set on creation
  54781. this.delay = 1000 / frameRate;
  54782. }
  54783. if (typeof loop === 'boolean')
  54784. {
  54785. // If they set a new loop value then use it, otherwise use the one set on creation
  54786. this.loop = loop;
  54787. }
  54788. if (typeof killOnComplete !== 'undefined')
  54789. {
  54790. // Remove the parent sprite once the animation has finished?
  54791. this.killOnComplete = killOnComplete;
  54792. }
  54793. this.isPlaying = true;
  54794. this.isFinished = false;
  54795. this.paused = false;
  54796. this.loopCount = 0;
  54797. this._timeLastFrame = this.game.time.time;
  54798. this._timeNextFrame = this.game.time.time + this.delay;
  54799. this._frameIndex = 0;
  54800. this.updateCurrentFrame(false, true);
  54801. this._parent.events.onAnimationStart$dispatch(this._parent, this);
  54802. this.onStart.dispatch(this._parent, this);
  54803. this._parent.animations.currentAnim = this;
  54804. this._parent.animations.currentFrame = this.currentFrame;
  54805. return this;
  54806. },
  54807. /**
  54808. * Sets this animation back to the first frame and restarts the animation.
  54809. *
  54810. * @method Phaser.Animation#restart
  54811. */
  54812. restart: function () {
  54813. this.isPlaying = true;
  54814. this.isFinished = false;
  54815. this.paused = false;
  54816. this.loopCount = 0;
  54817. this._timeLastFrame = this.game.time.time;
  54818. this._timeNextFrame = this.game.time.time + this.delay;
  54819. this._frameIndex = 0;
  54820. this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]);
  54821. this._parent.setFrame(this.currentFrame);
  54822. this._parent.animations.currentAnim = this;
  54823. this._parent.animations.currentFrame = this.currentFrame;
  54824. this.onStart.dispatch(this._parent, this);
  54825. },
  54826. /**
  54827. * Sets this animations playback to a given frame with the given ID.
  54828. *
  54829. * @method Phaser.Animation#setFrame
  54830. * @param {string|number} [frameId] - The identifier of the frame to set. Can be the name of the frame, the sprite index of the frame, or the animation-local frame index.
  54831. * @param {boolean} [useLocalFrameIndex=false] - If you provide a number for frameId, should it use the numeric indexes of the frameData, or the 0-indexed frame index local to the animation.
  54832. */
  54833. setFrame: function(frameId, useLocalFrameIndex) {
  54834. var frameIndex;
  54835. if (useLocalFrameIndex === undefined)
  54836. {
  54837. useLocalFrameIndex = false;
  54838. }
  54839. // Find the index to the desired frame.
  54840. if (typeof frameId === "string")
  54841. {
  54842. for (var i = 0; i < this._frames.length; i++)
  54843. {
  54844. if (this._frameData.getFrame(this._frames[i]).name === frameId)
  54845. {
  54846. frameIndex = i;
  54847. }
  54848. }
  54849. }
  54850. else if (typeof frameId === "number")
  54851. {
  54852. if (useLocalFrameIndex)
  54853. {
  54854. frameIndex = frameId;
  54855. }
  54856. else
  54857. {
  54858. for (var i = 0; i < this._frames.length; i++)
  54859. {
  54860. if (this._frames[i] === frameIndex)
  54861. {
  54862. frameIndex = i;
  54863. }
  54864. }
  54865. }
  54866. }
  54867. if (frameIndex)
  54868. {
  54869. // Set the current frame index to the found index. Subtract 1 so that it animates to the desired frame on update.
  54870. this._frameIndex = frameIndex - 1;
  54871. // Make the animation update at next update
  54872. this._timeNextFrame = this.game.time.time;
  54873. this.update();
  54874. }
  54875. },
  54876. /**
  54877. * 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.
  54878. * If `dispatchComplete` is true it will dispatch the complete events, otherwise they'll be ignored.
  54879. *
  54880. * @method Phaser.Animation#stop
  54881. * @param {boolean} [resetFrame=false] - If true after the animation stops the currentFrame value will be set to the first frame in this animation.
  54882. * @param {boolean} [dispatchComplete=false] - Dispatch the Animation.onComplete and parent.onAnimationComplete events?
  54883. */
  54884. stop: function (resetFrame, dispatchComplete) {
  54885. if (resetFrame === undefined) { resetFrame = false; }
  54886. if (dispatchComplete === undefined) { dispatchComplete = false; }
  54887. this.isPlaying = false;
  54888. this.isFinished = true;
  54889. this.paused = false;
  54890. if (resetFrame)
  54891. {
  54892. this.currentFrame = this._frameData.getFrame(this._frames[0]);
  54893. this._parent.setFrame(this.currentFrame);
  54894. }
  54895. if (dispatchComplete)
  54896. {
  54897. this._parent.events.onAnimationComplete$dispatch(this._parent, this);
  54898. this.onComplete.dispatch(this._parent, this);
  54899. }
  54900. },
  54901. /**
  54902. * Called when the Game enters a paused state.
  54903. *
  54904. * @method Phaser.Animation#onPause
  54905. */
  54906. onPause: function () {
  54907. if (this.isPlaying)
  54908. {
  54909. this._frameDiff = this._timeNextFrame - this.game.time.time;
  54910. }
  54911. },
  54912. /**
  54913. * Called when the Game resumes from a paused state.
  54914. *
  54915. * @method Phaser.Animation#onResume
  54916. */
  54917. onResume: function () {
  54918. if (this.isPlaying)
  54919. {
  54920. this._timeNextFrame = this.game.time.time + this._frameDiff;
  54921. }
  54922. },
  54923. /**
  54924. * Updates this animation. Called automatically by the AnimationManager.
  54925. *
  54926. * @method Phaser.Animation#update
  54927. */
  54928. update: function () {
  54929. if (this.isPaused)
  54930. {
  54931. return false;
  54932. }
  54933. if (this.isPlaying && this.game.time.time >= this._timeNextFrame)
  54934. {
  54935. this._frameSkip = 1;
  54936. // Lagging?
  54937. this._frameDiff = this.game.time.time - this._timeNextFrame;
  54938. this._timeLastFrame = this.game.time.time;
  54939. if (this._frameDiff > this.delay)
  54940. {
  54941. // We need to skip a frame, work out how many
  54942. this._frameSkip = Math.floor(this._frameDiff / this.delay);
  54943. this._frameDiff -= (this._frameSkip * this.delay);
  54944. }
  54945. // And what's left now?
  54946. this._timeNextFrame = this.game.time.time + (this.delay - this._frameDiff);
  54947. this._frameIndex += this._frameSkip;
  54948. if (this._frameIndex >= this._frames.length)
  54949. {
  54950. if (this.loop)
  54951. {
  54952. // Update current state before event callback
  54953. this._frameIndex %= this._frames.length;
  54954. this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]);
  54955. // Instead of calling updateCurrentFrame we do it here instead
  54956. if (this.currentFrame)
  54957. {
  54958. this._parent.setFrame(this.currentFrame);
  54959. }
  54960. this.loopCount++;
  54961. this._parent.events.onAnimationLoop$dispatch(this._parent, this);
  54962. this.onLoop.dispatch(this._parent, this);
  54963. if (this.onUpdate)
  54964. {
  54965. this.onUpdate.dispatch(this, this.currentFrame);
  54966. // False if the animation was destroyed from within a callback
  54967. return !!this._frameData;
  54968. }
  54969. else
  54970. {
  54971. return true;
  54972. }
  54973. }
  54974. else
  54975. {
  54976. this.complete();
  54977. return false;
  54978. }
  54979. }
  54980. else
  54981. {
  54982. return this.updateCurrentFrame(true);
  54983. }
  54984. }
  54985. return false;
  54986. },
  54987. /**
  54988. * Changes the currentFrame per the _frameIndex, updates the display state,
  54989. * and triggers the update signal.
  54990. *
  54991. * Returns true if the current frame update was 'successful', false otherwise.
  54992. *
  54993. * @method Phaser.Animation#updateCurrentFrame
  54994. * @private
  54995. * @param {boolean} signalUpdate - If true the `Animation.onUpdate` signal will be dispatched.
  54996. * @param {boolean} fromPlay - Was this call made from the playing of a new animation?
  54997. * @return {boolean} True if the current frame was updated, otherwise false.
  54998. */
  54999. updateCurrentFrame: function (signalUpdate, fromPlay) {
  55000. if (fromPlay === undefined) { fromPlay = false; }
  55001. if (!this._frameData)
  55002. {
  55003. // The animation is already destroyed, probably from a callback
  55004. return false;
  55005. }
  55006. // Previous index
  55007. var idx = this.currentFrame.index;
  55008. this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]);
  55009. if (this.currentFrame && (fromPlay || (!fromPlay && idx !== this.currentFrame.index)))
  55010. {
  55011. this._parent.setFrame(this.currentFrame);
  55012. }
  55013. if (this.onUpdate && signalUpdate)
  55014. {
  55015. this.onUpdate.dispatch(this, this.currentFrame);
  55016. // False if the animation was destroyed from within a callback
  55017. return !!this._frameData;
  55018. }
  55019. else
  55020. {
  55021. return true;
  55022. }
  55023. },
  55024. /**
  55025. * Advances by the given number of frames in the Animation, taking the loop value into consideration.
  55026. *
  55027. * @method Phaser.Animation#next
  55028. * @param {number} [quantity=1] - The number of frames to advance.
  55029. */
  55030. next: function (quantity) {
  55031. if (quantity === undefined) { quantity = 1; }
  55032. var frame = this._frameIndex + quantity;
  55033. if (frame >= this._frames.length)
  55034. {
  55035. if (this.loop)
  55036. {
  55037. frame %= this._frames.length;
  55038. }
  55039. else
  55040. {
  55041. frame = this._frames.length - 1;
  55042. }
  55043. }
  55044. if (frame !== this._frameIndex)
  55045. {
  55046. this._frameIndex = frame;
  55047. this.updateCurrentFrame(true);
  55048. }
  55049. },
  55050. /**
  55051. * Moves backwards the given number of frames in the Animation, taking the loop value into consideration.
  55052. *
  55053. * @method Phaser.Animation#previous
  55054. * @param {number} [quantity=1] - The number of frames to move back.
  55055. */
  55056. previous: function (quantity) {
  55057. if (quantity === undefined) { quantity = 1; }
  55058. var frame = this._frameIndex - quantity;
  55059. if (frame < 0)
  55060. {
  55061. if (this.loop)
  55062. {
  55063. frame = this._frames.length + frame;
  55064. }
  55065. else
  55066. {
  55067. frame++;
  55068. }
  55069. }
  55070. if (frame !== this._frameIndex)
  55071. {
  55072. this._frameIndex = frame;
  55073. this.updateCurrentFrame(true);
  55074. }
  55075. },
  55076. /**
  55077. * Changes the FrameData object this Animation is using.
  55078. *
  55079. * @method Phaser.Animation#updateFrameData
  55080. * @param {Phaser.FrameData} frameData - The FrameData object that contains all frames used by this Animation.
  55081. */
  55082. updateFrameData: function (frameData) {
  55083. this._frameData = frameData;
  55084. this.currentFrame = this._frameData ? this._frameData.getFrame(this._frames[this._frameIndex % this._frames.length]) : null;
  55085. },
  55086. /**
  55087. * Cleans up this animation ready for deletion. Nulls all values and references.
  55088. *
  55089. * @method Phaser.Animation#destroy
  55090. */
  55091. destroy: function () {
  55092. if (!this._frameData)
  55093. {
  55094. // Already destroyed
  55095. return;
  55096. }
  55097. this.game.onPause.remove(this.onPause, this);
  55098. this.game.onResume.remove(this.onResume, this);
  55099. this.game = null;
  55100. this._parent = null;
  55101. this._frames = null;
  55102. this._frameData = null;
  55103. this.currentFrame = null;
  55104. this.isPlaying = false;
  55105. this.onStart.dispose();
  55106. this.onLoop.dispose();
  55107. this.onComplete.dispose();
  55108. if (this.onUpdate)
  55109. {
  55110. this.onUpdate.dispose();
  55111. }
  55112. },
  55113. /**
  55114. * Called internally when the animation finishes playback.
  55115. * Sets the isPlaying and isFinished states and dispatches the onAnimationComplete event if it exists on the parent and local onComplete event.
  55116. *
  55117. * @method Phaser.Animation#complete
  55118. */
  55119. complete: function () {
  55120. this._frameIndex = this._frames.length - 1;
  55121. this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]);
  55122. this.isPlaying = false;
  55123. this.isFinished = true;
  55124. this.paused = false;
  55125. this._parent.events.onAnimationComplete$dispatch(this._parent, this);
  55126. this.onComplete.dispatch(this._parent, this);
  55127. if (this.killOnComplete)
  55128. {
  55129. this._parent.kill();
  55130. }
  55131. }
  55132. };
  55133. Phaser.Animation.prototype.constructor = Phaser.Animation;
  55134. /**
  55135. * @name Phaser.Animation#paused
  55136. * @property {boolean} paused - Gets and sets the paused state of this Animation.
  55137. */
  55138. Object.defineProperty(Phaser.Animation.prototype, 'paused', {
  55139. get: function () {
  55140. return this.isPaused;
  55141. },
  55142. set: function (value) {
  55143. this.isPaused = value;
  55144. if (value)
  55145. {
  55146. // Paused
  55147. this._pauseStartTime = this.game.time.time;
  55148. }
  55149. else
  55150. {
  55151. // Un-paused
  55152. if (this.isPlaying)
  55153. {
  55154. this._timeNextFrame = this.game.time.time + this.delay;
  55155. }
  55156. }
  55157. }
  55158. });
  55159. /**
  55160. * @name Phaser.Animation#frameTotal
  55161. * @property {number} frameTotal - The total number of frames in the currently loaded FrameData, or -1 if no FrameData is loaded.
  55162. * @readonly
  55163. */
  55164. Object.defineProperty(Phaser.Animation.prototype, 'frameTotal', {
  55165. get: function () {
  55166. return this._frames.length;
  55167. }
  55168. });
  55169. /**
  55170. * @name Phaser.Animation#frame
  55171. * @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display.
  55172. */
  55173. Object.defineProperty(Phaser.Animation.prototype, 'frame', {
  55174. get: function () {
  55175. if (this.currentFrame !== null)
  55176. {
  55177. return this.currentFrame.index;
  55178. }
  55179. else
  55180. {
  55181. return this._frameIndex;
  55182. }
  55183. },
  55184. set: function (value) {
  55185. this.currentFrame = this._frameData.getFrame(this._frames[value]);
  55186. if (this.currentFrame !== null)
  55187. {
  55188. this._frameIndex = value;
  55189. this._parent.setFrame(this.currentFrame);
  55190. if (this.onUpdate)
  55191. {
  55192. this.onUpdate.dispatch(this, this.currentFrame);
  55193. }
  55194. }
  55195. }
  55196. });
  55197. /**
  55198. * @name Phaser.Animation#speed
  55199. * @property {number} speed - Gets or sets the current speed of the animation in frames per second. Changing this in a playing animation will take effect from the next frame. Minimum value is 1.
  55200. */
  55201. Object.defineProperty(Phaser.Animation.prototype, 'speed', {
  55202. get: function () {
  55203. return Math.round(1000 / this.delay);
  55204. },
  55205. set: function (value) {
  55206. if (value >= 1)
  55207. {
  55208. this.delay = 1000 / value;
  55209. }
  55210. }
  55211. });
  55212. /**
  55213. * @name Phaser.Animation#enableUpdate
  55214. * @property {boolean} enableUpdate - Gets or sets if this animation will dispatch the onUpdate events upon changing frame.
  55215. */
  55216. Object.defineProperty(Phaser.Animation.prototype, 'enableUpdate', {
  55217. get: function () {
  55218. return (this.onUpdate !== null);
  55219. },
  55220. set: function (value) {
  55221. if (value && this.onUpdate === null)
  55222. {
  55223. this.onUpdate = new Phaser.Signal();
  55224. }
  55225. else if (!value && this.onUpdate !== null)
  55226. {
  55227. this.onUpdate.dispose();
  55228. this.onUpdate = null;
  55229. }
  55230. }
  55231. });
  55232. /**
  55233. * Really handy function for when you are creating arrays of animation data but it's using frame names and not numbers.
  55234. * For example imagine you've got 30 frames named: 'explosion_0001-large' to 'explosion_0030-large'
  55235. * You could use this function to generate those by doing: Phaser.Animation.generateFrameNames('explosion_', 1, 30, '-large', 4);
  55236. *
  55237. * @method Phaser.Animation.generateFrameNames
  55238. * @static
  55239. * @param {string} prefix - The start of the filename. If the filename was 'explosion_0001-large' the prefix would be 'explosion_'.
  55240. * @param {number} start - The number to start sequentially counting from. If your frames are named 'explosion_0001' to 'explosion_0034' the start is 1.
  55241. * @param {number} stop - The number to count to. If your frames are named 'explosion_0001' to 'explosion_0034' the stop value is 34.
  55242. * @param {string} [suffix=''] - The end of the filename. If the filename was 'explosion_0001-large' the prefix would be '-large'.
  55243. * @param {number} [zeroPad=0] - The number of zeros to pad the min and max values with. If your frames are named 'explosion_0001' to 'explosion_0034' then the zeroPad is 4.
  55244. * @return {string[]} An array of framenames.
  55245. */
  55246. Phaser.Animation.generateFrameNames = function (prefix, start, stop, suffix, zeroPad) {
  55247. if (suffix === undefined) { suffix = ''; }
  55248. var output = [];
  55249. var frame = '';
  55250. if (start < stop)
  55251. {
  55252. for (var i = start; i <= stop; i++)
  55253. {
  55254. if (typeof zeroPad === 'number')
  55255. {
  55256. // str, len, pad, dir
  55257. frame = Phaser.Utils.pad(i.toString(), zeroPad, '0', 1);
  55258. }
  55259. else
  55260. {
  55261. frame = i.toString();
  55262. }
  55263. frame = prefix + frame + suffix;
  55264. output.push(frame);
  55265. }
  55266. }
  55267. else
  55268. {
  55269. for (var i = start; i >= stop; i--)
  55270. {
  55271. if (typeof zeroPad === 'number')
  55272. {
  55273. // str, len, pad, dir
  55274. frame = Phaser.Utils.pad(i.toString(), zeroPad, '0', 1);
  55275. }
  55276. else
  55277. {
  55278. frame = i.toString();
  55279. }
  55280. frame = prefix + frame + suffix;
  55281. output.push(frame);
  55282. }
  55283. }
  55284. return output;
  55285. };
  55286. /**
  55287. * @author Richard Davey <rich@photonstorm.com>
  55288. * @copyright 2016 Photon Storm Ltd.
  55289. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  55290. */
  55291. /**
  55292. * A Frame is a single frame of an animation and is part of a FrameData collection.
  55293. *
  55294. * @class Phaser.Frame
  55295. * @constructor
  55296. * @param {number} index - The index of this Frame within the FrameData set it is being added to.
  55297. * @param {number} x - X position of the frame within the texture image.
  55298. * @param {number} y - Y position of the frame within the texture image.
  55299. * @param {number} width - Width of the frame within the texture image.
  55300. * @param {number} height - Height of the frame within the texture image.
  55301. * @param {string} name - The name of the frame. In Texture Atlas data this is usually set to the filename.
  55302. */
  55303. Phaser.Frame = function (index, x, y, width, height, name) {
  55304. /**
  55305. * @property {number} index - The index of this Frame within the FrameData set it is being added to.
  55306. */
  55307. this.index = index;
  55308. /**
  55309. * @property {number} x - X position within the image to cut from.
  55310. */
  55311. this.x = x;
  55312. /**
  55313. * @property {number} y - Y position within the image to cut from.
  55314. */
  55315. this.y = y;
  55316. /**
  55317. * @property {number} width - Width of the frame.
  55318. */
  55319. this.width = width;
  55320. /**
  55321. * @property {number} height - Height of the frame.
  55322. */
  55323. this.height = height;
  55324. /**
  55325. * @property {string} name - Useful for Texture Atlas files (is set to the filename value).
  55326. */
  55327. this.name = name;
  55328. /**
  55329. * @property {number} centerX - Center X position within the image to cut from.
  55330. */
  55331. this.centerX = Math.floor(width / 2);
  55332. /**
  55333. * @property {number} centerY - Center Y position within the image to cut from.
  55334. */
  55335. this.centerY = Math.floor(height / 2);
  55336. /**
  55337. * @property {number} distance - The distance from the top left to the bottom-right of this Frame.
  55338. */
  55339. this.distance = Phaser.Math.distance(0, 0, width, height);
  55340. /**
  55341. * @property {boolean} rotated - Rotated? (not yet implemented)
  55342. * @default
  55343. */
  55344. this.rotated = false;
  55345. /**
  55346. * @property {string} rotationDirection - Either 'cw' or 'ccw', rotation is always 90 degrees.
  55347. * @default 'cw'
  55348. */
  55349. this.rotationDirection = 'cw';
  55350. /**
  55351. * @property {boolean} trimmed - Was it trimmed when packed?
  55352. * @default
  55353. */
  55354. this.trimmed = false;
  55355. /**
  55356. * @property {number} sourceSizeW - Width of the original sprite before it was trimmed.
  55357. */
  55358. this.sourceSizeW = width;
  55359. /**
  55360. * @property {number} sourceSizeH - Height of the original sprite before it was trimmed.
  55361. */
  55362. this.sourceSizeH = height;
  55363. /**
  55364. * @property {number} spriteSourceSizeX - X position of the trimmed sprite inside original sprite.
  55365. * @default
  55366. */
  55367. this.spriteSourceSizeX = 0;
  55368. /**
  55369. * @property {number} spriteSourceSizeY - Y position of the trimmed sprite inside original sprite.
  55370. * @default
  55371. */
  55372. this.spriteSourceSizeY = 0;
  55373. /**
  55374. * @property {number} spriteSourceSizeW - Width of the trimmed sprite.
  55375. * @default
  55376. */
  55377. this.spriteSourceSizeW = 0;
  55378. /**
  55379. * @property {number} spriteSourceSizeH - Height of the trimmed sprite.
  55380. * @default
  55381. */
  55382. this.spriteSourceSizeH = 0;
  55383. /**
  55384. * @property {number} right - The right of the Frame (x + width).
  55385. */
  55386. this.right = this.x + this.width;
  55387. /**
  55388. * @property {number} bottom - The bottom of the frame (y + height).
  55389. */
  55390. this.bottom = this.y + this.height;
  55391. };
  55392. Phaser.Frame.prototype = {
  55393. /**
  55394. * Adjusts of all the Frame properties based on the given width and height values.
  55395. *
  55396. * @method Phaser.Frame#resize
  55397. * @param {integer} width - The new width of the Frame.
  55398. * @param {integer} height - The new height of the Frame.
  55399. */
  55400. resize: function (width, height) {
  55401. this.width = width;
  55402. this.height = height;
  55403. this.centerX = Math.floor(width / 2);
  55404. this.centerY = Math.floor(height / 2);
  55405. this.distance = Phaser.Math.distance(0, 0, width, height);
  55406. this.sourceSizeW = width;
  55407. this.sourceSizeH = height;
  55408. this.right = this.x + width;
  55409. this.bottom = this.y + height;
  55410. },
  55411. /**
  55412. * If the frame was trimmed when added to the Texture Atlas this records the trim and source data.
  55413. *
  55414. * @method Phaser.Frame#setTrim
  55415. * @param {boolean} trimmed - If this frame was trimmed or not.
  55416. * @param {number} actualWidth - The width of the frame before being trimmed.
  55417. * @param {number} actualHeight - The height of the frame before being trimmed.
  55418. * @param {number} destX - The destination X position of the trimmed frame for display.
  55419. * @param {number} destY - The destination Y position of the trimmed frame for display.
  55420. * @param {number} destWidth - The destination width of the trimmed frame for display.
  55421. * @param {number} destHeight - The destination height of the trimmed frame for display.
  55422. */
  55423. setTrim: function (trimmed, actualWidth, actualHeight, destX, destY, destWidth, destHeight) {
  55424. this.trimmed = trimmed;
  55425. if (trimmed)
  55426. {
  55427. this.sourceSizeW = actualWidth;
  55428. this.sourceSizeH = actualHeight;
  55429. this.centerX = Math.floor(actualWidth / 2);
  55430. this.centerY = Math.floor(actualHeight / 2);
  55431. this.spriteSourceSizeX = destX;
  55432. this.spriteSourceSizeY = destY;
  55433. this.spriteSourceSizeW = destWidth;
  55434. this.spriteSourceSizeH = destHeight;
  55435. }
  55436. },
  55437. /**
  55438. * Clones this Frame into a new Phaser.Frame object and returns it.
  55439. * Note that all properties are cloned, including the name, index and UUID.
  55440. *
  55441. * @method Phaser.Frame#clone
  55442. * @return {Phaser.Frame} An exact copy of this Frame object.
  55443. */
  55444. clone: function () {
  55445. var output = new Phaser.Frame(this.index, this.x, this.y, this.width, this.height, this.name);
  55446. for (var prop in this)
  55447. {
  55448. if (this.hasOwnProperty(prop))
  55449. {
  55450. output[prop] = this[prop];
  55451. }
  55452. }
  55453. return output;
  55454. },
  55455. /**
  55456. * Returns a Rectangle set to the dimensions of this Frame.
  55457. *
  55458. * @method Phaser.Frame#getRect
  55459. * @param {Phaser.Rectangle} [out] - A rectangle to copy the frame dimensions to.
  55460. * @return {Phaser.Rectangle} A rectangle.
  55461. */
  55462. getRect: function (out) {
  55463. if (out === undefined)
  55464. {
  55465. out = new Phaser.Rectangle(this.x, this.y, this.width, this.height);
  55466. }
  55467. else
  55468. {
  55469. out.setTo(this.x, this.y, this.width, this.height);
  55470. }
  55471. return out;
  55472. }
  55473. };
  55474. Phaser.Frame.prototype.constructor = Phaser.Frame;
  55475. /**
  55476. * @author Richard Davey <rich@photonstorm.com>
  55477. * @copyright 2016 Photon Storm Ltd.
  55478. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  55479. */
  55480. /**
  55481. * FrameData is a container for Frame objects, which are the internal representation of animation data in Phaser.
  55482. *
  55483. * @class Phaser.FrameData
  55484. * @constructor
  55485. */
  55486. Phaser.FrameData = function () {
  55487. /**
  55488. * @property {Array} _frames - Local array of frames.
  55489. * @private
  55490. */
  55491. this._frames = [];
  55492. /**
  55493. * @property {Array} _frameNames - Local array of frame names for name to index conversions.
  55494. * @private
  55495. */
  55496. this._frameNames = [];
  55497. };
  55498. Phaser.FrameData.prototype = {
  55499. /**
  55500. * Adds a new Frame to this FrameData collection. Typically called by the Animation.Parser and not directly.
  55501. *
  55502. * @method Phaser.FrameData#addFrame
  55503. * @param {Phaser.Frame} frame - The frame to add to this FrameData set.
  55504. * @return {Phaser.Frame} The frame that was just added.
  55505. */
  55506. addFrame: function (frame) {
  55507. frame.index = this._frames.length;
  55508. this._frames.push(frame);
  55509. if (frame.name !== '')
  55510. {
  55511. this._frameNames[frame.name] = frame.index;
  55512. }
  55513. return frame;
  55514. },
  55515. /**
  55516. * Get a Frame by its numerical index.
  55517. *
  55518. * @method Phaser.FrameData#getFrame
  55519. * @param {number} index - The index of the frame you want to get.
  55520. * @return {Phaser.Frame} The frame, if found.
  55521. */
  55522. getFrame: function (index) {
  55523. if (index >= this._frames.length)
  55524. {
  55525. index = 0;
  55526. }
  55527. return this._frames[index];
  55528. },
  55529. /**
  55530. * Get a Frame by its frame name.
  55531. *
  55532. * @method Phaser.FrameData#getFrameByName
  55533. * @param {string} name - The name of the frame you want to get.
  55534. * @return {Phaser.Frame} The frame, if found.
  55535. */
  55536. getFrameByName: function (name) {
  55537. if (typeof this._frameNames[name] === 'number')
  55538. {
  55539. return this._frames[this._frameNames[name]];
  55540. }
  55541. return null;
  55542. },
  55543. /**
  55544. * Check if there is a Frame with the given name.
  55545. *
  55546. * @method Phaser.FrameData#checkFrameName
  55547. * @param {string} name - The name of the frame you want to check.
  55548. * @return {boolean} True if the frame is found, otherwise false.
  55549. */
  55550. checkFrameName: function (name) {
  55551. if (this._frameNames[name] == null)
  55552. {
  55553. return false;
  55554. }
  55555. return true;
  55556. },
  55557. /**
  55558. * Makes a copy of this FrameData including copies (not references) to all of the Frames it contains.
  55559. *
  55560. * @method Phaser.FrameData#clone
  55561. * @return {Phaser.FrameData} A clone of this object, including clones of the Frame objects it contains.
  55562. */
  55563. clone: function () {
  55564. var output = new Phaser.FrameData();
  55565. // No input array, so we loop through all frames
  55566. for (var i = 0; i < this._frames.length; i++)
  55567. {
  55568. output._frames.push(this._frames[i].clone());
  55569. }
  55570. for (var p in this._frameNames)
  55571. {
  55572. if (this._frameNames.hasOwnProperty(p))
  55573. {
  55574. output._frameNames.push(this._frameNames[p]);
  55575. }
  55576. }
  55577. return output;
  55578. },
  55579. /**
  55580. * Returns a range of frames based on the given start and end frame indexes and returns them in an Array.
  55581. *
  55582. * @method Phaser.FrameData#getFrameRange
  55583. * @param {number} start - The starting frame index.
  55584. * @param {number} end - The ending frame index.
  55585. * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created.
  55586. * @return {Array} An array of Frames between the start and end index values, or an empty array if none were found.
  55587. */
  55588. getFrameRange: function (start, end, output) {
  55589. if (output === undefined) { output = []; }
  55590. for (var i = start; i <= end; i++)
  55591. {
  55592. output.push(this._frames[i]);
  55593. }
  55594. return output;
  55595. },
  55596. /**
  55597. * Returns all of the Frames in this FrameData set where the frame index is found in the input array.
  55598. * The frames are returned in the output array, or if none is provided in a new Array object.
  55599. *
  55600. * @method Phaser.FrameData#getFrames
  55601. * @param {Array} [frames] - An Array containing the indexes of the frames to retrieve. If the array is empty or undefined then all frames in the FrameData are returned.
  55602. * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? (false)
  55603. * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created.
  55604. * @return {Array} An array of all Frames in this FrameData set matching the given names or IDs.
  55605. */
  55606. getFrames: function (frames, useNumericIndex, output) {
  55607. if (useNumericIndex === undefined) { useNumericIndex = true; }
  55608. if (output === undefined) { output = []; }
  55609. if (frames === undefined || frames.length === 0)
  55610. {
  55611. // No input array, so we loop through all frames
  55612. for (var i = 0; i < this._frames.length; i++)
  55613. {
  55614. // We only need the indexes
  55615. output.push(this._frames[i]);
  55616. }
  55617. }
  55618. else
  55619. {
  55620. // Input array given, loop through that instead
  55621. for (var i = 0; i < frames.length; i++)
  55622. {
  55623. // Does the input array contain names or indexes?
  55624. if (useNumericIndex)
  55625. {
  55626. // The actual frame
  55627. output.push(this.getFrame(frames[i]));
  55628. }
  55629. else
  55630. {
  55631. // The actual frame
  55632. output.push(this.getFrameByName(frames[i]));
  55633. }
  55634. }
  55635. }
  55636. return output;
  55637. },
  55638. /**
  55639. * Returns all of the Frame indexes in this FrameData set.
  55640. * The frames indexes are returned in the output array, or if none is provided in a new Array object.
  55641. *
  55642. * @method Phaser.FrameData#getFrameIndexes
  55643. * @param {Array} [frames] - An Array containing the indexes of the frames to retrieve. If undefined or the array is empty then all frames in the FrameData are returned.
  55644. * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? (false)
  55645. * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created.
  55646. * @return {Array} An array of all Frame indexes matching the given names or IDs.
  55647. */
  55648. getFrameIndexes: function (frames, useNumericIndex, output) {
  55649. if (useNumericIndex === undefined) { useNumericIndex = true; }
  55650. if (output === undefined) { output = []; }
  55651. if (frames === undefined || frames.length === 0)
  55652. {
  55653. // No frames array, so we loop through all frames
  55654. for (var i = 0; i < this._frames.length; i++)
  55655. {
  55656. output.push(this._frames[i].index);
  55657. }
  55658. }
  55659. else
  55660. {
  55661. // Input array given, loop through that instead
  55662. for (var i = 0; i < frames.length; i++)
  55663. {
  55664. // Does the frames array contain names or indexes?
  55665. if (useNumericIndex && this._frames[frames[i]])
  55666. {
  55667. output.push(this._frames[frames[i]].index);
  55668. }
  55669. else
  55670. {
  55671. if (this.getFrameByName(frames[i]))
  55672. {
  55673. output.push(this.getFrameByName(frames[i]).index);
  55674. }
  55675. }
  55676. }
  55677. }
  55678. return output;
  55679. },
  55680. /**
  55681. * Destroys this FrameData collection by nulling the _frames and _frameNames arrays.
  55682. *
  55683. * @method Phaser.FrameData#destroy
  55684. */
  55685. destroy: function () {
  55686. this._frames = null;
  55687. this._frameNames = null;
  55688. }
  55689. };
  55690. Phaser.FrameData.prototype.constructor = Phaser.FrameData;
  55691. /**
  55692. * @name Phaser.FrameData#total
  55693. * @property {number} total - The total number of frames in this FrameData set.
  55694. * @readonly
  55695. */
  55696. Object.defineProperty(Phaser.FrameData.prototype, "total", {
  55697. get: function () {
  55698. return this._frames.length;
  55699. }
  55700. });
  55701. /**
  55702. * @author Richard Davey <rich@photonstorm.com>
  55703. * @copyright 2016 Photon Storm Ltd.
  55704. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  55705. */
  55706. /**
  55707. * Responsible for parsing sprite sheet and JSON data into the internal FrameData format that Phaser uses for animations.
  55708. *
  55709. * @class Phaser.AnimationParser
  55710. * @static
  55711. */
  55712. Phaser.AnimationParser = {
  55713. /**
  55714. * Parse a Sprite Sheet and extract the animation frame data from it.
  55715. *
  55716. * @method Phaser.AnimationParser.spriteSheet
  55717. * @param {Phaser.Game} game - A reference to the currently running game.
  55718. * @param {string|Image} key - The Game.Cache asset key of the Sprite Sheet image or an actual HTML Image element.
  55719. * @param {number} frameWidth - The fixed width of each frame of the animation.
  55720. * @param {number} frameHeight - The fixed height of each frame of the animation.
  55721. * @param {number} [frameMax=-1] - The total number of animation frames to extract from the Sprite Sheet. The default value of -1 means "extract all frames".
  55722. * @param {number} [margin=0] - If the frames have been drawn with a margin, specify the amount here.
  55723. * @param {number} [spacing=0] - If the frames have been drawn with spacing between them, specify the amount here.
  55724. * @return {Phaser.FrameData} A FrameData object containing the parsed frames.
  55725. */
  55726. spriteSheet: function (game, key, frameWidth, frameHeight, frameMax, margin, spacing) {
  55727. var img = key;
  55728. if (typeof key === 'string')
  55729. {
  55730. img = game.cache.getImage(key);
  55731. }
  55732. if (img === null)
  55733. {
  55734. return null;
  55735. }
  55736. var width = img.width;
  55737. var height = img.height;
  55738. if (frameWidth <= 0)
  55739. {
  55740. frameWidth = Math.floor(-width / Math.min(-1, frameWidth));
  55741. }
  55742. if (frameHeight <= 0)
  55743. {
  55744. frameHeight = Math.floor(-height / Math.min(-1, frameHeight));
  55745. }
  55746. var row = Math.floor((width - margin) / (frameWidth + spacing));
  55747. var column = Math.floor((height - margin) / (frameHeight + spacing));
  55748. var total = row * column;
  55749. if (frameMax !== -1)
  55750. {
  55751. total = frameMax;
  55752. }
  55753. // Zero or smaller than frame sizes?
  55754. if (width === 0 || height === 0 || width < frameWidth || height < frameHeight || total === 0)
  55755. {
  55756. console.warn("Phaser.AnimationParser.spriteSheet: '" + key + "'s width/height zero or width/height < given frameWidth/frameHeight");
  55757. return null;
  55758. }
  55759. // Let's create some frames then
  55760. var data = new Phaser.FrameData();
  55761. var x = margin;
  55762. var y = margin;
  55763. for (var i = 0; i < total; i++)
  55764. {
  55765. data.addFrame(new Phaser.Frame(i, x, y, frameWidth, frameHeight, ''));
  55766. x += frameWidth + spacing;
  55767. if (x + frameWidth > width)
  55768. {
  55769. x = margin;
  55770. y += frameHeight + spacing;
  55771. }
  55772. }
  55773. return data;
  55774. },
  55775. /**
  55776. * Parse the JSON data and extract the animation frame data from it.
  55777. *
  55778. * @method Phaser.AnimationParser.JSONData
  55779. * @param {Phaser.Game} game - A reference to the currently running game.
  55780. * @param {object} json - The JSON data from the Texture Atlas. Must be in Array format.
  55781. * @return {Phaser.FrameData} A FrameData object containing the parsed frames.
  55782. */
  55783. JSONData: function (game, json) {
  55784. // Malformed?
  55785. if (!json['frames'])
  55786. {
  55787. console.warn("Phaser.AnimationParser.JSONData: Invalid Texture Atlas JSON given, missing 'frames' array");
  55788. console.log(json);
  55789. return;
  55790. }
  55791. // Let's create some frames then
  55792. var data = new Phaser.FrameData();
  55793. // By this stage frames is a fully parsed array
  55794. var frames = json['frames'];
  55795. var newFrame;
  55796. for (var i = 0; i < frames.length; i++)
  55797. {
  55798. newFrame = data.addFrame(new Phaser.Frame(
  55799. i,
  55800. frames[i].frame.x,
  55801. frames[i].frame.y,
  55802. frames[i].frame.w,
  55803. frames[i].frame.h,
  55804. frames[i].filename
  55805. ));
  55806. if (frames[i].trimmed)
  55807. {
  55808. newFrame.setTrim(
  55809. frames[i].trimmed,
  55810. frames[i].sourceSize.w,
  55811. frames[i].sourceSize.h,
  55812. frames[i].spriteSourceSize.x,
  55813. frames[i].spriteSourceSize.y,
  55814. frames[i].spriteSourceSize.w,
  55815. frames[i].spriteSourceSize.h
  55816. );
  55817. }
  55818. }
  55819. return data;
  55820. },
  55821. /**
  55822. * Parse the JSON data and extract the animation frame data from it.
  55823. *
  55824. * @method Phaser.AnimationParser.JSONDataPyxel
  55825. * @param {Phaser.Game} game - A reference to the currently running game.
  55826. * @param {object} json - The JSON data from the Texture Atlas. Must be in Pyxel JSON format.
  55827. * @return {Phaser.FrameData} A FrameData object containing the parsed frames.
  55828. */
  55829. JSONDataPyxel: function (game, json) {
  55830. // Malformed? There are a few keys to check here.
  55831. var signature = ['layers', 'tilewidth','tileheight','tileswide', 'tileshigh'];
  55832. signature.forEach( function(key) {
  55833. if (!json[key])
  55834. {
  55835. console.warn("Phaser.AnimationParser.JSONDataPyxel: Invalid Pyxel Tilemap JSON given, missing '" + key + "' key.");
  55836. console.log(json);
  55837. return;
  55838. }
  55839. });
  55840. // For this purpose, I only care about parsing tilemaps with a single layer.
  55841. if(json['layers'].length != 1) {
  55842. console.warn("Phaser.AnimationParser.JSONDataPyxel: Too many layers, this parser only supports flat Tilemaps.");
  55843. console.log(json);
  55844. return;
  55845. }
  55846. var data = new Phaser.FrameData();
  55847. var tileheight = json['tileheight'];
  55848. var tilewidth = json['tilewidth'];
  55849. var frames = json['layers'][0]['tiles'];
  55850. var newFrame;
  55851. for (var i = 0; i < frames.length; i++)
  55852. {
  55853. newFrame = data.addFrame(new Phaser.Frame(
  55854. i,
  55855. frames[i].x,
  55856. frames[i].y,
  55857. tilewidth,
  55858. tileheight,
  55859. "frame_" + i // No names are included in pyxel tilemap data.
  55860. ));
  55861. // No trim data is included.
  55862. newFrame.setTrim(false);
  55863. }
  55864. return data;
  55865. },
  55866. /**
  55867. * Parse the JSON data and extract the animation frame data from it.
  55868. *
  55869. * @method Phaser.AnimationParser.JSONDataHash
  55870. * @param {Phaser.Game} game - A reference to the currently running game.
  55871. * @param {object} json - The JSON data from the Texture Atlas. Must be in JSON Hash format.
  55872. * @return {Phaser.FrameData} A FrameData object containing the parsed frames.
  55873. */
  55874. JSONDataHash: function (game, json) {
  55875. // Malformed?
  55876. if (!json['frames'])
  55877. {
  55878. console.warn("Phaser.AnimationParser.JSONDataHash: Invalid Texture Atlas JSON given, missing 'frames' object");
  55879. console.log(json);
  55880. return;
  55881. }
  55882. // Let's create some frames then
  55883. var data = new Phaser.FrameData();
  55884. // By this stage frames is a fully parsed array
  55885. var frames = json['frames'];
  55886. var newFrame;
  55887. var i = 0;
  55888. for (var key in frames)
  55889. {
  55890. newFrame = data.addFrame(new Phaser.Frame(
  55891. i,
  55892. frames[key].frame.x,
  55893. frames[key].frame.y,
  55894. frames[key].frame.w,
  55895. frames[key].frame.h,
  55896. key
  55897. ));
  55898. if (frames[key].trimmed)
  55899. {
  55900. newFrame.setTrim(
  55901. frames[key].trimmed,
  55902. frames[key].sourceSize.w,
  55903. frames[key].sourceSize.h,
  55904. frames[key].spriteSourceSize.x,
  55905. frames[key].spriteSourceSize.y,
  55906. frames[key].spriteSourceSize.w,
  55907. frames[key].spriteSourceSize.h
  55908. );
  55909. }
  55910. i++;
  55911. }
  55912. return data;
  55913. },
  55914. /**
  55915. * Parse the XML data and extract the animation frame data from it.
  55916. *
  55917. * @method Phaser.AnimationParser.XMLData
  55918. * @param {Phaser.Game} game - A reference to the currently running game.
  55919. * @param {object} xml - The XML data from the Texture Atlas. Must be in Starling XML format.
  55920. * @return {Phaser.FrameData} A FrameData object containing the parsed frames.
  55921. */
  55922. XMLData: function (game, xml) {
  55923. // Malformed?
  55924. if (!xml.getElementsByTagName('TextureAtlas'))
  55925. {
  55926. console.warn("Phaser.AnimationParser.XMLData: Invalid Texture Atlas XML given, missing <TextureAtlas> tag");
  55927. return;
  55928. }
  55929. // Let's create some frames then
  55930. var data = new Phaser.FrameData();
  55931. var frames = xml.getElementsByTagName('SubTexture');
  55932. var newFrame;
  55933. var name;
  55934. var frame;
  55935. var x;
  55936. var y;
  55937. var width;
  55938. var height;
  55939. var frameX;
  55940. var frameY;
  55941. var frameWidth;
  55942. var frameHeight;
  55943. for (var i = 0; i < frames.length; i++)
  55944. {
  55945. frame = frames[i].attributes;
  55946. name = frame.name.value;
  55947. x = parseInt(frame.x.value, 10);
  55948. y = parseInt(frame.y.value, 10);
  55949. width = parseInt(frame.width.value, 10);
  55950. height = parseInt(frame.height.value, 10);
  55951. frameX = null;
  55952. frameY = null;
  55953. if (frame.frameX)
  55954. {
  55955. frameX = Math.abs(parseInt(frame.frameX.value, 10));
  55956. frameY = Math.abs(parseInt(frame.frameY.value, 10));
  55957. frameWidth = parseInt(frame.frameWidth.value, 10);
  55958. frameHeight = parseInt(frame.frameHeight.value, 10);
  55959. }
  55960. newFrame = data.addFrame(new Phaser.Frame(i, x, y, width, height, name));
  55961. // Trimmed?
  55962. if (frameX !== null || frameY !== null)
  55963. {
  55964. newFrame.setTrim(true, width, height, frameX, frameY, frameWidth, frameHeight);
  55965. }
  55966. }
  55967. return data;
  55968. }
  55969. };
  55970. /**
  55971. * @author Richard Davey <rich@photonstorm.com>
  55972. * @copyright 2016 Photon Storm Ltd.
  55973. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  55974. */
  55975. /**
  55976. * Phaser has one single cache in which it stores all assets.
  55977. *
  55978. * The cache is split up into sections, such as images, sounds, video, json, etc. All assets are stored using
  55979. * a unique string-based key as their identifier. Assets stored in different areas of the cache can have the
  55980. * same key, for example 'playerWalking' could be used as the key for both a sprite sheet and an audio file,
  55981. * because they are unique data types.
  55982. *
  55983. * The cache is automatically populated by the Phaser.Loader. When you use the loader to pull in external assets
  55984. * such as images they are automatically placed into their respective cache. Most common Game Objects, such as
  55985. * Sprites and Videos automatically query the cache to extract the assets they need on instantiation.
  55986. *
  55987. * You can access the cache from within a State via `this.cache`. From here you can call any public method it has,
  55988. * including adding new entries to it, deleting them or querying them.
  55989. *
  55990. * Understand that almost without exception when you get an item from the cache it will return a reference to the
  55991. * item stored in the cache, not a copy of it. Therefore if you retrieve an item and then modify it, the original
  55992. * object in the cache will also be updated, even if you don't put it back into the cache again.
  55993. *
  55994. * By default when you change State the cache is _not_ cleared, although there is an option to clear it should
  55995. * your game require it. In a typical game set-up the cache is populated once after the main game has loaded and
  55996. * then used as an asset store.
  55997. *
  55998. * @class Phaser.Cache
  55999. * @constructor
  56000. * @param {Phaser.Game} game - A reference to the currently running game.
  56001. */
  56002. Phaser.Cache = function (game) {
  56003. /**
  56004. * @property {Phaser.Game} game - Local reference to game.
  56005. */
  56006. this.game = game;
  56007. /**
  56008. * Automatically resolve resource URLs to absolute paths for use with the Cache.getURL method.
  56009. * @property {boolean} autoResolveURL
  56010. */
  56011. this.autoResolveURL = false;
  56012. /**
  56013. * The main cache object into which all resources are placed.
  56014. * @property {object} _cache
  56015. * @private
  56016. */
  56017. this._cache = {
  56018. canvas: {},
  56019. image: {},
  56020. texture: {},
  56021. sound: {},
  56022. video: {},
  56023. text: {},
  56024. json: {},
  56025. xml: {},
  56026. physics: {},
  56027. tilemap: {},
  56028. binary: {},
  56029. bitmapData: {},
  56030. bitmapFont: {},
  56031. shader: {},
  56032. renderTexture: {}
  56033. };
  56034. /**
  56035. * @property {object} _urlMap - Maps URLs to resources.
  56036. * @private
  56037. */
  56038. this._urlMap = {};
  56039. /**
  56040. * @property {Image} _urlResolver - Used to resolve URLs to the absolute path.
  56041. * @private
  56042. */
  56043. this._urlResolver = new Image();
  56044. /**
  56045. * @property {string} _urlTemp - Temporary variable to hold a resolved url.
  56046. * @private
  56047. */
  56048. this._urlTemp = null;
  56049. /**
  56050. * @property {Phaser.Signal} onSoundUnlock - This event is dispatched when the sound system is unlocked via a touch event on cellular devices.
  56051. */
  56052. this.onSoundUnlock = new Phaser.Signal();
  56053. /**
  56054. * @property {array} _cacheMap - Const to cache object look-up array.
  56055. * @private
  56056. */
  56057. this._cacheMap = [];
  56058. this._cacheMap[Phaser.Cache.CANVAS] = this._cache.canvas;
  56059. this._cacheMap[Phaser.Cache.IMAGE] = this._cache.image;
  56060. this._cacheMap[Phaser.Cache.TEXTURE] = this._cache.texture;
  56061. this._cacheMap[Phaser.Cache.SOUND] = this._cache.sound;
  56062. this._cacheMap[Phaser.Cache.TEXT] = this._cache.text;
  56063. this._cacheMap[Phaser.Cache.PHYSICS] = this._cache.physics;
  56064. this._cacheMap[Phaser.Cache.TILEMAP] = this._cache.tilemap;
  56065. this._cacheMap[Phaser.Cache.BINARY] = this._cache.binary;
  56066. this._cacheMap[Phaser.Cache.BITMAPDATA] = this._cache.bitmapData;
  56067. this._cacheMap[Phaser.Cache.BITMAPFONT] = this._cache.bitmapFont;
  56068. this._cacheMap[Phaser.Cache.JSON] = this._cache.json;
  56069. this._cacheMap[Phaser.Cache.XML] = this._cache.xml;
  56070. this._cacheMap[Phaser.Cache.VIDEO] = this._cache.video;
  56071. this._cacheMap[Phaser.Cache.SHADER] = this._cache.shader;
  56072. this._cacheMap[Phaser.Cache.RENDER_TEXTURE] = this._cache.renderTexture;
  56073. this.addDefaultImage();
  56074. this.addMissingImage();
  56075. };
  56076. /**
  56077. * @constant
  56078. * @type {number}
  56079. */
  56080. Phaser.Cache.CANVAS = 1;
  56081. /**
  56082. * @constant
  56083. * @type {number}
  56084. */
  56085. Phaser.Cache.IMAGE = 2;
  56086. /**
  56087. * @constant
  56088. * @type {number}
  56089. */
  56090. Phaser.Cache.TEXTURE = 3;
  56091. /**
  56092. * @constant
  56093. * @type {number}
  56094. */
  56095. Phaser.Cache.SOUND = 4;
  56096. /**
  56097. * @constant
  56098. * @type {number}
  56099. */
  56100. Phaser.Cache.TEXT = 5;
  56101. /**
  56102. * @constant
  56103. * @type {number}
  56104. */
  56105. Phaser.Cache.PHYSICS = 6;
  56106. /**
  56107. * @constant
  56108. * @type {number}
  56109. */
  56110. Phaser.Cache.TILEMAP = 7;
  56111. /**
  56112. * @constant
  56113. * @type {number}
  56114. */
  56115. Phaser.Cache.BINARY = 8;
  56116. /**
  56117. * @constant
  56118. * @type {number}
  56119. */
  56120. Phaser.Cache.BITMAPDATA = 9;
  56121. /**
  56122. * @constant
  56123. * @type {number}
  56124. */
  56125. Phaser.Cache.BITMAPFONT = 10;
  56126. /**
  56127. * @constant
  56128. * @type {number}
  56129. */
  56130. Phaser.Cache.JSON = 11;
  56131. /**
  56132. * @constant
  56133. * @type {number}
  56134. */
  56135. Phaser.Cache.XML = 12;
  56136. /**
  56137. * @constant
  56138. * @type {number}
  56139. */
  56140. Phaser.Cache.VIDEO = 13;
  56141. /**
  56142. * @constant
  56143. * @type {number}
  56144. */
  56145. Phaser.Cache.SHADER = 14;
  56146. /**
  56147. * @constant
  56148. * @type {number}
  56149. */
  56150. Phaser.Cache.RENDER_TEXTURE = 15;
  56151. Phaser.Cache.prototype = {
  56152. //////////////////
  56153. // Add Methods //
  56154. //////////////////
  56155. /**
  56156. * Add a new canvas object in to the cache.
  56157. *
  56158. * @method Phaser.Cache#addCanvas
  56159. * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
  56160. * @param {HTMLCanvasElement} canvas - The Canvas DOM element.
  56161. * @param {CanvasRenderingContext2D} [context] - The context of the canvas element. If not specified it will default go `getContext('2d')`.
  56162. */
  56163. addCanvas: function (key, canvas, context) {
  56164. if (context === undefined) { context = canvas.getContext('2d'); }
  56165. this._cache.canvas[key] = { canvas: canvas, context: context };
  56166. },
  56167. /**
  56168. * Adds an Image file into the Cache. The file must have already been loaded, typically via Phaser.Loader, but can also have been loaded into the DOM.
  56169. * If an image already exists in the cache with the same key then it is removed and destroyed, and the new image inserted in its place.
  56170. *
  56171. * @method Phaser.Cache#addImage
  56172. * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
  56173. * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`.
  56174. * @param {object} data - Extra image data.
  56175. * @return {object} The full image object that was added to the cache.
  56176. */
  56177. addImage: function (key, url, data) {
  56178. if (this.checkImageKey(key))
  56179. {
  56180. this.removeImage(key);
  56181. }
  56182. var img = {
  56183. key: key,
  56184. url: url,
  56185. data: data,
  56186. base: new PIXI.BaseTexture(data),
  56187. frame: new Phaser.Frame(0, 0, 0, data.width, data.height, key),
  56188. frameData: new Phaser.FrameData()
  56189. };
  56190. img.frameData.addFrame(new Phaser.Frame(0, 0, 0, data.width, data.height, url));
  56191. this._cache.image[key] = img;
  56192. this._resolveURL(url, img);
  56193. return img;
  56194. },
  56195. /**
  56196. * Adds a default image to be used in special cases such as WebGL Filters.
  56197. * It uses the special reserved key of `__default`.
  56198. * This method is called automatically when the Cache is created.
  56199. * This image is skipped when `Cache.destroy` is called due to its internal requirements.
  56200. *
  56201. * @method Phaser.Cache#addDefaultImage
  56202. * @protected
  56203. */
  56204. addDefaultImage: function () {
  56205. var img = new Image();
  56206. img.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgAQMAAABJtOi3AAAAA1BMVEX///+nxBvIAAAAAXRSTlMAQObYZgAAABVJREFUeF7NwIEAAAAAgKD9qdeocAMAoAABm3DkcAAAAABJRU5ErkJggg==";
  56207. var obj = this.addImage('__default', null, img);
  56208. // Because we don't want to invalidate the sprite batch for an invisible texture
  56209. obj.base.skipRender = true;
  56210. PIXI.TextureCache['__default'] = new PIXI.Texture(obj.base);
  56211. },
  56212. /**
  56213. * Adds an image to be used when a key is wrong / missing.
  56214. * It uses the special reserved key of `__missing`.
  56215. * This method is called automatically when the Cache is created.
  56216. * This image is skipped when `Cache.destroy` is called due to its internal requirements.
  56217. *
  56218. * @method Phaser.Cache#addMissingImage
  56219. * @protected
  56220. */
  56221. addMissingImage: function () {
  56222. var img = new Image();
  56223. img.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJ9JREFUeNq01ssOwyAMRFG46v//Mt1ESmgh+DFmE2GPOBARKb2NVjo+17PXLD8a1+pl5+A+wSgFygymWYHBb0FtsKhJDdZlncG2IzJ4ayoMDv20wTmSMzClEgbWYNTAkQ0Z+OJ+A/eWnAaR9+oxCF4Os0H8htsMUp+pwcgBBiMNnAwF8GqIgL2hAzaGFFgZauDPKABmowZ4GL369/0rwACp2yA/ttmvsQAAAABJRU5ErkJggg==";
  56224. var obj = this.addImage('__missing', null, img);
  56225. PIXI.TextureCache['__missing'] = new PIXI.Texture(obj.base);
  56226. },
  56227. /**
  56228. * Adds a Sound file into the Cache. The file must have already been loaded, typically via Phaser.Loader.
  56229. *
  56230. * @method Phaser.Cache#addSound
  56231. * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
  56232. * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`.
  56233. * @param {object} data - Extra sound data.
  56234. * @param {boolean} webAudio - True if the file is using web audio.
  56235. * @param {boolean} audioTag - True if the file is using legacy HTML audio.
  56236. */
  56237. addSound: function (key, url, data, webAudio, audioTag) {
  56238. if (webAudio === undefined) { webAudio = true; audioTag = false; }
  56239. if (audioTag === undefined) { webAudio = false; audioTag = true; }
  56240. var decoded = false;
  56241. if (audioTag)
  56242. {
  56243. decoded = true;
  56244. }
  56245. this._cache.sound[key] = {
  56246. url: url,
  56247. data: data,
  56248. isDecoding: false,
  56249. decoded: decoded,
  56250. webAudio: webAudio,
  56251. audioTag: audioTag,
  56252. locked: this.game.sound.touchLocked
  56253. };
  56254. this._resolveURL(url, this._cache.sound[key]);
  56255. },
  56256. /**
  56257. * Add a new text data.
  56258. *
  56259. * @method Phaser.Cache#addText
  56260. * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
  56261. * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`.
  56262. * @param {object} data - Extra text data.
  56263. */
  56264. addText: function (key, url, data) {
  56265. this._cache.text[key] = { url: url, data: data };
  56266. this._resolveURL(url, this._cache.text[key]);
  56267. },
  56268. /**
  56269. * Add a new physics data object to the Cache.
  56270. *
  56271. * @method Phaser.Cache#addPhysicsData
  56272. * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
  56273. * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`.
  56274. * @param {object} JSONData - The physics data object (a JSON file).
  56275. * @param {number} format - The format of the physics data.
  56276. */
  56277. addPhysicsData: function (key, url, JSONData, format) {
  56278. this._cache.physics[key] = { url: url, data: JSONData, format: format };
  56279. this._resolveURL(url, this._cache.physics[key]);
  56280. },
  56281. /**
  56282. * Add a new tilemap to the Cache.
  56283. *
  56284. * @method Phaser.Cache#addTilemap
  56285. * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
  56286. * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`.
  56287. * @param {object} mapData - The tilemap data object (either a CSV or JSON file).
  56288. * @param {number} format - The format of the tilemap data.
  56289. */
  56290. addTilemap: function (key, url, mapData, format) {
  56291. this._cache.tilemap[key] = { url: url, data: mapData, format: format };
  56292. this._resolveURL(url, this._cache.tilemap[key]);
  56293. },
  56294. /**
  56295. * Add a binary object in to the cache.
  56296. *
  56297. * @method Phaser.Cache#addBinary
  56298. * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
  56299. * @param {object} binaryData - The binary object to be added to the cache.
  56300. */
  56301. addBinary: function (key, binaryData) {
  56302. this._cache.binary[key] = binaryData;
  56303. },
  56304. /**
  56305. * Add a BitmapData object to the cache.
  56306. *
  56307. * @method Phaser.Cache#addBitmapData
  56308. * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
  56309. * @param {Phaser.BitmapData} bitmapData - The BitmapData object to be addded to the cache.
  56310. * @param {Phaser.FrameData|null} [frameData=(auto create)] - Optional FrameData set associated with the given BitmapData. If not specified (or `undefined`) a new FrameData object is created containing the Bitmap's Frame. If `null` is supplied then no FrameData will be created.
  56311. * @return {Phaser.BitmapData} The BitmapData object to be addded to the cache.
  56312. */
  56313. addBitmapData: function (key, bitmapData, frameData) {
  56314. bitmapData.key = key;
  56315. if (frameData === undefined)
  56316. {
  56317. frameData = new Phaser.FrameData();
  56318. frameData.addFrame(bitmapData.textureFrame);
  56319. }
  56320. this._cache.bitmapData[key] = { data: bitmapData, frameData: frameData };
  56321. return bitmapData;
  56322. },
  56323. /**
  56324. * Add a new Bitmap Font to the Cache.
  56325. *
  56326. * @method Phaser.Cache#addBitmapFont
  56327. * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
  56328. * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`.
  56329. * @param {object} data - Extra font data.
  56330. * @param {object} atlasData - Texture atlas frames data.
  56331. * @param {string} [atlasType='xml'] - The format of the texture atlas ( 'json' or 'xml' ).
  56332. * @param {number} [xSpacing=0] - If you'd like to add additional horizontal spacing between the characters then set the pixel value here.
  56333. * @param {number} [ySpacing=0] - If you'd like to add additional vertical spacing between the lines then set the pixel value here.
  56334. */
  56335. addBitmapFont: function (key, url, data, atlasData, atlasType, xSpacing, ySpacing) {
  56336. var obj = {
  56337. url: url,
  56338. data: data,
  56339. font: null,
  56340. base: new PIXI.BaseTexture(data)
  56341. };
  56342. if (xSpacing === undefined) { xSpacing = 0; }
  56343. if (ySpacing === undefined) { ySpacing = 0; }
  56344. if (atlasType === 'json')
  56345. {
  56346. obj.font = Phaser.LoaderParser.jsonBitmapFont(atlasData, obj.base, xSpacing, ySpacing);
  56347. }
  56348. else
  56349. {
  56350. obj.font = Phaser.LoaderParser.xmlBitmapFont(atlasData, obj.base, xSpacing, ySpacing);
  56351. }
  56352. this._cache.bitmapFont[key] = obj;
  56353. this._resolveURL(url, obj);
  56354. },
  56355. /**
  56356. * Add a new json object into the cache.
  56357. *
  56358. * @method Phaser.Cache#addJSON
  56359. * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
  56360. * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`.
  56361. * @param {object} data - Extra json data.
  56362. */
  56363. addJSON: function (key, url, data) {
  56364. this._cache.json[key] = { url: url, data: data };
  56365. this._resolveURL(url, this._cache.json[key]);
  56366. },
  56367. /**
  56368. * Add a new xml object into the cache.
  56369. *
  56370. * @method Phaser.Cache#addXML
  56371. * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
  56372. * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`.
  56373. * @param {object} data - Extra text data.
  56374. */
  56375. addXML: function (key, url, data) {
  56376. this._cache.xml[key] = { url: url, data: data };
  56377. this._resolveURL(url, this._cache.xml[key]);
  56378. },
  56379. /**
  56380. * Adds a Video file into the Cache. The file must have already been loaded, typically via Phaser.Loader.
  56381. *
  56382. * @method Phaser.Cache#addVideo
  56383. * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
  56384. * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`.
  56385. * @param {object} data - Extra video data.
  56386. * @param {boolean} isBlob - True if the file was preloaded via xhr and the data parameter is a Blob. false if a Video tag was created instead.
  56387. */
  56388. addVideo: function (key, url, data, isBlob) {
  56389. this._cache.video[key] = { url: url, data: data, isBlob: isBlob, locked: true };
  56390. this._resolveURL(url, this._cache.video[key]);
  56391. },
  56392. /**
  56393. * Adds a Fragment Shader in to the Cache. The file must have already been loaded, typically via Phaser.Loader.
  56394. *
  56395. * @method Phaser.Cache#addShader
  56396. * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
  56397. * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`.
  56398. * @param {object} data - Extra shader data.
  56399. */
  56400. addShader: function (key, url, data) {
  56401. this._cache.shader[key] = { url: url, data: data };
  56402. this._resolveURL(url, this._cache.shader[key]);
  56403. },
  56404. /**
  56405. * Add a new Phaser.RenderTexture in to the cache.
  56406. *
  56407. * @method Phaser.Cache#addRenderTexture
  56408. * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
  56409. * @param {Phaser.RenderTexture} texture - The texture to use as the base of the RenderTexture.
  56410. */
  56411. addRenderTexture: function (key, texture) {
  56412. this._cache.renderTexture[key] = { texture: texture, frame: new Phaser.Frame(0, 0, 0, texture.width, texture.height, '', '') };
  56413. },
  56414. /**
  56415. * Add a new sprite sheet in to the cache.
  56416. *
  56417. * @method Phaser.Cache#addSpriteSheet
  56418. * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
  56419. * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`.
  56420. * @param {object} data - Extra sprite sheet data.
  56421. * @param {number} frameWidth - Width of the sprite sheet.
  56422. * @param {number} frameHeight - Height of the sprite sheet.
  56423. * @param {number} [frameMax=-1] - How many frames stored in the sprite sheet. If -1 then it divides the whole sheet evenly.
  56424. * @param {number} [margin=0] - If the frames have been drawn with a margin, specify the amount here.
  56425. * @param {number} [spacing=0] - If the frames have been drawn with spacing between them, specify the amount here.
  56426. */
  56427. addSpriteSheet: function (key, url, data, frameWidth, frameHeight, frameMax, margin, spacing) {
  56428. if (frameMax === undefined) { frameMax = -1; }
  56429. if (margin === undefined) { margin = 0; }
  56430. if (spacing === undefined) { spacing = 0; }
  56431. var obj = {
  56432. key: key,
  56433. url: url,
  56434. data: data,
  56435. frameWidth: frameWidth,
  56436. frameHeight: frameHeight,
  56437. margin: margin,
  56438. spacing: spacing,
  56439. base: new PIXI.BaseTexture(data),
  56440. frameData: Phaser.AnimationParser.spriteSheet(this.game, data, frameWidth, frameHeight, frameMax, margin, spacing)
  56441. };
  56442. this._cache.image[key] = obj;
  56443. this._resolveURL(url, obj);
  56444. },
  56445. /**
  56446. * Add a new texture atlas to the Cache.
  56447. *
  56448. * @method Phaser.Cache#addTextureAtlas
  56449. * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
  56450. * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`.
  56451. * @param {object} data - Extra texture atlas data.
  56452. * @param {object} atlasData - Texture atlas frames data.
  56453. * @param {number} format - The format of the texture atlas.
  56454. */
  56455. addTextureAtlas: function (key, url, data, atlasData, format) {
  56456. var obj = {
  56457. key: key,
  56458. url: url,
  56459. data: data,
  56460. base: new PIXI.BaseTexture(data)
  56461. };
  56462. if (format === Phaser.Loader.TEXTURE_ATLAS_XML_STARLING)
  56463. {
  56464. obj.frameData = Phaser.AnimationParser.XMLData(this.game, atlasData, key);
  56465. }
  56466. else if (format === Phaser.Loader.TEXTURE_ATLAS_JSON_PYXEL)
  56467. {
  56468. obj.frameData = Phaser.AnimationParser.JSONDataPyxel(this.game, atlasData, key);
  56469. }
  56470. else
  56471. {
  56472. // Let's just work it out from the frames array
  56473. if (Array.isArray(atlasData.frames))
  56474. {
  56475. obj.frameData = Phaser.AnimationParser.JSONData(this.game, atlasData, key);
  56476. }
  56477. else
  56478. {
  56479. obj.frameData = Phaser.AnimationParser.JSONDataHash(this.game, atlasData, key);
  56480. }
  56481. }
  56482. this._cache.image[key] = obj;
  56483. this._resolveURL(url, obj);
  56484. },
  56485. ////////////////////////////
  56486. // Sound Related Methods //
  56487. ////////////////////////////
  56488. /**
  56489. * Reload a Sound file from the server.
  56490. *
  56491. * @method Phaser.Cache#reloadSound
  56492. * @param {string} key - The key of the asset within the cache.
  56493. */
  56494. reloadSound: function (key) {
  56495. var _this = this;
  56496. var sound = this.getSound(key);
  56497. if (sound)
  56498. {
  56499. sound.data.src = sound.url;
  56500. sound.data.addEventListener('canplaythrough', function () {
  56501. return _this.reloadSoundComplete(key);
  56502. }, false);
  56503. sound.data.load();
  56504. }
  56505. },
  56506. /**
  56507. * Fires the onSoundUnlock event when the sound has completed reloading.
  56508. *
  56509. * @method Phaser.Cache#reloadSoundComplete
  56510. * @param {string} key - The key of the asset within the cache.
  56511. */
  56512. reloadSoundComplete: function (key) {
  56513. var sound = this.getSound(key);
  56514. if (sound)
  56515. {
  56516. sound.locked = false;
  56517. this.onSoundUnlock.dispatch(key);
  56518. }
  56519. },
  56520. /**
  56521. * Updates the sound object in the cache.
  56522. *
  56523. * @method Phaser.Cache#updateSound
  56524. * @param {string} key - The key of the asset within the cache.
  56525. */
  56526. updateSound: function (key, property, value) {
  56527. var sound = this.getSound(key);
  56528. if (sound)
  56529. {
  56530. sound[property] = value;
  56531. }
  56532. },
  56533. /**
  56534. * Add a new decoded sound.
  56535. *
  56536. * @method Phaser.Cache#decodedSound
  56537. * @param {string} key - The key of the asset within the cache.
  56538. * @param {object} data - Extra sound data.
  56539. */
  56540. decodedSound: function (key, data) {
  56541. var sound = this.getSound(key);
  56542. sound.data = data;
  56543. sound.decoded = true;
  56544. sound.isDecoding = false;
  56545. },
  56546. /**
  56547. * Check if the given sound has finished decoding.
  56548. *
  56549. * @method Phaser.Cache#isSoundDecoded
  56550. * @param {string} key - The key of the asset within the cache.
  56551. * @return {boolean} The decoded state of the Sound object.
  56552. */
  56553. isSoundDecoded: function (key) {
  56554. var sound = this.getItem(key, Phaser.Cache.SOUND, 'isSoundDecoded');
  56555. if (sound)
  56556. {
  56557. return sound.decoded;
  56558. }
  56559. },
  56560. /**
  56561. * Check if the given sound is ready for playback.
  56562. * A sound is considered ready when it has finished decoding and the device is no longer touch locked.
  56563. *
  56564. * @method Phaser.Cache#isSoundReady
  56565. * @param {string} key - The key of the asset within the cache.
  56566. * @return {boolean} True if the sound is decoded and the device is not touch locked.
  56567. */
  56568. isSoundReady: function (key) {
  56569. var sound = this.getItem(key, Phaser.Cache.SOUND, 'isSoundDecoded');
  56570. if (sound)
  56571. {
  56572. return (sound.decoded && !this.game.sound.touchLocked);
  56573. }
  56574. },
  56575. ////////////////////////
  56576. // Check Key Methods //
  56577. ////////////////////////
  56578. /**
  56579. * Checks if a key for the given cache object type exists.
  56580. *
  56581. * @method Phaser.Cache#checkKey
  56582. * @param {integer} cache - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`.
  56583. * @param {string} key - The key of the asset within the cache.
  56584. * @return {boolean} True if the key exists, otherwise false.
  56585. */
  56586. checkKey: function (cache, key) {
  56587. if (this._cacheMap[cache][key])
  56588. {
  56589. return true;
  56590. }
  56591. return false;
  56592. },
  56593. /**
  56594. * Checks if the given URL has been loaded into the Cache.
  56595. * This method will only work if Cache.autoResolveURL was set to `true` before any preloading took place.
  56596. * The method will make a DOM src call to the URL given, so please be aware of this for certain file types, such as Sound files on Firefox
  56597. * which may cause double-load instances.
  56598. *
  56599. * @method Phaser.Cache#checkURL
  56600. * @param {string} url - The url to check for in the cache.
  56601. * @return {boolean} True if the url exists, otherwise false.
  56602. */
  56603. checkURL: function (url) {
  56604. if (this._urlMap[this._resolveURL(url)])
  56605. {
  56606. return true;
  56607. }
  56608. return false;
  56609. },
  56610. /**
  56611. * Checks if the given key exists in the Canvas Cache.
  56612. *
  56613. * @method Phaser.Cache#checkCanvasKey
  56614. * @param {string} key - The key of the asset within the cache.
  56615. * @return {boolean} True if the key exists in the cache, otherwise false.
  56616. */
  56617. checkCanvasKey: function (key) {
  56618. return this.checkKey(Phaser.Cache.CANVAS, key);
  56619. },
  56620. /**
  56621. * Checks if the given key exists in the Image Cache. Note that this also includes Texture Atlases, Sprite Sheets and Retro Fonts.
  56622. *
  56623. * @method Phaser.Cache#checkImageKey
  56624. * @param {string} key - The key of the asset within the cache.
  56625. * @return {boolean} True if the key exists in the cache, otherwise false.
  56626. */
  56627. checkImageKey: function (key) {
  56628. return this.checkKey(Phaser.Cache.IMAGE, key);
  56629. },
  56630. /**
  56631. * Checks if the given key exists in the Texture Cache.
  56632. *
  56633. * @method Phaser.Cache#checkTextureKey
  56634. * @param {string} key - The key of the asset within the cache.
  56635. * @return {boolean} True if the key exists in the cache, otherwise false.
  56636. */
  56637. checkTextureKey: function (key) {
  56638. return this.checkKey(Phaser.Cache.TEXTURE, key);
  56639. },
  56640. /**
  56641. * Checks if the given key exists in the Sound Cache.
  56642. *
  56643. * @method Phaser.Cache#checkSoundKey
  56644. * @param {string} key - The key of the asset within the cache.
  56645. * @return {boolean} True if the key exists in the cache, otherwise false.
  56646. */
  56647. checkSoundKey: function (key) {
  56648. return this.checkKey(Phaser.Cache.SOUND, key);
  56649. },
  56650. /**
  56651. * Checks if the given key exists in the Text Cache.
  56652. *
  56653. * @method Phaser.Cache#checkTextKey
  56654. * @param {string} key - The key of the asset within the cache.
  56655. * @return {boolean} True if the key exists in the cache, otherwise false.
  56656. */
  56657. checkTextKey: function (key) {
  56658. return this.checkKey(Phaser.Cache.TEXT, key);
  56659. },
  56660. /**
  56661. * Checks if the given key exists in the Physics Cache.
  56662. *
  56663. * @method Phaser.Cache#checkPhysicsKey
  56664. * @param {string} key - The key of the asset within the cache.
  56665. * @return {boolean} True if the key exists in the cache, otherwise false.
  56666. */
  56667. checkPhysicsKey: function (key) {
  56668. return this.checkKey(Phaser.Cache.PHYSICS, key);
  56669. },
  56670. /**
  56671. * Checks if the given key exists in the Tilemap Cache.
  56672. *
  56673. * @method Phaser.Cache#checkTilemapKey
  56674. * @param {string} key - The key of the asset within the cache.
  56675. * @return {boolean} True if the key exists in the cache, otherwise false.
  56676. */
  56677. checkTilemapKey: function (key) {
  56678. return this.checkKey(Phaser.Cache.TILEMAP, key);
  56679. },
  56680. /**
  56681. * Checks if the given key exists in the Binary Cache.
  56682. *
  56683. * @method Phaser.Cache#checkBinaryKey
  56684. * @param {string} key - The key of the asset within the cache.
  56685. * @return {boolean} True if the key exists in the cache, otherwise false.
  56686. */
  56687. checkBinaryKey: function (key) {
  56688. return this.checkKey(Phaser.Cache.BINARY, key);
  56689. },
  56690. /**
  56691. * Checks if the given key exists in the BitmapData Cache.
  56692. *
  56693. * @method Phaser.Cache#checkBitmapDataKey
  56694. * @param {string} key - The key of the asset within the cache.
  56695. * @return {boolean} True if the key exists in the cache, otherwise false.
  56696. */
  56697. checkBitmapDataKey: function (key) {
  56698. return this.checkKey(Phaser.Cache.BITMAPDATA, key);
  56699. },
  56700. /**
  56701. * Checks if the given key exists in the BitmapFont Cache.
  56702. *
  56703. * @method Phaser.Cache#checkBitmapFontKey
  56704. * @param {string} key - The key of the asset within the cache.
  56705. * @return {boolean} True if the key exists in the cache, otherwise false.
  56706. */
  56707. checkBitmapFontKey: function (key) {
  56708. return this.checkKey(Phaser.Cache.BITMAPFONT, key);
  56709. },
  56710. /**
  56711. * Checks if the given key exists in the JSON Cache.
  56712. *
  56713. * @method Phaser.Cache#checkJSONKey
  56714. * @param {string} key - The key of the asset within the cache.
  56715. * @return {boolean} True if the key exists in the cache, otherwise false.
  56716. */
  56717. checkJSONKey: function (key) {
  56718. return this.checkKey(Phaser.Cache.JSON, key);
  56719. },
  56720. /**
  56721. * Checks if the given key exists in the XML Cache.
  56722. *
  56723. * @method Phaser.Cache#checkXMLKey
  56724. * @param {string} key - The key of the asset within the cache.
  56725. * @return {boolean} True if the key exists in the cache, otherwise false.
  56726. */
  56727. checkXMLKey: function (key) {
  56728. return this.checkKey(Phaser.Cache.XML, key);
  56729. },
  56730. /**
  56731. * Checks if the given key exists in the Video Cache.
  56732. *
  56733. * @method Phaser.Cache#checkVideoKey
  56734. * @param {string} key - The key of the asset within the cache.
  56735. * @return {boolean} True if the key exists in the cache, otherwise false.
  56736. */
  56737. checkVideoKey: function (key) {
  56738. return this.checkKey(Phaser.Cache.VIDEO, key);
  56739. },
  56740. /**
  56741. * Checks if the given key exists in the Fragment Shader Cache.
  56742. *
  56743. * @method Phaser.Cache#checkShaderKey
  56744. * @param {string} key - The key of the asset within the cache.
  56745. * @return {boolean} True if the key exists in the cache, otherwise false.
  56746. */
  56747. checkShaderKey: function (key) {
  56748. return this.checkKey(Phaser.Cache.SHADER, key);
  56749. },
  56750. /**
  56751. * Checks if the given key exists in the Render Texture Cache.
  56752. *
  56753. * @method Phaser.Cache#checkRenderTextureKey
  56754. * @param {string} key - The key of the asset within the cache.
  56755. * @return {boolean} True if the key exists in the cache, otherwise false.
  56756. */
  56757. checkRenderTextureKey: function (key) {
  56758. return this.checkKey(Phaser.Cache.RENDER_TEXTURE, key);
  56759. },
  56760. ////////////////
  56761. // Get Items //
  56762. ////////////////
  56763. /**
  56764. * Get an item from a cache based on the given key and property.
  56765. *
  56766. * This method is mostly used internally by other Cache methods such as `getImage` but is exposed
  56767. * publicly for your own use as well.
  56768. *
  56769. * @method Phaser.Cache#getItem
  56770. * @param {string} key - The key of the asset within the cache.
  56771. * @param {integer} cache - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`.
  56772. * @param {string} [method] - The string name of the method calling getItem. Can be empty, in which case no console warning is output.
  56773. * @param {string} [property] - If you require a specific property from the cache item, specify it here.
  56774. * @return {object} The cached item if found, otherwise `null`. If the key is invalid and `method` is set then a console.warn is output.
  56775. */
  56776. getItem: function (key, cache, method, property) {
  56777. if (!this.checkKey(cache, key))
  56778. {
  56779. if (method)
  56780. {
  56781. console.warn('Phaser.Cache.' + method + ': Key "' + key + '" not found in Cache.');
  56782. }
  56783. }
  56784. else
  56785. {
  56786. if (property === undefined)
  56787. {
  56788. return this._cacheMap[cache][key];
  56789. }
  56790. else
  56791. {
  56792. return this._cacheMap[cache][key][property];
  56793. }
  56794. }
  56795. return null;
  56796. },
  56797. /**
  56798. * Gets a Canvas object from the cache.
  56799. *
  56800. * The object is looked-up based on the key given.
  56801. *
  56802. * Note: If the object cannot be found a `console.warn` message is displayed.
  56803. *
  56804. * @method Phaser.Cache#getCanvas
  56805. * @param {string} key - The key of the asset to retrieve from the cache.
  56806. * @return {object} The canvas object or `null` if no item could be found matching the given key.
  56807. */
  56808. getCanvas: function (key) {
  56809. return this.getItem(key, Phaser.Cache.CANVAS, 'getCanvas', 'canvas');
  56810. },
  56811. /**
  56812. * Gets a Image object from the cache. This returns a DOM Image object, not a Phaser.Image object.
  56813. *
  56814. * The object is looked-up based on the key given.
  56815. *
  56816. * Note: If the object cannot be found a `console.warn` message is displayed.
  56817. *
  56818. * Only the Image cache is searched, which covers images loaded via Loader.image, Sprite Sheets and Texture Atlases.
  56819. *
  56820. * If you need the image used by a bitmap font or similar then please use those respective 'get' methods.
  56821. *
  56822. * @method Phaser.Cache#getImage
  56823. * @param {string} [key] - The key of the asset to retrieve from the cache. If not given or null it will return a default image. If given but not found in the cache it will throw a warning and return the missing image.
  56824. * @param {boolean} [full=false] - If true the full image object will be returned, if false just the HTML Image object is returned.
  56825. * @return {Image} The Image object if found in the Cache, otherwise `null`. If `full` was true then a JavaScript object is returned.
  56826. */
  56827. getImage: function (key, full) {
  56828. if (key === undefined || key === null)
  56829. {
  56830. key = '__default';
  56831. }
  56832. if (full === undefined) { full = false; }
  56833. var img = this.getItem(key, Phaser.Cache.IMAGE, 'getImage');
  56834. if (img === null)
  56835. {
  56836. img = this.getItem('__missing', Phaser.Cache.IMAGE, 'getImage');
  56837. }
  56838. if (full)
  56839. {
  56840. return img;
  56841. }
  56842. else
  56843. {
  56844. return img.data;
  56845. }
  56846. },
  56847. /**
  56848. * Get a single texture frame by key.
  56849. *
  56850. * You'd only do this to get the default Frame created for a non-atlas / spritesheet image.
  56851. *
  56852. * @method Phaser.Cache#getTextureFrame
  56853. * @param {string} key - The key of the asset to retrieve from the cache.
  56854. * @return {Phaser.Frame} The frame data.
  56855. */
  56856. getTextureFrame: function (key) {
  56857. return this.getItem(key, Phaser.Cache.TEXTURE, 'getTextureFrame', 'frame');
  56858. },
  56859. /**
  56860. * Gets a Phaser.Sound object from the cache.
  56861. *
  56862. * The object is looked-up based on the key given.
  56863. *
  56864. * Note: If the object cannot be found a `console.warn` message is displayed.
  56865. *
  56866. * @method Phaser.Cache#getSound
  56867. * @param {string} key - The key of the asset to retrieve from the cache.
  56868. * @return {Phaser.Sound} The sound object.
  56869. */
  56870. getSound: function (key) {
  56871. return this.getItem(key, Phaser.Cache.SOUND, 'getSound');
  56872. },
  56873. /**
  56874. * Gets a raw Sound data object from the cache.
  56875. *
  56876. * The object is looked-up based on the key given.
  56877. *
  56878. * Note: If the object cannot be found a `console.warn` message is displayed.
  56879. *
  56880. * @method Phaser.Cache#getSoundData
  56881. * @param {string} key - The key of the asset to retrieve from the cache.
  56882. * @return {object} The sound data.
  56883. */
  56884. getSoundData: function (key) {
  56885. return this.getItem(key, Phaser.Cache.SOUND, 'getSoundData', 'data');
  56886. },
  56887. /**
  56888. * Gets a Text object from the cache.
  56889. *
  56890. * The object is looked-up based on the key given.
  56891. *
  56892. * Note: If the object cannot be found a `console.warn` message is displayed.
  56893. *
  56894. * @method Phaser.Cache#getText
  56895. * @param {string} key - The key of the asset to retrieve from the cache.
  56896. * @return {object} The text data.
  56897. */
  56898. getText: function (key) {
  56899. return this.getItem(key, Phaser.Cache.TEXT, 'getText', 'data');
  56900. },
  56901. /**
  56902. * Gets a Physics Data object from the cache.
  56903. *
  56904. * The object is looked-up based on the key given.
  56905. *
  56906. * Note: If the object cannot be found a `console.warn` message is displayed.
  56907. *
  56908. * You can get either the entire data set, a single object or a single fixture of an object from it.
  56909. *
  56910. * @method Phaser.Cache#getPhysicsData
  56911. * @param {string} key - The key of the asset to retrieve from the cache.
  56912. * @param {string} [object=null] - If specified it will return just the physics object that is part of the given key, if null it will return them all.
  56913. * @param {string} fixtureKey - Fixture key of fixture inside an object. This key can be set per fixture with the Phaser Exporter.
  56914. * @return {object} The requested physics object data if found.
  56915. */
  56916. getPhysicsData: function (key, object, fixtureKey) {
  56917. var data = this.getItem(key, Phaser.Cache.PHYSICS, 'getPhysicsData', 'data');
  56918. if (data === null || object === undefined || object === null)
  56919. {
  56920. return data;
  56921. }
  56922. else
  56923. {
  56924. if (data[object])
  56925. {
  56926. var fixtures = data[object];
  56927. // Try to find a fixture by its fixture key if given
  56928. if (fixtures && fixtureKey)
  56929. {
  56930. for (var fixture in fixtures)
  56931. {
  56932. // This contains the fixture data of a polygon or a circle
  56933. fixture = fixtures[fixture];
  56934. // Test the key
  56935. if (fixture.fixtureKey === fixtureKey)
  56936. {
  56937. return fixture;
  56938. }
  56939. }
  56940. // We did not find the requested fixture
  56941. console.warn('Phaser.Cache.getPhysicsData: Could not find given fixtureKey: "' + fixtureKey + ' in ' + key + '"');
  56942. }
  56943. else
  56944. {
  56945. return fixtures;
  56946. }
  56947. }
  56948. else
  56949. {
  56950. console.warn('Phaser.Cache.getPhysicsData: Invalid key/object: "' + key + ' / ' + object + '"');
  56951. }
  56952. }
  56953. return null;
  56954. },
  56955. /**
  56956. * Gets a raw Tilemap data object from the cache. This will be in either CSV or JSON format.
  56957. *
  56958. * The object is looked-up based on the key given.
  56959. *
  56960. * Note: If the object cannot be found a `console.warn` message is displayed.
  56961. *
  56962. * @method Phaser.Cache#getTilemapData
  56963. * @param {string} key - The key of the asset to retrieve from the cache.
  56964. * @return {object} The raw tilemap data in CSV or JSON format.
  56965. */
  56966. getTilemapData: function (key) {
  56967. return this.getItem(key, Phaser.Cache.TILEMAP, 'getTilemapData');
  56968. },
  56969. /**
  56970. * Gets a binary object from the cache.
  56971. *
  56972. * The object is looked-up based on the key given.
  56973. *
  56974. * Note: If the object cannot be found a `console.warn` message is displayed.
  56975. *
  56976. * @method Phaser.Cache#getBinary
  56977. * @param {string} key - The key of the asset to retrieve from the cache.
  56978. * @return {object} The binary data object.
  56979. */
  56980. getBinary: function (key) {
  56981. return this.getItem(key, Phaser.Cache.BINARY, 'getBinary');
  56982. },
  56983. /**
  56984. * Gets a BitmapData object from the cache.
  56985. *
  56986. * The object is looked-up based on the key given.
  56987. *
  56988. * Note: If the object cannot be found a `console.warn` message is displayed.
  56989. *
  56990. * @method Phaser.Cache#getBitmapData
  56991. * @param {string} key - The key of the asset to retrieve from the cache.
  56992. * @return {Phaser.BitmapData} The requested BitmapData object if found, or null if not.
  56993. */
  56994. getBitmapData: function (key) {
  56995. return this.getItem(key, Phaser.Cache.BITMAPDATA, 'getBitmapData', 'data');
  56996. },
  56997. /**
  56998. * Gets a Bitmap Font object from the cache.
  56999. *
  57000. * The object is looked-up based on the key given.
  57001. *
  57002. * Note: If the object cannot be found a `console.warn` message is displayed.
  57003. *
  57004. * @method Phaser.Cache#getBitmapFont
  57005. * @param {string} key - The key of the asset to retrieve from the cache.
  57006. * @return {Phaser.BitmapFont} The requested BitmapFont object if found, or null if not.
  57007. */
  57008. getBitmapFont: function (key) {
  57009. return this.getItem(key, Phaser.Cache.BITMAPFONT, 'getBitmapFont');
  57010. },
  57011. /**
  57012. * Gets a JSON object from the cache.
  57013. *
  57014. * The object is looked-up based on the key given.
  57015. *
  57016. * Note: If the object cannot be found a `console.warn` message is displayed.
  57017. *
  57018. * You can either return the object by reference (the default), or return a clone
  57019. * of it by setting the `clone` argument to `true`.
  57020. *
  57021. * @method Phaser.Cache#getJSON
  57022. * @param {string} key - The key of the asset to retrieve from the cache.
  57023. * @param {boolean} [clone=false] - Return a clone of the original object (true) or a reference to it? (false)
  57024. * @return {object} The JSON object.
  57025. */
  57026. getJSON: function (key, clone) {
  57027. var data = this.getItem(key, Phaser.Cache.JSON, 'getJSON', 'data');
  57028. if (data)
  57029. {
  57030. if (clone)
  57031. {
  57032. return Phaser.Utils.extend(true, data);
  57033. }
  57034. else
  57035. {
  57036. return data;
  57037. }
  57038. }
  57039. else
  57040. {
  57041. return null;
  57042. }
  57043. },
  57044. /**
  57045. * Gets an XML object from the cache.
  57046. *
  57047. * The object is looked-up based on the key given.
  57048. *
  57049. * Note: If the object cannot be found a `console.warn` message is displayed.
  57050. *
  57051. * @method Phaser.Cache#getXML
  57052. * @param {string} key - The key of the asset to retrieve from the cache.
  57053. * @return {object} The XML object.
  57054. */
  57055. getXML: function (key) {
  57056. return this.getItem(key, Phaser.Cache.XML, 'getXML', 'data');
  57057. },
  57058. /**
  57059. * Gets a Phaser.Video object from the cache.
  57060. *
  57061. * The object is looked-up based on the key given.
  57062. *
  57063. * Note: If the object cannot be found a `console.warn` message is displayed.
  57064. *
  57065. * @method Phaser.Cache#getVideo
  57066. * @param {string} key - The key of the asset to retrieve from the cache.
  57067. * @return {Phaser.Video} The video object.
  57068. */
  57069. getVideo: function (key) {
  57070. return this.getItem(key, Phaser.Cache.VIDEO, 'getVideo');
  57071. },
  57072. /**
  57073. * Gets a fragment shader object from the cache.
  57074. *
  57075. * The object is looked-up based on the key given.
  57076. *
  57077. * Note: If the object cannot be found a `console.warn` message is displayed.
  57078. *
  57079. * @method Phaser.Cache#getShader
  57080. * @param {string} key - The key of the asset to retrieve from the cache.
  57081. * @return {string} The shader object.
  57082. */
  57083. getShader: function (key) {
  57084. return this.getItem(key, Phaser.Cache.SHADER, 'getShader', 'data');
  57085. },
  57086. /**
  57087. * Gets a RenderTexture object from the cache.
  57088. *
  57089. * The object is looked-up based on the key given.
  57090. *
  57091. * Note: If the object cannot be found a `console.warn` message is displayed.
  57092. *
  57093. * @method Phaser.Cache#getRenderTexture
  57094. * @param {string} key - The key of the asset to retrieve from the cache.
  57095. * @return {Object} The object with Phaser.RenderTexture and Phaser.Frame.
  57096. */
  57097. getRenderTexture: function (key) {
  57098. return this.getItem(key, Phaser.Cache.RENDER_TEXTURE, 'getRenderTexture');
  57099. },
  57100. ////////////////////////////
  57101. // Frame Related Methods //
  57102. ////////////////////////////
  57103. /**
  57104. * Gets a PIXI.BaseTexture by key from the given Cache.
  57105. *
  57106. * @method Phaser.Cache#getBaseTexture
  57107. * @param {string} key - Asset key of the image for which you want the BaseTexture for.
  57108. * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in.
  57109. * @return {PIXI.BaseTexture} The BaseTexture object.
  57110. */
  57111. getBaseTexture: function (key, cache) {
  57112. if (cache === undefined) { cache = Phaser.Cache.IMAGE; }
  57113. return this.getItem(key, cache, 'getBaseTexture', 'base');
  57114. },
  57115. /**
  57116. * Get a single frame by key. You'd only do this to get the default Frame created for a non-atlas/spritesheet image.
  57117. *
  57118. * @method Phaser.Cache#getFrame
  57119. * @param {string} key - Asset key of the frame data to retrieve from the Cache.
  57120. * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in.
  57121. * @return {Phaser.Frame} The frame data.
  57122. */
  57123. getFrame: function (key, cache) {
  57124. if (cache === undefined) { cache = Phaser.Cache.IMAGE; }
  57125. return this.getItem(key, cache, 'getFrame', 'frame');
  57126. },
  57127. /**
  57128. * Get the total number of frames contained in the FrameData object specified by the given key.
  57129. *
  57130. * @method Phaser.Cache#getFrameCount
  57131. * @param {string} key - Asset key of the FrameData you want.
  57132. * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in.
  57133. * @return {number} Then number of frames. 0 if the image is not found.
  57134. */
  57135. getFrameCount: function (key, cache) {
  57136. var data = this.getFrameData(key, cache);
  57137. if (data)
  57138. {
  57139. return data.total;
  57140. }
  57141. else
  57142. {
  57143. return 0;
  57144. }
  57145. },
  57146. /**
  57147. * Gets a Phaser.FrameData object from the Image Cache.
  57148. *
  57149. * The object is looked-up based on the key given.
  57150. *
  57151. * Note: If the object cannot be found a `console.warn` message is displayed.
  57152. *
  57153. * @method Phaser.Cache#getFrameData
  57154. * @param {string} key - Asset key of the frame data to retrieve from the Cache.
  57155. * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in.
  57156. * @return {Phaser.FrameData} The frame data.
  57157. */
  57158. getFrameData: function (key, cache) {
  57159. if (cache === undefined) { cache = Phaser.Cache.IMAGE; }
  57160. return this.getItem(key, cache, 'getFrameData', 'frameData');
  57161. },
  57162. /**
  57163. * Check if the FrameData for the given key exists in the Image Cache.
  57164. *
  57165. * @method Phaser.Cache#hasFrameData
  57166. * @param {string} key - Asset key of the frame data to retrieve from the Cache.
  57167. * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in.
  57168. * @return {boolean} True if the given key has frameData in the cache, otherwise false.
  57169. */
  57170. hasFrameData: function (key, cache) {
  57171. if (cache === undefined) { cache = Phaser.Cache.IMAGE; }
  57172. return (this.getItem(key, cache, '', 'frameData') !== null);
  57173. },
  57174. /**
  57175. * Replaces a set of frameData with a new Phaser.FrameData object.
  57176. *
  57177. * @method Phaser.Cache#updateFrameData
  57178. * @param {string} key - The unique key by which you will reference this object.
  57179. * @param {number} frameData - The new FrameData.
  57180. * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`.
  57181. */
  57182. updateFrameData: function (key, frameData, cache) {
  57183. if (cache === undefined) { cache = Phaser.Cache.IMAGE; }
  57184. if (this._cacheMap[cache][key])
  57185. {
  57186. this._cacheMap[cache][key].frameData = frameData;
  57187. }
  57188. },
  57189. /**
  57190. * Get a single frame out of a frameData set by key.
  57191. *
  57192. * @method Phaser.Cache#getFrameByIndex
  57193. * @param {string} key - Asset key of the frame data to retrieve from the Cache.
  57194. * @param {number} index - The index of the frame you want to get.
  57195. * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`.
  57196. * @return {Phaser.Frame} The frame object.
  57197. */
  57198. getFrameByIndex: function (key, index, cache) {
  57199. var data = this.getFrameData(key, cache);
  57200. if (data)
  57201. {
  57202. return data.getFrame(index);
  57203. }
  57204. else
  57205. {
  57206. return null;
  57207. }
  57208. },
  57209. /**
  57210. * Get a single frame out of a frameData set by key.
  57211. *
  57212. * @method Phaser.Cache#getFrameByName
  57213. * @param {string} key - Asset key of the frame data to retrieve from the Cache.
  57214. * @param {string} name - The name of the frame you want to get.
  57215. * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`.
  57216. * @return {Phaser.Frame} The frame object.
  57217. */
  57218. getFrameByName: function (key, name, cache) {
  57219. var data = this.getFrameData(key, cache);
  57220. if (data)
  57221. {
  57222. return data.getFrameByName(name);
  57223. }
  57224. else
  57225. {
  57226. return null;
  57227. }
  57228. },
  57229. /**
  57230. * Gets a PIXI.Texture by key from the PIXI.TextureCache.
  57231. *
  57232. * If the texture isn't found in the cache, then it searches the Phaser Image Cache and
  57233. * creates a new PIXI.Texture object which is then returned.
  57234. *
  57235. * @method Phaser.Cache#getPixiTexture
  57236. * @deprecated
  57237. * @param {string} key - Asset key of the Texture to retrieve from the Cache.
  57238. * @return {PIXI.Texture} The Texture object.
  57239. */
  57240. getPixiTexture: function (key) {
  57241. if (PIXI.TextureCache[key])
  57242. {
  57243. return PIXI.TextureCache[key];
  57244. }
  57245. else
  57246. {
  57247. var base = this.getPixiBaseTexture(key);
  57248. if (base)
  57249. {
  57250. return new PIXI.Texture(base);
  57251. }
  57252. else
  57253. {
  57254. return null;
  57255. }
  57256. }
  57257. },
  57258. /**
  57259. * Gets a PIXI.BaseTexture by key from the PIXI.BaseTextureCache.
  57260. *
  57261. * If the texture isn't found in the cache, then it searches the Phaser Image Cache.
  57262. *
  57263. * @method Phaser.Cache#getPixiBaseTexture
  57264. * @deprecated
  57265. * @param {string} key - Asset key of the BaseTexture to retrieve from the Cache.
  57266. * @return {PIXI.BaseTexture} The BaseTexture object or null if not found.
  57267. */
  57268. getPixiBaseTexture: function (key) {
  57269. if (PIXI.BaseTextureCache[key])
  57270. {
  57271. return PIXI.BaseTextureCache[key];
  57272. }
  57273. else
  57274. {
  57275. var img = this.getItem(key, Phaser.Cache.IMAGE, 'getPixiBaseTexture');
  57276. if (img !== null)
  57277. {
  57278. return img.base;
  57279. }
  57280. else
  57281. {
  57282. return null;
  57283. }
  57284. }
  57285. },
  57286. /**
  57287. * Get a cached object by the URL.
  57288. * This only returns a value if you set Cache.autoResolveURL to `true` *before* starting the preload of any assets.
  57289. * Be aware that every call to this function makes a DOM src query, so use carefully and double-check for implications in your target browsers/devices.
  57290. *
  57291. * @method Phaser.Cache#getURL
  57292. * @param {string} url - The url for the object loaded to get from the cache.
  57293. * @return {object} The cached object.
  57294. */
  57295. getURL: function (url) {
  57296. var url = this._resolveURL(url);
  57297. if (url)
  57298. {
  57299. return this._urlMap[url];
  57300. }
  57301. else
  57302. {
  57303. console.warn('Phaser.Cache.getUrl: Invalid url: "' + url + '" or Cache.autoResolveURL was false');
  57304. return null;
  57305. }
  57306. },
  57307. /**
  57308. * Gets all keys used in the requested Cache.
  57309. *
  57310. * @method Phaser.Cache#getKeys
  57311. * @param {integer} [cache=Phaser.Cache.IMAGE] - The Cache you wish to get the keys from. Can be any of the Cache consts such as `Phaser.Cache.IMAGE`, `Phaser.Cache.SOUND` etc.
  57312. * @return {Array} The array of keys in the requested cache.
  57313. */
  57314. getKeys: function (cache) {
  57315. if (cache === undefined) { cache = Phaser.Cache.IMAGE; }
  57316. var out = [];
  57317. if (this._cacheMap[cache])
  57318. {
  57319. for (var key in this._cacheMap[cache])
  57320. {
  57321. if (key !== '__default' && key !== '__missing')
  57322. {
  57323. out.push(key);
  57324. }
  57325. }
  57326. }
  57327. return out;
  57328. },
  57329. /////////////////////
  57330. // Remove Methods //
  57331. /////////////////////
  57332. /**
  57333. * Removes a canvas from the cache.
  57334. *
  57335. * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere
  57336. * then it will persist in memory.
  57337. *
  57338. * @method Phaser.Cache#removeCanvas
  57339. * @param {string} key - Key of the asset you want to remove.
  57340. */
  57341. removeCanvas: function (key) {
  57342. delete this._cache.canvas[key];
  57343. },
  57344. /**
  57345. * Removes an image from the cache.
  57346. *
  57347. * You can optionally elect to destroy it as well. This calls BaseTexture.destroy on it.
  57348. *
  57349. * Note that this only removes it from the Phaser and PIXI Caches. If you still have references to the data elsewhere
  57350. * then it will persist in memory.
  57351. *
  57352. * @method Phaser.Cache#removeImage
  57353. * @param {string} key - Key of the asset you want to remove.
  57354. * @param {boolean} [removeFromPixi=true] - Should this image also be destroyed? Removing it from the PIXI.BaseTextureCache?
  57355. */
  57356. removeImage: function (key, removeFromPixi) {
  57357. if (removeFromPixi === undefined) { removeFromPixi = true; }
  57358. var img = this.getImage(key, true);
  57359. if (removeFromPixi && img.base)
  57360. {
  57361. img.base.destroy();
  57362. }
  57363. delete this._cache.image[key];
  57364. },
  57365. /**
  57366. * Removes a sound from the cache.
  57367. *
  57368. * If any `Phaser.Sound` objects use the audio file in the cache that you remove with this method, they will
  57369. * _automatically_ destroy themselves. If you wish to have full control over when Sounds are destroyed then
  57370. * you must finish your house-keeping and destroy them all yourself first, before calling this method.
  57371. *
  57372. * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere
  57373. * then it will persist in memory.
  57374. *
  57375. * @method Phaser.Cache#removeSound
  57376. * @param {string} key - Key of the asset you want to remove.
  57377. */
  57378. removeSound: function (key) {
  57379. delete this._cache.sound[key];
  57380. },
  57381. /**
  57382. * Removes a text file from the cache.
  57383. *
  57384. * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere
  57385. * then it will persist in memory.
  57386. *
  57387. * @method Phaser.Cache#removeText
  57388. * @param {string} key - Key of the asset you want to remove.
  57389. */
  57390. removeText: function (key) {
  57391. delete this._cache.text[key];
  57392. },
  57393. /**
  57394. * Removes a physics data file from the cache.
  57395. *
  57396. * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere
  57397. * then it will persist in memory.
  57398. *
  57399. * @method Phaser.Cache#removePhysics
  57400. * @param {string} key - Key of the asset you want to remove.
  57401. */
  57402. removePhysics: function (key) {
  57403. delete this._cache.physics[key];
  57404. },
  57405. /**
  57406. * Removes a tilemap from the cache.
  57407. *
  57408. * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere
  57409. * then it will persist in memory.
  57410. *
  57411. * @method Phaser.Cache#removeTilemap
  57412. * @param {string} key - Key of the asset you want to remove.
  57413. */
  57414. removeTilemap: function (key) {
  57415. delete this._cache.tilemap[key];
  57416. },
  57417. /**
  57418. * Removes a binary file from the cache.
  57419. *
  57420. * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere
  57421. * then it will persist in memory.
  57422. *
  57423. * @method Phaser.Cache#removeBinary
  57424. * @param {string} key - Key of the asset you want to remove.
  57425. */
  57426. removeBinary: function (key) {
  57427. delete this._cache.binary[key];
  57428. },
  57429. /**
  57430. * Removes a bitmap data from the cache.
  57431. *
  57432. * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere
  57433. * then it will persist in memory.
  57434. *
  57435. * @method Phaser.Cache#removeBitmapData
  57436. * @param {string} key - Key of the asset you want to remove.
  57437. */
  57438. removeBitmapData: function (key) {
  57439. delete this._cache.bitmapData[key];
  57440. },
  57441. /**
  57442. * Removes a bitmap font from the cache.
  57443. *
  57444. * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere
  57445. * then it will persist in memory.
  57446. *
  57447. * @method Phaser.Cache#removeBitmapFont
  57448. * @param {string} key - Key of the asset you want to remove.
  57449. */
  57450. removeBitmapFont: function (key) {
  57451. delete this._cache.bitmapFont[key];
  57452. },
  57453. /**
  57454. * Removes a json object from the cache.
  57455. *
  57456. * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere
  57457. * then it will persist in memory.
  57458. *
  57459. * @method Phaser.Cache#removeJSON
  57460. * @param {string} key - Key of the asset you want to remove.
  57461. */
  57462. removeJSON: function (key) {
  57463. delete this._cache.json[key];
  57464. },
  57465. /**
  57466. * Removes a xml object from the cache.
  57467. *
  57468. * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere
  57469. * then it will persist in memory.
  57470. *
  57471. * @method Phaser.Cache#removeXML
  57472. * @param {string} key - Key of the asset you want to remove.
  57473. */
  57474. removeXML: function (key) {
  57475. delete this._cache.xml[key];
  57476. },
  57477. /**
  57478. * Removes a video from the cache.
  57479. *
  57480. * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere
  57481. * then it will persist in memory.
  57482. *
  57483. * @method Phaser.Cache#removeVideo
  57484. * @param {string} key - Key of the asset you want to remove.
  57485. */
  57486. removeVideo: function (key) {
  57487. delete this._cache.video[key];
  57488. },
  57489. /**
  57490. * Removes a shader from the cache.
  57491. *
  57492. * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere
  57493. * then it will persist in memory.
  57494. *
  57495. * @method Phaser.Cache#removeShader
  57496. * @param {string} key - Key of the asset you want to remove.
  57497. */
  57498. removeShader: function (key) {
  57499. delete this._cache.shader[key];
  57500. },
  57501. /**
  57502. * Removes a Render Texture from the cache.
  57503. *
  57504. * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere
  57505. * then it will persist in memory.
  57506. *
  57507. * @method Phaser.Cache#removeRenderTexture
  57508. * @param {string} key - Key of the asset you want to remove.
  57509. */
  57510. removeRenderTexture: function (key) {
  57511. delete this._cache.renderTexture[key];
  57512. },
  57513. /**
  57514. * Removes a Sprite Sheet from the cache.
  57515. *
  57516. * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere
  57517. * then it will persist in memory.
  57518. *
  57519. * @method Phaser.Cache#removeSpriteSheet
  57520. * @param {string} key - Key of the asset you want to remove.
  57521. */
  57522. removeSpriteSheet: function (key) {
  57523. delete this._cache.spriteSheet[key];
  57524. },
  57525. /**
  57526. * Removes a Texture Atlas from the cache.
  57527. *
  57528. * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere
  57529. * then it will persist in memory.
  57530. *
  57531. * @method Phaser.Cache#removeTextureAtlas
  57532. * @param {string} key - Key of the asset you want to remove.
  57533. */
  57534. removeTextureAtlas: function (key) {
  57535. delete this._cache.atlas[key];
  57536. },
  57537. /**
  57538. * Empties out all of the GL Textures from Images stored in the cache.
  57539. * This is called automatically when the WebGL context is lost and then restored.
  57540. *
  57541. * @method Phaser.Cache#clearGLTextures
  57542. * @protected
  57543. */
  57544. clearGLTextures: function () {
  57545. for (var key in this._cache.image)
  57546. {
  57547. this._cache.image[key].base._glTextures = [];
  57548. }
  57549. },
  57550. /**
  57551. * Resolves a URL to its absolute form and stores it in Cache._urlMap as long as Cache.autoResolveURL is set to `true`.
  57552. * This is then looked-up by the Cache.getURL and Cache.checkURL calls.
  57553. *
  57554. * @method Phaser.Cache#_resolveURL
  57555. * @private
  57556. * @param {string} url - The URL to resolve. This is appended to Loader.baseURL.
  57557. * @param {object} [data] - The data associated with the URL to be stored to the URL Map.
  57558. * @return {string} The resolved URL.
  57559. */
  57560. _resolveURL: function (url, data) {
  57561. if (!this.autoResolveURL)
  57562. {
  57563. return null;
  57564. }
  57565. this._urlResolver.src = this.game.load.baseURL + url;
  57566. this._urlTemp = this._urlResolver.src;
  57567. // Ensure no request is actually made
  57568. this._urlResolver.src = '';
  57569. // Record the URL to the map
  57570. if (data)
  57571. {
  57572. this._urlMap[this._urlTemp] = data;
  57573. }
  57574. return this._urlTemp;
  57575. },
  57576. /**
  57577. * Clears the cache. Removes every local cache object reference.
  57578. * If an object in the cache has a `destroy` method it will also be called.
  57579. *
  57580. * @method Phaser.Cache#destroy
  57581. */
  57582. destroy: function () {
  57583. for (var i = 0; i < this._cacheMap.length; i++)
  57584. {
  57585. var cache = this._cacheMap[i];
  57586. for (var key in cache)
  57587. {
  57588. if (key !== '__default' && key !== '__missing')
  57589. {
  57590. if (cache[key]['destroy'])
  57591. {
  57592. cache[key].destroy();
  57593. }
  57594. delete cache[key];
  57595. }
  57596. }
  57597. }
  57598. this._urlMap = null;
  57599. this._urlResolver = null;
  57600. this._urlTemp = null;
  57601. }
  57602. };
  57603. Phaser.Cache.prototype.constructor = Phaser.Cache;
  57604. /* jshint wsh:true */
  57605. /**
  57606. * @author Richard Davey <rich@photonstorm.com>
  57607. * @copyright 2016 Photon Storm Ltd.
  57608. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  57609. */
  57610. /**
  57611. * The Loader handles loading all external content such as Images, Sounds, Texture Atlases and data files.
  57612. *
  57613. * The loader uses a combination of tag loading (eg. Image elements) and XHR and provides progress and completion callbacks.
  57614. *
  57615. * Parallel loading (see {@link #enableParallel}) is supported and enabled by default.
  57616. * Load-before behavior of parallel resources is controlled by synchronization points as discussed in {@link #withSyncPoint}.
  57617. *
  57618. * Texture Atlases can be created with tools such as [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) and
  57619. * [Shoebox](http://renderhjs.net/shoebox/)
  57620. *
  57621. * @class Phaser.Loader
  57622. * @param {Phaser.Game} game - A reference to the currently running game.
  57623. */
  57624. Phaser.Loader = function (game) {
  57625. /**
  57626. * Local reference to game.
  57627. * @property {Phaser.Game} game
  57628. * @protected
  57629. */
  57630. this.game = game;
  57631. /**
  57632. * Local reference to the Phaser.Cache.
  57633. * @property {Phaser.Cache} cache
  57634. * @protected
  57635. */
  57636. this.cache = game.cache;
  57637. /**
  57638. * If true all calls to Loader.reset will be ignored. Useful if you need to create a load queue before swapping to a preloader state.
  57639. * @property {boolean} resetLocked
  57640. * @default
  57641. */
  57642. this.resetLocked = false;
  57643. /**
  57644. * True if the Loader is in the process of loading the queue.
  57645. * @property {boolean} isLoading
  57646. * @default
  57647. */
  57648. this.isLoading = false;
  57649. /**
  57650. * True if all assets in the queue have finished loading.
  57651. * @property {boolean} hasLoaded
  57652. * @default
  57653. */
  57654. this.hasLoaded = false;
  57655. /**
  57656. * You can optionally link a progress sprite with {@link Phaser.Loader#setPreloadSprite setPreloadSprite}.
  57657. *
  57658. * This property is an object containing: sprite, rect, direction, width and height
  57659. *
  57660. * @property {?object} preloadSprite
  57661. * @protected
  57662. */
  57663. this.preloadSprite = null;
  57664. /**
  57665. * The crossOrigin value applied to loaded images. Very often this needs to be set to 'anonymous'.
  57666. * @property {boolean|string} crossOrigin
  57667. * @default
  57668. */
  57669. this.crossOrigin = false;
  57670. /**
  57671. * If you want to append a URL before the path of any asset you can set this here.
  57672. * Useful if allowing the asset base url to be configured outside of the game code.
  57673. * The string _must_ end with a "/".
  57674. *
  57675. * @property {string} baseURL
  57676. */
  57677. this.baseURL = '';
  57678. /**
  57679. * The value of `path`, if set, is placed before any _relative_ file path given. For example:
  57680. *
  57681. * `load.path = "images/sprites/";
  57682. * load.image("ball", "ball.png");
  57683. * load.image("tree", "level1/oaktree.png");
  57684. * load.image("boom", "http://server.com/explode.png");`
  57685. *
  57686. * Would load the `ball` file from `images/sprites/ball.png` and the tree from
  57687. * `images/sprites/level1/oaktree.png` but the file `boom` would load from the URL
  57688. * given as it's an absolute URL.
  57689. *
  57690. * Please note that the path is added before the filename but *after* the baseURL (if set.)
  57691. *
  57692. * The string _must_ end with a "/".
  57693. *
  57694. * @property {string} path
  57695. */
  57696. this.path = '';
  57697. /**
  57698. * This event is dispatched when the loading process starts: before the first file has been requested,
  57699. * but after all the initial packs have been loaded.
  57700. *
  57701. * @property {Phaser.Signal} onLoadStart
  57702. */
  57703. this.onLoadStart = new Phaser.Signal();
  57704. /**
  57705. * This event is dispatched when the final file in the load queue has either loaded or failed.
  57706. *
  57707. * @property {Phaser.Signal} onLoadComplete
  57708. */
  57709. this.onLoadComplete = new Phaser.Signal();
  57710. /**
  57711. * This event is dispatched when an asset pack has either loaded or failed to load.
  57712. *
  57713. * This is called when the asset pack manifest file has loaded and successfully added its contents to the loader queue.
  57714. *
  57715. * Params: `(pack key, success?, total packs loaded, total packs)`
  57716. *
  57717. * @property {Phaser.Signal} onPackComplete
  57718. */
  57719. this.onPackComplete = new Phaser.Signal();
  57720. /**
  57721. * This event is dispatched immediately before a file starts loading.
  57722. * It's possible the file may fail (eg. download error, invalid format) after this event is sent.
  57723. *
  57724. * Params: `(progress, file key, file url)`
  57725. *
  57726. * @property {Phaser.Signal} onFileStart
  57727. */
  57728. this.onFileStart = new Phaser.Signal();
  57729. /**
  57730. * This event is dispatched when a file has either loaded or failed to load.
  57731. *
  57732. * Any function bound to this will receive the following parameters:
  57733. *
  57734. * progress, file key, success?, total loaded files, total files
  57735. *
  57736. * Where progress is a number between 1 and 100 (inclusive) representing the percentage of the load.
  57737. *
  57738. * @property {Phaser.Signal} onFileComplete
  57739. */
  57740. this.onFileComplete = new Phaser.Signal();
  57741. /**
  57742. * This event is dispatched when a file (or pack) errors as a result of the load request.
  57743. *
  57744. * For files it will be triggered before `onFileComplete`. For packs it will be triggered before `onPackComplete`.
  57745. *
  57746. * Params: `(file key, file)`
  57747. *
  57748. * @property {Phaser.Signal} onFileError
  57749. */
  57750. this.onFileError = new Phaser.Signal();
  57751. /**
  57752. * If true and if the browser supports XDomainRequest, it will be used in preference for XHR.
  57753. *
  57754. * This is only relevant for IE 9 and should _only_ be enabled for IE 9 clients when required by the server/CDN.
  57755. *
  57756. * @property {boolean} useXDomainRequest
  57757. * @deprecated This is only relevant for IE 9.
  57758. */
  57759. this.useXDomainRequest = false;
  57760. /**
  57761. * @private
  57762. * @property {boolean} _warnedAboutXDomainRequest - Control number of warnings for using XDR outside of IE 9.
  57763. */
  57764. this._warnedAboutXDomainRequest = false;
  57765. /**
  57766. * If true (the default) then parallel downloading will be enabled.
  57767. *
  57768. * To disable all parallel downloads this must be set to false prior to any resource being loaded.
  57769. *
  57770. * @property {boolean} enableParallel
  57771. */
  57772. this.enableParallel = true;
  57773. /**
  57774. * The number of concurrent / parallel resources to try and fetch at once.
  57775. *
  57776. * Many current browsers limit 6 requests per domain; this is slightly conservative.
  57777. *
  57778. * @property {integer} maxParallelDownloads
  57779. * @protected
  57780. */
  57781. this.maxParallelDownloads = 4;
  57782. /**
  57783. * A counter: if more than zero, files will be automatically added as a synchronization point.
  57784. * @property {integer} _withSyncPointDepth;
  57785. */
  57786. this._withSyncPointDepth = 0;
  57787. /**
  57788. * Contains all the information for asset files (including packs) to load.
  57789. *
  57790. * File/assets are only removed from the list after all loading completes.
  57791. *
  57792. * @property {file[]} _fileList
  57793. * @private
  57794. */
  57795. this._fileList = [];
  57796. /**
  57797. * Inflight files (or packs) that are being fetched/processed.
  57798. *
  57799. * This means that if there are any files in the flight queue there should still be processing
  57800. * going on; it should only be empty before or after loading.
  57801. *
  57802. * The files in the queue may have additional properties added to them,
  57803. * including `requestObject` which is normally the associated XHR.
  57804. *
  57805. * @property {file[]} _flightQueue
  57806. * @private
  57807. */
  57808. this._flightQueue = [];
  57809. /**
  57810. * The offset into the fileList past all the complete (loaded or error) entries.
  57811. *
  57812. * @property {integer} _processingHead
  57813. * @private
  57814. */
  57815. this._processingHead = 0;
  57816. /**
  57817. * True when the first file (not pack) has loading started.
  57818. * This used to to control dispatching `onLoadStart` which happens after any initial packs are loaded.
  57819. *
  57820. * @property {boolean} _initialPacksLoaded
  57821. * @private
  57822. */
  57823. this._fileLoadStarted = false;
  57824. /**
  57825. * Total packs seen - adjusted when a pack is added.
  57826. * @property {integer} _totalPackCount
  57827. * @private
  57828. */
  57829. this._totalPackCount = 0;
  57830. /**
  57831. * Total files seen - adjusted when a file is added.
  57832. * @property {integer} _totalFileCount
  57833. * @private
  57834. */
  57835. this._totalFileCount = 0;
  57836. /**
  57837. * Total packs loaded - adjusted just prior to `onPackComplete`.
  57838. * @property {integer} _loadedPackCount
  57839. * @private
  57840. */
  57841. this._loadedPackCount = 0;
  57842. /**
  57843. * Total files loaded - adjusted just prior to `onFileComplete`.
  57844. * @property {integer} _loadedFileCount
  57845. * @private
  57846. */
  57847. this._loadedFileCount = 0;
  57848. };
  57849. /**
  57850. * @constant
  57851. * @type {number}
  57852. */
  57853. Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY = 0;
  57854. /**
  57855. * @constant
  57856. * @type {number}
  57857. */
  57858. Phaser.Loader.TEXTURE_ATLAS_JSON_HASH = 1;
  57859. /**
  57860. * @constant
  57861. * @type {number}
  57862. */
  57863. Phaser.Loader.TEXTURE_ATLAS_XML_STARLING = 2;
  57864. /**
  57865. * @constant
  57866. * @type {number}
  57867. */
  57868. Phaser.Loader.PHYSICS_LIME_CORONA_JSON = 3;
  57869. /**
  57870. * @constant
  57871. * @type {number}
  57872. */
  57873. Phaser.Loader.PHYSICS_PHASER_JSON = 4;
  57874. /**
  57875. * @constant
  57876. * @type {number}
  57877. */
  57878. Phaser.Loader.TEXTURE_ATLAS_JSON_PYXEL = 5;
  57879. Phaser.Loader.prototype = {
  57880. /**
  57881. * Set a Sprite to be a "preload" sprite by passing it to this method.
  57882. *
  57883. * A "preload" sprite will have its width or height crop adjusted based on the percentage of the loader in real-time.
  57884. * This allows you to easily make loading bars for games.
  57885. *
  57886. * The sprite will automatically be made visible when calling this.
  57887. *
  57888. * @method Phaser.Loader#setPreloadSprite
  57889. * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite or image that will be cropped during the load.
  57890. * @param {number} [direction=0] - A value of zero means the sprite will be cropped horizontally, a value of 1 means its will be cropped vertically.
  57891. */
  57892. setPreloadSprite: function (sprite, direction) {
  57893. direction = direction || 0;
  57894. this.preloadSprite = { sprite: sprite, direction: direction, width: sprite.width, height: sprite.height, rect: null };
  57895. if (direction === 0)
  57896. {
  57897. // Horizontal rect
  57898. this.preloadSprite.rect = new Phaser.Rectangle(0, 0, 1, sprite.height);
  57899. }
  57900. else
  57901. {
  57902. // Vertical rect
  57903. this.preloadSprite.rect = new Phaser.Rectangle(0, 0, sprite.width, 1);
  57904. }
  57905. sprite.crop(this.preloadSprite.rect);
  57906. sprite.visible = true;
  57907. },
  57908. /**
  57909. * Called automatically by ScaleManager when the game resizes in RESIZE scalemode.
  57910. *
  57911. * This can be used to adjust the preloading sprite size, eg.
  57912. *
  57913. * @method Phaser.Loader#resize
  57914. * @protected
  57915. */
  57916. resize: function () {
  57917. if (this.preloadSprite && this.preloadSprite.height !== this.preloadSprite.sprite.height)
  57918. {
  57919. this.preloadSprite.rect.height = this.preloadSprite.sprite.height;
  57920. }
  57921. },
  57922. /**
  57923. * Check whether a file/asset with a specific key is queued to be loaded.
  57924. *
  57925. * To access a loaded asset use Phaser.Cache, eg. {@link Phaser.Cache#checkImageKey}
  57926. *
  57927. * @method Phaser.Loader#checkKeyExists
  57928. * @param {string} type - The type asset you want to check.
  57929. * @param {string} key - Key of the asset you want to check.
  57930. * @return {boolean} Return true if exists, otherwise return false.
  57931. */
  57932. checkKeyExists: function (type, key) {
  57933. return this.getAssetIndex(type, key) > -1;
  57934. },
  57935. /**
  57936. * Get the queue-index of the file/asset with a specific key.
  57937. *
  57938. * Only assets in the download file queue will be found.
  57939. *
  57940. * @method Phaser.Loader#getAssetIndex
  57941. * @param {string} type - The type asset you want to check.
  57942. * @param {string} key - Key of the asset you want to check.
  57943. * @return {number} The index of this key in the filelist, or -1 if not found.
  57944. * The index may change and should only be used immediately following this call
  57945. */
  57946. getAssetIndex: function (type, key) {
  57947. var bestFound = -1;
  57948. for (var i = 0; i < this._fileList.length; i++)
  57949. {
  57950. var file = this._fileList[i];
  57951. if (file.type === type && file.key === key)
  57952. {
  57953. bestFound = i;
  57954. // An already loaded/loading file may be superceded.
  57955. if (!file.loaded && !file.loading)
  57956. {
  57957. break;
  57958. }
  57959. }
  57960. }
  57961. return bestFound;
  57962. },
  57963. /**
  57964. * Find a file/asset with a specific key.
  57965. *
  57966. * Only assets in the download file queue will be found.
  57967. *
  57968. * @method Phaser.Loader#getAsset
  57969. * @param {string} type - The type asset you want to check.
  57970. * @param {string} key - Key of the asset you want to check.
  57971. * @return {any} Returns an object if found that has 2 properties: `index` and `file`; otherwise a non-true value is returned.
  57972. * The index may change and should only be used immediately following this call.
  57973. */
  57974. getAsset: function (type, key) {
  57975. var fileIndex = this.getAssetIndex(type, key);
  57976. if (fileIndex > -1)
  57977. {
  57978. return { index: fileIndex, file: this._fileList[fileIndex] };
  57979. }
  57980. return false;
  57981. },
  57982. /**
  57983. * Reset the loader and clear any queued assets. If `Loader.resetLocked` is true this operation will abort.
  57984. *
  57985. * This will abort any loading and clear any queued assets.
  57986. *
  57987. * Optionally you can clear any associated events.
  57988. *
  57989. * @method Phaser.Loader#reset
  57990. * @protected
  57991. * @param {boolean} [hard=false] - If true then the preload sprite and other artifacts may also be cleared.
  57992. * @param {boolean} [clearEvents=false] - If true then the all Loader signals will have removeAll called on them.
  57993. */
  57994. reset: function (hard, clearEvents) {
  57995. if (clearEvents === undefined) { clearEvents = false; }
  57996. if (this.resetLocked)
  57997. {
  57998. return;
  57999. }
  58000. if (hard)
  58001. {
  58002. this.preloadSprite = null;
  58003. }
  58004. this.isLoading = false;
  58005. this._processingHead = 0;
  58006. this._fileList.length = 0;
  58007. this._flightQueue.length = 0;
  58008. this._fileLoadStarted = false;
  58009. this._totalFileCount = 0;
  58010. this._totalPackCount = 0;
  58011. this._loadedPackCount = 0;
  58012. this._loadedFileCount = 0;
  58013. if (clearEvents)
  58014. {
  58015. this.onLoadStart.removeAll();
  58016. this.onLoadComplete.removeAll();
  58017. this.onPackComplete.removeAll();
  58018. this.onFileStart.removeAll();
  58019. this.onFileComplete.removeAll();
  58020. this.onFileError.removeAll();
  58021. }
  58022. },
  58023. /**
  58024. * Internal function that adds a new entry to the file list. Do not call directly.
  58025. *
  58026. * @method Phaser.Loader#addToFileList
  58027. * @protected
  58028. * @param {string} type - The type of resource to add to the list (image, audio, xml, etc).
  58029. * @param {string} key - The unique Cache ID key of this resource.
  58030. * @param {string} [url] - The URL the asset will be loaded from.
  58031. * @param {object} [properties=(none)] - Any additional properties needed to load the file. These are added directly to the added file object and overwrite any defaults.
  58032. * @param {boolean} [overwrite=false] - If true then this will overwrite a file asset of the same type/key. Otherwise it will only add a new asset. If overwrite is true, and the asset is already being loaded (or has been loaded), then it is appended instead.
  58033. * @param {string} [extension] - If no URL is given the Loader will sometimes auto-generate the URL based on the key, using this as the extension.
  58034. * @return {Phaser.Loader} This instance of the Phaser Loader.
  58035. */
  58036. addToFileList: function (type, key, url, properties, overwrite, extension) {
  58037. if (overwrite === undefined) { overwrite = false; }
  58038. if (key === undefined || key === '')
  58039. {
  58040. console.warn("Phaser.Loader: Invalid or no key given of type " + type);
  58041. return this;
  58042. }
  58043. if (url === undefined || url === null)
  58044. {
  58045. if (extension)
  58046. {
  58047. url = key + extension;
  58048. }
  58049. else
  58050. {
  58051. console.warn("Phaser.Loader: No URL given for file type: " + type + " key: " + key);
  58052. return this;
  58053. }
  58054. }
  58055. var file = {
  58056. type: type,
  58057. key: key,
  58058. path: this.path,
  58059. url: url,
  58060. syncPoint: this._withSyncPointDepth > 0,
  58061. data: null,
  58062. loading: false,
  58063. loaded: false,
  58064. error: false
  58065. };
  58066. if (properties)
  58067. {
  58068. for (var prop in properties)
  58069. {
  58070. file[prop] = properties[prop];
  58071. }
  58072. }
  58073. var fileIndex = this.getAssetIndex(type, key);
  58074. if (overwrite && fileIndex > -1)
  58075. {
  58076. var currentFile = this._fileList[fileIndex];
  58077. if (!currentFile.loading && !currentFile.loaded)
  58078. {
  58079. this._fileList[fileIndex] = file;
  58080. }
  58081. else
  58082. {
  58083. this._fileList.push(file);
  58084. this._totalFileCount++;
  58085. }
  58086. }
  58087. else if (fileIndex === -1)
  58088. {
  58089. this._fileList.push(file);
  58090. this._totalFileCount++;
  58091. }
  58092. return this;
  58093. },
  58094. /**
  58095. * Internal function that replaces an existing entry in the file list with a new one. Do not call directly.
  58096. *
  58097. * @method Phaser.Loader#replaceInFileList
  58098. * @protected
  58099. * @param {string} type - The type of resource to add to the list (image, audio, xml, etc).
  58100. * @param {string} key - The unique Cache ID key of this resource.
  58101. * @param {string} url - The URL the asset will be loaded from.
  58102. * @param {object} properties - Any additional properties needed to load the file.
  58103. */
  58104. replaceInFileList: function (type, key, url, properties) {
  58105. return this.addToFileList(type, key, url, properties, true);
  58106. },
  58107. /**
  58108. * Add a JSON resource pack ('packfile') to the Loader.
  58109. *
  58110. * A packfile is a JSON file that contains a list of assets to the be loaded.
  58111. * Please see the example 'loader/asset pack' in the Phaser Examples repository.
  58112. *
  58113. * Packs are always put before the first non-pack file that is not loaded / loading.
  58114. *
  58115. * This means that all packs added before any loading has started are added to the front
  58116. * of the file queue, in the order added.
  58117. *
  58118. * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
  58119. *
  58120. * The URL of the packfile can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
  58121. *
  58122. * @method Phaser.Loader#pack
  58123. * @param {string} key - Unique asset key of this resource pack.
  58124. * @param {string} [url] - URL of the Asset Pack JSON file. If you wish to pass a json object instead set this to null and pass the object as the data parameter.
  58125. * @param {object} [data] - The Asset Pack JSON data. Use this to pass in a json data object rather than loading it from a URL. TODO
  58126. * @param {object} [callbackContext=(loader)] - Some Loader operations, like Binary and Script require a context for their callbacks. Pass the context here.
  58127. * @return {Phaser.Loader} This Loader instance.
  58128. */
  58129. pack: function (key, url, data, callbackContext) {
  58130. if (url === undefined) { url = null; }
  58131. if (data === undefined) { data = null; }
  58132. if (callbackContext === undefined) { callbackContext = null; }
  58133. if (!url && !data)
  58134. {
  58135. console.warn('Phaser.Loader.pack - Both url and data are null. One must be set.');
  58136. return this;
  58137. }
  58138. var pack = {
  58139. type: 'packfile',
  58140. key: key,
  58141. url: url,
  58142. path: this.path,
  58143. syncPoint: true,
  58144. data: null,
  58145. loading: false,
  58146. loaded: false,
  58147. error: false,
  58148. callbackContext: callbackContext
  58149. };
  58150. // A data object has been given
  58151. if (data)
  58152. {
  58153. if (typeof data === 'string')
  58154. {
  58155. data = JSON.parse(data);
  58156. }
  58157. pack.data = data || {};
  58158. // Already consider 'loaded'
  58159. pack.loaded = true;
  58160. }
  58161. // Add before first non-pack/no-loaded ~ last pack from start prior to loading
  58162. // (Read one past for splice-to-end)
  58163. for (var i = 0; i < this._fileList.length + 1; i++)
  58164. {
  58165. var file = this._fileList[i];
  58166. if (!file || (!file.loaded && !file.loading && file.type !== 'packfile'))
  58167. {
  58168. this._fileList.splice(i, 0, pack);
  58169. this._totalPackCount++;
  58170. break;
  58171. }
  58172. }
  58173. return this;
  58174. },
  58175. /**
  58176. * Adds an Image to the current load queue.
  58177. *
  58178. * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts.
  58179. *
  58180. * Phaser can load all common image types: png, jpg, gif and any other format the browser can natively handle.
  58181. *
  58182. * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
  58183. *
  58184. * Retrieve the image via `Cache.getImage(key)`
  58185. *
  58186. * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
  58187. *
  58188. * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien"
  58189. * and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension.
  58190. * If you do not desire this action then provide a URL.
  58191. *
  58192. * @method Phaser.Loader#image
  58193. * @param {string} key - Unique asset key of this image file.
  58194. * @param {string} [url] - URL of an image file. If undefined or `null` the url will be set to `<key>.png`, i.e. if `key` was "alien" then the URL will be "alien.png".
  58195. * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it.
  58196. * @return {Phaser.Loader} This Loader instance.
  58197. */
  58198. image: function (key, url, overwrite) {
  58199. return this.addToFileList('image', key, url, undefined, overwrite, '.png');
  58200. },
  58201. /**
  58202. * Adds an array of images to the current load queue.
  58203. *
  58204. * It works by passing each element of the array to the Loader.image method.
  58205. *
  58206. * The files are **not** loaded immediately after calling this method. The files are added to the queue ready to be loaded when the loader starts.
  58207. *
  58208. * Phaser can load all common image types: png, jpg, gif and any other format the browser can natively handle.
  58209. *
  58210. * The keys must be unique Strings. They are used to add the files to the Phaser.Cache upon successful load.
  58211. *
  58212. * Retrieve the images via `Cache.getImage(key)`
  58213. *
  58214. * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
  58215. *
  58216. * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien"
  58217. * and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension.
  58218. * If you do not desire this action then provide a URL.
  58219. *
  58220. * @method Phaser.Loader#images
  58221. * @param {array} keys - An array of unique asset keys of the image files.
  58222. * @param {array} [urls] - Optional array of URLs. If undefined or `null` the url will be set to `<key>.png`, i.e. if `key` was "alien" then the URL will be "alien.png". If provided the URLs array length must match the keys array length.
  58223. * @return {Phaser.Loader} This Loader instance.
  58224. */
  58225. images: function (keys, urls) {
  58226. if (Array.isArray(urls))
  58227. {
  58228. for (var i = 0; i < keys.length; i++)
  58229. {
  58230. this.image(keys[i], urls[i]);
  58231. }
  58232. }
  58233. else
  58234. {
  58235. for (var i = 0; i < keys.length; i++)
  58236. {
  58237. this.image(keys[i]);
  58238. }
  58239. }
  58240. return this;
  58241. },
  58242. /**
  58243. * Adds a Text file to the current load queue.
  58244. *
  58245. * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts.
  58246. *
  58247. * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
  58248. *
  58249. * Retrieve the file via `Cache.getText(key)`
  58250. *
  58251. * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
  58252. *
  58253. * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien"
  58254. * and no URL is given then the Loader will set the URL to be "alien.txt". It will always add `.txt` as the extension.
  58255. * If you do not desire this action then provide a URL.
  58256. *
  58257. * @method Phaser.Loader#text
  58258. * @param {string} key - Unique asset key of the text file.
  58259. * @param {string} [url] - URL of the text file. If undefined or `null` the url will be set to `<key>.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt".
  58260. * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it.
  58261. * @return {Phaser.Loader} This Loader instance.
  58262. */
  58263. text: function (key, url, overwrite) {
  58264. return this.addToFileList('text', key, url, undefined, overwrite, '.txt');
  58265. },
  58266. /**
  58267. * Adds a JSON file to the current load queue.
  58268. *
  58269. * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts.
  58270. *
  58271. * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
  58272. *
  58273. * Retrieve the file via `Cache.getJSON(key)`. JSON files are automatically parsed upon load.
  58274. * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the text file as needed.
  58275. *
  58276. * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
  58277. *
  58278. * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien"
  58279. * and no URL is given then the Loader will set the URL to be "alien.json". It will always add `.json` as the extension.
  58280. * If you do not desire this action then provide a URL.
  58281. *
  58282. * @method Phaser.Loader#json
  58283. * @param {string} key - Unique asset key of the json file.
  58284. * @param {string} [url] - URL of the JSON file. If undefined or `null` the url will be set to `<key>.json`, i.e. if `key` was "alien" then the URL will be "alien.json".
  58285. * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it.
  58286. * @return {Phaser.Loader} This Loader instance.
  58287. */
  58288. json: function (key, url, overwrite) {
  58289. return this.addToFileList('json', key, url, undefined, overwrite, '.json');
  58290. },
  58291. /**
  58292. * Adds a fragment shader file to the current load queue.
  58293. *
  58294. * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts.
  58295. *
  58296. * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
  58297. *
  58298. * Retrieve the file via `Cache.getShader(key)`.
  58299. *
  58300. * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
  58301. *
  58302. * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "blur"
  58303. * and no URL is given then the Loader will set the URL to be "blur.frag". It will always add `.frag` as the extension.
  58304. * If you do not desire this action then provide a URL.
  58305. *
  58306. * @method Phaser.Loader#shader
  58307. * @param {string} key - Unique asset key of the fragment file.
  58308. * @param {string} [url] - URL of the fragment file. If undefined or `null` the url will be set to `<key>.frag`, i.e. if `key` was "blur" then the URL will be "blur.frag".
  58309. * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it.
  58310. * @return {Phaser.Loader} This Loader instance.
  58311. */
  58312. shader: function (key, url, overwrite) {
  58313. return this.addToFileList('shader', key, url, undefined, overwrite, '.frag');
  58314. },
  58315. /**
  58316. * Adds an XML file to the current load queue.
  58317. *
  58318. * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts.
  58319. *
  58320. * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
  58321. *
  58322. * Retrieve the file via `Cache.getXML(key)`.
  58323. *
  58324. * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
  58325. *
  58326. * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien"
  58327. * and no URL is given then the Loader will set the URL to be "alien.xml". It will always add `.xml` as the extension.
  58328. * If you do not desire this action then provide a URL.
  58329. *
  58330. * @method Phaser.Loader#xml
  58331. * @param {string} key - Unique asset key of the xml file.
  58332. * @param {string} [url] - URL of the XML file. If undefined or `null` the url will be set to `<key>.xml`, i.e. if `key` was "alien" then the URL will be "alien.xml".
  58333. * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it.
  58334. * @return {Phaser.Loader} This Loader instance.
  58335. */
  58336. xml: function (key, url, overwrite) {
  58337. return this.addToFileList('xml', key, url, undefined, overwrite, '.xml');
  58338. },
  58339. /**
  58340. * Adds a JavaScript file to the current load queue.
  58341. *
  58342. * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts.
  58343. *
  58344. * The key must be a unique String.
  58345. *
  58346. * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
  58347. *
  58348. * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien"
  58349. * and no URL is given then the Loader will set the URL to be "alien.js". It will always add `.js` as the extension.
  58350. * If you do not desire this action then provide a URL.
  58351. *
  58352. * Upon successful load the JavaScript is automatically turned into a script tag and executed, so be careful what you load!
  58353. *
  58354. * A callback, which will be invoked as the script tag has been created, can also be specified.
  58355. * The callback must return relevant `data`.
  58356. *
  58357. * @method Phaser.Loader#script
  58358. * @param {string} key - Unique asset key of the script file.
  58359. * @param {string} [url] - URL of the JavaScript file. If undefined or `null` the url will be set to `<key>.js`, i.e. if `key` was "alien" then the URL will be "alien.js".
  58360. * @param {function} [callback=(none)] - Optional callback that will be called after the script tag has loaded, so you can perform additional processing.
  58361. * @param {object} [callbackContext=(loader)] - The context under which the callback will be applied. If not specified it will use the Phaser Loader as the context.
  58362. * @return {Phaser.Loader} This Loader instance.
  58363. */
  58364. script: function (key, url, callback, callbackContext) {
  58365. if (callback === undefined) { callback = false; }
  58366. if (callback !== false && callbackContext === undefined) { callbackContext = this; }
  58367. return this.addToFileList('script', key, url, { syncPoint: true, callback: callback, callbackContext: callbackContext }, false, '.js');
  58368. },
  58369. /**
  58370. * Adds a binary file to the current load queue.
  58371. *
  58372. * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts.
  58373. *
  58374. * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
  58375. *
  58376. * Retrieve the file via `Cache.getBinary(key)`.
  58377. *
  58378. * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
  58379. *
  58380. * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien"
  58381. * and no URL is given then the Loader will set the URL to be "alien.bin". It will always add `.bin` as the extension.
  58382. * If you do not desire this action then provide a URL.
  58383. *
  58384. * It will be loaded via xhr with a responseType of "arraybuffer". You can specify an optional callback to process the file after load.
  58385. * When the callback is called it will be passed 2 parameters: the key of the file and the file data.
  58386. *
  58387. * WARNING: If a callback is specified the data will be set to whatever it returns. Always return the data object, even if you didn't modify it.
  58388. *
  58389. * @method Phaser.Loader#binary
  58390. * @param {string} key - Unique asset key of the binary file.
  58391. * @param {string} [url] - URL of the binary file. If undefined or `null` the url will be set to `<key>.bin`, i.e. if `key` was "alien" then the URL will be "alien.bin".
  58392. * @param {function} [callback=(none)] - Optional callback that will be passed the file after loading, so you can perform additional processing on it.
  58393. * @param {object} [callbackContext] - The context under which the callback will be applied. If not specified it will use the callback itself as the context.
  58394. * @return {Phaser.Loader} This Loader instance.
  58395. */
  58396. binary: function (key, url, callback, callbackContext) {
  58397. if (callback === undefined) { callback = false; }
  58398. // Why is the default callback context the ..callback?
  58399. if (callback !== false && callbackContext === undefined) { callbackContext = callback; }
  58400. return this.addToFileList('binary', key, url, { callback: callback, callbackContext: callbackContext }, false, '.bin');
  58401. },
  58402. /**
  58403. * Adds a Sprite Sheet to the current load queue.
  58404. *
  58405. * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts.
  58406. *
  58407. * To clarify the terminology that Phaser uses: A Sprite Sheet is an image containing frames, usually of an animation, that are all equal
  58408. * dimensions and often in sequence. For example if the frame size is 32x32 then every frame in the sprite sheet will be that size.
  58409. * Sometimes (outside of Phaser) the term "sprite sheet" is used to refer to a texture atlas.
  58410. * A Texture Atlas works by packing together images as best it can, using whatever frame sizes it likes, often with cropping and trimming
  58411. * the frames in the process. Software such as Texture Packer, Flash CC or Shoebox all generate texture atlases, not sprite sheets.
  58412. * If you've got an atlas then use `Loader.atlas` instead.
  58413. *
  58414. * The key must be a unique String. It is used to add the image to the Phaser.Cache upon successful load.
  58415. *
  58416. * Retrieve the file via `Cache.getImage(key)`. Sprite sheets, being image based, live in the same Cache as all other Images.
  58417. *
  58418. * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
  58419. *
  58420. * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien"
  58421. * and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension.
  58422. * If you do not desire this action then provide a URL.
  58423. *
  58424. * @method Phaser.Loader#spritesheet
  58425. * @param {string} key - Unique asset key of the sheet file.
  58426. * @param {string} url - URL of the sprite sheet file. If undefined or `null` the url will be set to `<key>.png`, i.e. if `key` was "alien" then the URL will be "alien.png".
  58427. * @param {number} frameWidth - Width in pixels of a single frame in the sprite sheet.
  58428. * @param {number} frameHeight - Height in pixels of a single frame in the sprite sheet.
  58429. * @param {number} [frameMax=-1] - How many frames in this sprite sheet. If not specified it will divide the whole image into frames.
  58430. * @param {number} [margin=0] - If the frames have been drawn with a margin, specify the amount here.
  58431. * @param {number} [spacing=0] - If the frames have been drawn with spacing between them, specify the amount here.
  58432. * @return {Phaser.Loader} This Loader instance.
  58433. */
  58434. spritesheet: function (key, url, frameWidth, frameHeight, frameMax, margin, spacing) {
  58435. if (frameMax === undefined) { frameMax = -1; }
  58436. if (margin === undefined) { margin = 0; }
  58437. if (spacing === undefined) { spacing = 0; }
  58438. return this.addToFileList('spritesheet', key, url, { frameWidth: frameWidth, frameHeight: frameHeight, frameMax: frameMax, margin: margin, spacing: spacing }, false, '.png');
  58439. },
  58440. /**
  58441. * Adds an audio file to the current load queue.
  58442. *
  58443. * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts.
  58444. *
  58445. * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
  58446. *
  58447. * Retrieve the file via `Cache.getSound(key)`.
  58448. *
  58449. * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
  58450. *
  58451. * Mobile warning: There are some mobile devices (certain iPad 2 and iPad Mini revisions) that cannot play 48000 Hz audio.
  58452. * When they try to play the audio becomes extremely distorted and buzzes, eventually crashing the sound system.
  58453. * The solution is to use a lower encoding rate such as 44100 Hz.
  58454. *
  58455. * @method Phaser.Loader#audio
  58456. * @param {string} key - Unique asset key of the audio file.
  58457. * @param {string|string[]|object[]} urls - Either a single string or an array of URIs or pairs of `{uri: .., type: ..}`.
  58458. * If an array is specified then the first URI (or URI + mime pair) that is device-compatible will be selected.
  58459. * For example: `"jump.mp3"`, `['jump.mp3', 'jump.ogg', 'jump.m4a']`, or `[{uri: "data:<opus_resource>", type: 'opus'}, 'fallback.mp3']`.
  58460. * BLOB and DATA URIs can be used but only support automatic detection when used in the pair form; otherwise the format must be manually checked before adding the resource.
  58461. * @param {boolean} [autoDecode=true] - When using Web Audio the audio files can either be decoded at load time or run-time.
  58462. * Audio files can't be played until they are decoded and, if specified, this enables immediate decoding. Decoding is a non-blocking async process, however it consumes huge amounts of CPU time on mobiles especially.
  58463. * @return {Phaser.Loader} This Loader instance.
  58464. */
  58465. audio: function (key, urls, autoDecode) {
  58466. if (this.game.sound.noAudio)
  58467. {
  58468. return this;
  58469. }
  58470. if (autoDecode === undefined) { autoDecode = true; }
  58471. if (typeof urls === 'string')
  58472. {
  58473. urls = [urls];
  58474. }
  58475. return this.addToFileList('audio', key, urls, { buffer: null, autoDecode: autoDecode });
  58476. },
  58477. /**
  58478. * Adds an audio sprite file to the current load queue.
  58479. *
  58480. * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts.
  58481. *
  58482. * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
  58483. *
  58484. * Audio Sprites are a combination of audio files and a JSON configuration.
  58485. *
  58486. * The JSON follows the format of that created by https://github.com/tonistiigi/audiosprite
  58487. *
  58488. * Retrieve the file via `Cache.getSoundData(key)`.
  58489. *
  58490. * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
  58491. *
  58492. * @method Phaser.Loader#audiosprite
  58493. * @param {string} key - Unique asset key of the audio file.
  58494. * @param {Array|string} urls - An array containing the URLs of the audio files, i.e.: [ 'audiosprite.mp3', 'audiosprite.ogg', 'audiosprite.m4a' ] or a single string containing just one URL.
  58495. * @param {string} [jsonURL=null] - The URL of the audiosprite configuration JSON object. If you wish to pass the data directly set this parameter to null.
  58496. * @param {string|object} [jsonData=null] - A JSON object or string containing the audiosprite configuration data. This is ignored if jsonURL is not null.
  58497. * @param {boolean} [autoDecode=true] - When using Web Audio the audio files can either be decoded at load time or run-time.
  58498. * Audio files can't be played until they are decoded and, if specified, this enables immediate decoding. Decoding is a non-blocking async process, however it consumes huge amounts of CPU time on mobiles especially.
  58499. * @return {Phaser.Loader} This Loader instance.
  58500. */
  58501. audioSprite: function (key, urls, jsonURL, jsonData, autoDecode) {
  58502. if (this.game.sound.noAudio)
  58503. {
  58504. return this;
  58505. }
  58506. if (jsonURL === undefined) { jsonURL = null; }
  58507. if (jsonData === undefined) { jsonData = null; }
  58508. if (autoDecode === undefined) { autoDecode = true; }
  58509. this.audio(key, urls, autoDecode);
  58510. if (jsonURL)
  58511. {
  58512. this.json(key + '-audioatlas', jsonURL);
  58513. }
  58514. else if (jsonData)
  58515. {
  58516. if (typeof jsonData === 'string')
  58517. {
  58518. jsonData = JSON.parse(jsonData);
  58519. }
  58520. this.cache.addJSON(key + '-audioatlas', '', jsonData);
  58521. }
  58522. else
  58523. {
  58524. console.warn('Phaser.Loader.audiosprite - You must specify either a jsonURL or provide a jsonData object');
  58525. }
  58526. return this;
  58527. },
  58528. /**
  58529. * A legacy alias for Loader.audioSprite. Please see that method for documentation.
  58530. *
  58531. * @method Phaser.Loader#audiosprite
  58532. * @param {string} key - Unique asset key of the audio file.
  58533. * @param {Array|string} urls - An array containing the URLs of the audio files, i.e.: [ 'audiosprite.mp3', 'audiosprite.ogg', 'audiosprite.m4a' ] or a single string containing just one URL.
  58534. * @param {string} [jsonURL=null] - The URL of the audiosprite configuration JSON object. If you wish to pass the data directly set this parameter to null.
  58535. * @param {string|object} [jsonData=null] - A JSON object or string containing the audiosprite configuration data. This is ignored if jsonURL is not null.
  58536. * @param {boolean} [autoDecode=true] - When using Web Audio the audio files can either be decoded at load time or run-time.
  58537. * Audio files can't be played until they are decoded and, if specified, this enables immediate decoding. Decoding is a non-blocking async process, however it consumes huge amounts of CPU time on mobiles especially.
  58538. * @return {Phaser.Loader} This Loader instance.
  58539. */
  58540. audiosprite: function (key, urls, jsonURL, jsonData, autoDecode) {
  58541. return this.audioSprite(key, urls, jsonURL, jsonData, autoDecode);
  58542. },
  58543. /**
  58544. * Adds a video file to the current load queue.
  58545. *
  58546. * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts.
  58547. *
  58548. * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
  58549. *
  58550. * Retrieve the file via `Cache.getVideo(key)`.
  58551. *
  58552. * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
  58553. *
  58554. * You don't need to preload a video in order to play it in your game. See `Video.createVideoFromURL` for details.
  58555. *
  58556. * @method Phaser.Loader#video
  58557. * @param {string} key - Unique asset key of the video file.
  58558. * @param {string|string[]|object[]} urls - Either a single string or an array of URIs or pairs of `{uri: .., type: ..}`.
  58559. * If an array is specified then the first URI (or URI + mime pair) that is device-compatible will be selected.
  58560. * For example: `"boom.mp4"`, `['boom.mp4', 'boom.ogg', 'boom.webm']`, or `[{uri: "data:<opus_resource>", type: 'opus'}, 'fallback.mp4']`.
  58561. * BLOB and DATA URIs can be used but only support automatic detection when used in the pair form; otherwise the format must be manually checked before adding the resource.
  58562. * @param {string} [loadEvent='canplaythrough'] - This sets the Video source event to listen for before the load is considered complete.
  58563. * 'canplaythrough' implies the video has downloaded enough, and bandwidth is high enough that it can be played to completion.
  58564. * 'canplay' implies the video has downloaded enough to start playing, but not necessarily to finish.
  58565. * 'loadeddata' just makes sure that the video meta data and first frame have downloaded. Phaser uses this value automatically if the
  58566. * browser is detected as being Firefox and no `loadEvent` is given, otherwise it defaults to `canplaythrough`.
  58567. * @param {boolean} [asBlob=false] - Video files can either be loaded via the creation of a video element which has its src property set.
  58568. * Or they can be loaded via xhr, stored as binary data in memory and then converted to a Blob. This isn't supported in IE9 or Android 2.
  58569. * If you need to have the same video playing at different times across multiple Sprites then you need to load it as a Blob.
  58570. * @return {Phaser.Loader} This Loader instance.
  58571. */
  58572. video: function (key, urls, loadEvent, asBlob) {
  58573. if (loadEvent === undefined)
  58574. {
  58575. if (this.game.device.firefox)
  58576. {
  58577. loadEvent = 'loadeddata';
  58578. }
  58579. else
  58580. {
  58581. loadEvent = 'canplaythrough';
  58582. }
  58583. }
  58584. if (asBlob === undefined) { asBlob = false; }
  58585. if (typeof urls === 'string')
  58586. {
  58587. urls = [urls];
  58588. }
  58589. return this.addToFileList('video', key, urls, { buffer: null, asBlob: asBlob, loadEvent: loadEvent });
  58590. },
  58591. /**
  58592. * Adds a Tile Map data file to the current load queue.
  58593. *
  58594. * You can choose to either load the data externally, by providing a URL to a json file.
  58595. * Or you can pass in a JSON object or String via the `data` parameter.
  58596. * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache.
  58597. *
  58598. * If a URL is provided the file is **not** loaded immediately after calling this method, but is added to the load queue.
  58599. *
  58600. * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
  58601. *
  58602. * Retrieve the file via `Cache.getTilemapData(key)`. JSON files are automatically parsed upon load.
  58603. * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the text file as needed.
  58604. *
  58605. * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
  58606. *
  58607. * If the URL isn't specified and no data is given then the Loader will take the key and create a filename from that.
  58608. * For example if the key is "level1" and no URL or data is given then the Loader will set the URL to be "level1.json".
  58609. * If you set the format to be Tilemap.CSV it will set the URL to be "level1.csv" instead.
  58610. *
  58611. * If you do not desire this action then provide a URL or data object.
  58612. *
  58613. * @method Phaser.Loader#tilemap
  58614. * @param {string} key - Unique asset key of the tilemap data.
  58615. * @param {string} [url] - URL of the tile map file. If undefined or `null` and no data is given the url will be set to `<key>.json`, i.e. if `key` was "level1" then the URL will be "level1.json".
  58616. * @param {object|string} [data] - An optional JSON data object. If given then the url is ignored and this JSON object is used for map data instead.
  58617. * @param {number} [format=Phaser.Tilemap.CSV] - The format of the map data. Either Phaser.Tilemap.CSV or Phaser.Tilemap.TILED_JSON.
  58618. * @return {Phaser.Loader} This Loader instance.
  58619. */
  58620. tilemap: function (key, url, data, format) {
  58621. if (url === undefined) { url = null; }
  58622. if (data === undefined) { data = null; }
  58623. if (format === undefined) { format = Phaser.Tilemap.CSV; }
  58624. if (!url && !data)
  58625. {
  58626. if (format === Phaser.Tilemap.CSV)
  58627. {
  58628. url = key + '.csv';
  58629. }
  58630. else
  58631. {
  58632. url = key + '.json';
  58633. }
  58634. }
  58635. // A map data object has been given
  58636. if (data)
  58637. {
  58638. switch (format)
  58639. {
  58640. // A csv string or object has been given
  58641. case Phaser.Tilemap.CSV:
  58642. break;
  58643. // A json string or object has been given
  58644. case Phaser.Tilemap.TILED_JSON:
  58645. if (typeof data === 'string')
  58646. {
  58647. data = JSON.parse(data);
  58648. }
  58649. break;
  58650. }
  58651. this.cache.addTilemap(key, null, data, format);
  58652. }
  58653. else
  58654. {
  58655. this.addToFileList('tilemap', key, url, { format: format });
  58656. }
  58657. return this;
  58658. },
  58659. /**
  58660. * Adds a physics data file to the current load queue.
  58661. *
  58662. * The data must be in `Lime + Corona` JSON format. [Physics Editor](https://www.codeandweb.com) by code'n'web exports in this format natively.
  58663. *
  58664. * You can choose to either load the data externally, by providing a URL to a json file.
  58665. * Or you can pass in a JSON object or String via the `data` parameter.
  58666. * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache.
  58667. *
  58668. * If a URL is provided the file is **not** loaded immediately after calling this method, but is added to the load queue.
  58669. *
  58670. * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
  58671. *
  58672. * Retrieve the file via `Cache.getJSON(key)`. JSON files are automatically parsed upon load.
  58673. * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the text file as needed.
  58674. *
  58675. * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
  58676. *
  58677. * If the URL isn't specified and no data is given then the Loader will take the key and create a filename from that.
  58678. * For example if the key is "alien" and no URL or data is given then the Loader will set the URL to be "alien.json".
  58679. * It will always use `.json` as the extension.
  58680. *
  58681. * If you do not desire this action then provide a URL or data object.
  58682. *
  58683. * @method Phaser.Loader#physics
  58684. * @param {string} key - Unique asset key of the physics json data.
  58685. * @param {string} [url] - URL of the physics data file. If undefined or `null` and no data is given the url will be set to `<key>.json`, i.e. if `key` was "alien" then the URL will be "alien.json".
  58686. * @param {object|string} [data] - An optional JSON data object. If given then the url is ignored and this JSON object is used for physics data instead.
  58687. * @param {string} [format=Phaser.Physics.LIME_CORONA_JSON] - The format of the physics data.
  58688. * @return {Phaser.Loader} This Loader instance.
  58689. */
  58690. physics: function (key, url, data, format) {
  58691. if (url === undefined) { url = null; }
  58692. if (data === undefined) { data = null; }
  58693. if (format === undefined) { format = Phaser.Physics.LIME_CORONA_JSON; }
  58694. if (!url && !data)
  58695. {
  58696. url = key + '.json';
  58697. }
  58698. // A map data object has been given
  58699. if (data)
  58700. {
  58701. if (typeof data === 'string')
  58702. {
  58703. data = JSON.parse(data);
  58704. }
  58705. this.cache.addPhysicsData(key, null, data, format);
  58706. }
  58707. else
  58708. {
  58709. this.addToFileList('physics', key, url, { format: format });
  58710. }
  58711. return this;
  58712. },
  58713. /**
  58714. * Adds Bitmap Font files to the current load queue.
  58715. *
  58716. * To create the Bitmap Font files you can use:
  58717. *
  58718. * BMFont (Windows, free): http://www.angelcode.com/products/bmfont/
  58719. * Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner
  58720. * Littera (Web-based, free): http://kvazars.com/littera/
  58721. *
  58722. * You can choose to either load the data externally, by providing a URL to an xml file.
  58723. * Or you can pass in an XML object or String via the `xmlData` parameter.
  58724. * If you pass a String the data is automatically run through `Loader.parseXML` and then immediately added to the Phaser.Cache.
  58725. *
  58726. * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue.
  58727. *
  58728. * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
  58729. *
  58730. * Retrieve the file via `Cache.getBitmapFont(key)`. XML files are automatically parsed upon load.
  58731. * If you need to control when the XML is parsed then use `Loader.text` instead and parse the XML file as needed.
  58732. *
  58733. * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
  58734. *
  58735. * If the textureURL isn't specified then the Loader will take the key and create a filename from that.
  58736. * For example if the key is "megaFont" and textureURL is null then the Loader will set the URL to be "megaFont.png".
  58737. * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will
  58738. * set the atlasURL to be the key. For example if the key is "megaFont" the atlasURL will be set to "megaFont.xml".
  58739. *
  58740. * If you do not desire this action then provide URLs and / or a data object.
  58741. *
  58742. * @method Phaser.Loader#bitmapFont
  58743. * @param {string} key - Unique asset key of the bitmap font.
  58744. * @param {string} textureURL - URL of the Bitmap Font texture file. If undefined or `null` the url will be set to `<key>.png`, i.e. if `key` was "megaFont" then the URL will be "megaFont.png".
  58745. * @param {string} atlasURL - URL of the Bitmap Font atlas file (xml/json). If undefined or `null` AND `atlasData` is null, the url will be set to `<key>.xml`, i.e. if `key` was "megaFont" then the URL will be "megaFont.xml".
  58746. * @param {object} atlasData - An optional Bitmap Font atlas in string form (stringified xml/json).
  58747. * @param {number} [xSpacing=0] - If you'd like to add additional horizontal spacing between the characters then set the pixel value here.
  58748. * @param {number} [ySpacing=0] - If you'd like to add additional vertical spacing between the lines then set the pixel value here.
  58749. * @return {Phaser.Loader} This Loader instance.
  58750. */
  58751. bitmapFont: function (key, textureURL, atlasURL, atlasData, xSpacing, ySpacing) {
  58752. if (textureURL === undefined || textureURL === null)
  58753. {
  58754. textureURL = key + '.png';
  58755. }
  58756. if (atlasURL === undefined) { atlasURL = null; }
  58757. if (atlasData === undefined) { atlasData = null; }
  58758. if (atlasURL === null && atlasData === null)
  58759. {
  58760. atlasURL = key + '.xml';
  58761. }
  58762. if (xSpacing === undefined) { xSpacing = 0; }
  58763. if (ySpacing === undefined) { ySpacing = 0; }
  58764. // A URL to a json/xml atlas has been given
  58765. if (atlasURL)
  58766. {
  58767. this.addToFileList('bitmapfont', key, textureURL, { atlasURL: atlasURL, xSpacing: xSpacing, ySpacing: ySpacing });
  58768. }
  58769. else
  58770. {
  58771. // A stringified xml/json atlas has been given
  58772. if (typeof atlasData === 'string')
  58773. {
  58774. var json, xml;
  58775. try
  58776. {
  58777. json = JSON.parse(atlasData);
  58778. }
  58779. catch ( e )
  58780. {
  58781. xml = this.parseXml(atlasData);
  58782. }
  58783. if (!xml && !json)
  58784. {
  58785. throw new Error("Phaser.Loader. Invalid Bitmap Font atlas given");
  58786. }
  58787. this.addToFileList('bitmapfont', key, textureURL, { atlasURL: null, atlasData: json || xml,
  58788. atlasType: (!!json ? 'json' : 'xml'), xSpacing: xSpacing, ySpacing: ySpacing });
  58789. }
  58790. }
  58791. return this;
  58792. },
  58793. /**
  58794. * Adds a Texture Atlas file to the current load queue.
  58795. *
  58796. * Unlike `Loader.atlasJSONHash` this call expects the atlas data to be in a JSON Array format.
  58797. *
  58798. * To create the Texture Atlas you can use tools such as:
  58799. *
  58800. * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser)
  58801. * [Shoebox](http://renderhjs.net/shoebox/)
  58802. *
  58803. * If using Texture Packer we recommend you enable "Trim sprite names".
  58804. * If your atlas software has an option to "rotate" the resulting frames, you must disable it.
  58805. *
  58806. * You can choose to either load the data externally, by providing a URL to a json file.
  58807. * Or you can pass in a JSON object or String via the `atlasData` parameter.
  58808. * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache.
  58809. *
  58810. * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue.
  58811. *
  58812. * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
  58813. *
  58814. * Retrieve the file via `Cache.getImage(key)`. JSON files are automatically parsed upon load.
  58815. * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the JSON file as needed.
  58816. *
  58817. * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
  58818. *
  58819. * If the textureURL isn't specified then the Loader will take the key and create a filename from that.
  58820. * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png".
  58821. * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will
  58822. * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.json".
  58823. *
  58824. * If you do not desire this action then provide URLs and / or a data object.
  58825. *
  58826. * @method Phaser.Loader#atlasJSONArray
  58827. * @param {string} key - Unique asset key of the texture atlas file.
  58828. * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `<key>.png`, i.e. if `key` was "alien" then the URL will be "alien.png".
  58829. * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `<key>.json`, i.e. if `key` was "alien" then the URL will be "alien.json".
  58830. * @param {object} [atlasData] - A JSON data object. You don't need this if the data is being loaded from a URL.
  58831. * @return {Phaser.Loader} This Loader instance.
  58832. */
  58833. atlasJSONArray: function (key, textureURL, atlasURL, atlasData) {
  58834. return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY);
  58835. },
  58836. /**
  58837. * Adds a Texture Atlas file to the current load queue.
  58838. *
  58839. * Unlike `Loader.atlas` this call expects the atlas data to be in a JSON Hash format.
  58840. *
  58841. * To create the Texture Atlas you can use tools such as:
  58842. *
  58843. * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser)
  58844. * [Shoebox](http://renderhjs.net/shoebox/)
  58845. *
  58846. * If using Texture Packer we recommend you enable "Trim sprite names".
  58847. * If your atlas software has an option to "rotate" the resulting frames, you must disable it.
  58848. *
  58849. * You can choose to either load the data externally, by providing a URL to a json file.
  58850. * Or you can pass in a JSON object or String via the `atlasData` parameter.
  58851. * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache.
  58852. *
  58853. * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue.
  58854. *
  58855. * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
  58856. *
  58857. * Retrieve the file via `Cache.getImage(key)`. JSON files are automatically parsed upon load.
  58858. * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the JSON file as needed.
  58859. *
  58860. * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
  58861. *
  58862. * If the textureURL isn't specified then the Loader will take the key and create a filename from that.
  58863. * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png".
  58864. * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will
  58865. * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.json".
  58866. *
  58867. * If you do not desire this action then provide URLs and / or a data object.
  58868. *
  58869. * @method Phaser.Loader#atlasJSONHash
  58870. * @param {string} key - Unique asset key of the texture atlas file.
  58871. * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `<key>.png`, i.e. if `key` was "alien" then the URL will be "alien.png".
  58872. * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `<key>.json`, i.e. if `key` was "alien" then the URL will be "alien.json".
  58873. * @param {object} [atlasData] - A JSON data object. You don't need this if the data is being loaded from a URL.
  58874. * @return {Phaser.Loader} This Loader instance.
  58875. */
  58876. atlasJSONHash: function (key, textureURL, atlasURL, atlasData) {
  58877. return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_JSON_HASH);
  58878. },
  58879. /**
  58880. * Adds a Texture Atlas file to the current load queue.
  58881. *
  58882. * This call expects the atlas data to be in the Starling XML data format.
  58883. *
  58884. * To create the Texture Atlas you can use tools such as:
  58885. *
  58886. * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser)
  58887. * [Shoebox](http://renderhjs.net/shoebox/)
  58888. *
  58889. * If using Texture Packer we recommend you enable "Trim sprite names".
  58890. * If your atlas software has an option to "rotate" the resulting frames, you must disable it.
  58891. *
  58892. * You can choose to either load the data externally, by providing a URL to an xml file.
  58893. * Or you can pass in an XML object or String via the `atlasData` parameter.
  58894. * If you pass a String the data is automatically run through `Loader.parseXML` and then immediately added to the Phaser.Cache.
  58895. *
  58896. * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue.
  58897. *
  58898. * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
  58899. *
  58900. * Retrieve the file via `Cache.getImage(key)`. XML files are automatically parsed upon load.
  58901. * If you need to control when the XML is parsed then use `Loader.text` instead and parse the XML file as needed.
  58902. *
  58903. * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
  58904. *
  58905. * If the textureURL isn't specified then the Loader will take the key and create a filename from that.
  58906. * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png".
  58907. * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will
  58908. * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.xml".
  58909. *
  58910. * If you do not desire this action then provide URLs and / or a data object.
  58911. *
  58912. * @method Phaser.Loader#atlasXML
  58913. * @param {string} key - Unique asset key of the texture atlas file.
  58914. * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `<key>.png`, i.e. if `key` was "alien" then the URL will be "alien.png".
  58915. * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `<key>.json`, i.e. if `key` was "alien" then the URL will be "alien.xml".
  58916. * @param {object} [atlasData] - An XML data object. You don't need this if the data is being loaded from a URL.
  58917. * @return {Phaser.Loader} This Loader instance.
  58918. */
  58919. atlasXML: function (key, textureURL, atlasURL, atlasData) {
  58920. if (atlasURL === undefined) { atlasURL = null; }
  58921. if (atlasData === undefined) { atlasData = null; }
  58922. if (!atlasURL && !atlasData)
  58923. {
  58924. atlasURL = key + '.xml';
  58925. }
  58926. return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_XML_STARLING);
  58927. },
  58928. /**
  58929. * Adds a Texture Atlas file to the current load queue.
  58930. *
  58931. * To create the Texture Atlas you can use tools such as:
  58932. *
  58933. * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser)
  58934. * [Shoebox](http://renderhjs.net/shoebox/)
  58935. *
  58936. * If using Texture Packer we recommend you enable "Trim sprite names".
  58937. * If your atlas software has an option to "rotate" the resulting frames, you must disable it.
  58938. *
  58939. * You can choose to either load the data externally, by providing a URL to a json file.
  58940. * Or you can pass in a JSON object or String via the `atlasData` parameter.
  58941. * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache.
  58942. *
  58943. * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue.
  58944. *
  58945. * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
  58946. *
  58947. * Retrieve the file via `Cache.getImage(key)`. JSON files are automatically parsed upon load.
  58948. * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the JSON file as needed.
  58949. *
  58950. * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
  58951. *
  58952. * If the textureURL isn't specified then the Loader will take the key and create a filename from that.
  58953. * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png".
  58954. * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will
  58955. * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.json".
  58956. *
  58957. * If you do not desire this action then provide URLs and / or a data object.
  58958. *
  58959. * @method Phaser.Loader#atlas
  58960. * @param {string} key - Unique asset key of the texture atlas file.
  58961. * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `<key>.png`, i.e. if `key` was "alien" then the URL will be "alien.png".
  58962. * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `<key>.json`, i.e. if `key` was "alien" then the URL will be "alien.json".
  58963. * @param {object} [atlasData] - A JSON or XML data object. You don't need this if the data is being loaded from a URL.
  58964. * @param {number} [format] - The format of the data. Can be Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY (the default), Phaser.Loader.TEXTURE_ATLAS_JSON_HASH or Phaser.Loader.TEXTURE_ATLAS_XML_STARLING.
  58965. * @return {Phaser.Loader} This Loader instance.
  58966. */
  58967. atlas: function (key, textureURL, atlasURL, atlasData, format) {
  58968. if (textureURL === undefined || textureURL === null)
  58969. {
  58970. textureURL = key + '.png';
  58971. }
  58972. if (atlasURL === undefined) { atlasURL = null; }
  58973. if (atlasData === undefined) { atlasData = null; }
  58974. if (format === undefined) { format = Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY; }
  58975. if (!atlasURL && !atlasData)
  58976. {
  58977. if (format === Phaser.Loader.TEXTURE_ATLAS_XML_STARLING)
  58978. {
  58979. atlasURL = key + '.xml';
  58980. }
  58981. else
  58982. {
  58983. atlasURL = key + '.json';
  58984. }
  58985. }
  58986. // A URL to a json/xml file has been given
  58987. if (atlasURL)
  58988. {
  58989. this.addToFileList('textureatlas', key, textureURL, { atlasURL: atlasURL, format: format });
  58990. }
  58991. else
  58992. {
  58993. switch (format)
  58994. {
  58995. // A json string or object has been given
  58996. case Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY:
  58997. if (typeof atlasData === 'string')
  58998. {
  58999. atlasData = JSON.parse(atlasData);
  59000. }
  59001. break;
  59002. // An xml string or object has been given
  59003. case Phaser.Loader.TEXTURE_ATLAS_XML_STARLING:
  59004. if (typeof atlasData === 'string')
  59005. {
  59006. var xml = this.parseXml(atlasData);
  59007. if (!xml)
  59008. {
  59009. throw new Error("Phaser.Loader. Invalid Texture Atlas XML given");
  59010. }
  59011. atlasData = xml;
  59012. }
  59013. break;
  59014. }
  59015. this.addToFileList('textureatlas', key, textureURL, { atlasURL: null, atlasData: atlasData, format: format });
  59016. }
  59017. return this;
  59018. },
  59019. /**
  59020. * Add a synchronization point to the assets/files added within the supplied callback.
  59021. *
  59022. * A synchronization point denotes that an asset _must_ be completely loaded before
  59023. * subsequent assets can be loaded. An asset marked as a sync-point does not need to wait
  59024. * for previous assets to load (unless they are sync-points). Resources, such as packs, may still
  59025. * be downloaded around sync-points, as long as they do not finalize loading.
  59026. *
  59027. * @method Phaser.Loader#withSyncPoints
  59028. * @param {function} callback - The callback is invoked and is supplied with a single argument: the loader.
  59029. * @param {object} [callbackContext=(loader)] - Context for the callback.
  59030. * @return {Phaser.Loader} This Loader instance.
  59031. */
  59032. withSyncPoint: function (callback, callbackContext) {
  59033. this._withSyncPointDepth++;
  59034. try {
  59035. callback.call(callbackContext || this, this);
  59036. } finally {
  59037. this._withSyncPointDepth--;
  59038. }
  59039. return this;
  59040. },
  59041. /**
  59042. * Add a synchronization point to a specific file/asset in the load queue.
  59043. *
  59044. * This has no effect on already loaded assets.
  59045. *
  59046. * @method Phaser.Loader#addSyncPoint
  59047. * @param {string} type - The type of resource to turn into a sync point (image, audio, xml, etc).
  59048. * @param {string} key - Key of the file you want to turn into a sync point.
  59049. * @return {Phaser.Loader} This Loader instance.
  59050. * @see {@link Phaser.Loader#withSyncPoint withSyncPoint}
  59051. */
  59052. addSyncPoint: function (type, key) {
  59053. var asset = this.getAsset(type, key);
  59054. if (asset)
  59055. {
  59056. asset.file.syncPoint = true;
  59057. }
  59058. return this;
  59059. },
  59060. /**
  59061. * Remove a file/asset from the loading queue.
  59062. *
  59063. * A file that is loaded or has started loading cannot be removed.
  59064. *
  59065. * @method Phaser.Loader#removeFile
  59066. * @protected
  59067. * @param {string} type - The type of resource to add to the list (image, audio, xml, etc).
  59068. * @param {string} key - Key of the file you want to remove.
  59069. */
  59070. removeFile: function (type, key) {
  59071. var asset = this.getAsset(type, key);
  59072. if (asset)
  59073. {
  59074. if (!asset.loaded && !asset.loading)
  59075. {
  59076. this._fileList.splice(asset.index, 1);
  59077. }
  59078. }
  59079. },
  59080. /**
  59081. * Remove all file loading requests - this is _insufficient_ to stop current loading. Use `reset` instead.
  59082. *
  59083. * @method Phaser.Loader#removeAll
  59084. * @protected
  59085. */
  59086. removeAll: function () {
  59087. this._fileList.length = 0;
  59088. this._flightQueue.length = 0;
  59089. },
  59090. /**
  59091. * Start loading the assets. Normally you don't need to call this yourself as the StateManager will do so.
  59092. *
  59093. * @method Phaser.Loader#start
  59094. */
  59095. start: function () {
  59096. if (this.isLoading)
  59097. {
  59098. return;
  59099. }
  59100. this.hasLoaded = false;
  59101. this.isLoading = true;
  59102. this.updateProgress();
  59103. this.processLoadQueue();
  59104. },
  59105. /**
  59106. * Process the next item(s) in the file/asset queue.
  59107. *
  59108. * Process the queue and start loading enough items to fill up the inflight queue.
  59109. *
  59110. * If a sync-file is encountered then subsequent asset processing is delayed until it completes.
  59111. * The exception to this rule is that packfiles can be downloaded (but not processed) even if
  59112. * there appear other sync files (ie. packs) - this enables multiple packfiles to be fetched in parallel.
  59113. * such as during the start phaser.
  59114. *
  59115. * @method Phaser.Loader#processLoadQueue
  59116. * @private
  59117. */
  59118. processLoadQueue: function () {
  59119. if (!this.isLoading)
  59120. {
  59121. console.warn('Phaser.Loader - active loading canceled / reset');
  59122. this.finishedLoading(true);
  59123. return;
  59124. }
  59125. // Empty the flight queue as applicable
  59126. for (var i = 0; i < this._flightQueue.length; i++)
  59127. {
  59128. var file = this._flightQueue[i];
  59129. if (file.loaded || file.error)
  59130. {
  59131. this._flightQueue.splice(i, 1);
  59132. i--;
  59133. file.loading = false;
  59134. file.requestUrl = null;
  59135. file.requestObject = null;
  59136. if (file.error)
  59137. {
  59138. this.onFileError.dispatch(file.key, file);
  59139. }
  59140. if (file.type !== 'packfile')
  59141. {
  59142. this._loadedFileCount++;
  59143. this.onFileComplete.dispatch(this.progress, file.key, !file.error, this._loadedFileCount, this._totalFileCount);
  59144. }
  59145. else if (file.type === 'packfile' && file.error)
  59146. {
  59147. // Non-error pack files are handled when processing the file queue
  59148. this._loadedPackCount++;
  59149. this.onPackComplete.dispatch(file.key, !file.error, this._loadedPackCount, this._totalPackCount);
  59150. }
  59151. }
  59152. }
  59153. // When true further non-pack file downloads are suppressed
  59154. var syncblock = false;
  59155. var inflightLimit = this.enableParallel ? Phaser.Math.clamp(this.maxParallelDownloads, 1, 12) : 1;
  59156. for (var i = this._processingHead; i < this._fileList.length; i++)
  59157. {
  59158. var file = this._fileList[i];
  59159. // Pack is fetched (ie. has data) and is currently at the start of the process queue.
  59160. if (file.type === 'packfile' && !file.error && file.loaded && i === this._processingHead)
  59161. {
  59162. // Processing the pack / adds more files
  59163. this.processPack(file);
  59164. this._loadedPackCount++;
  59165. this.onPackComplete.dispatch(file.key, !file.error, this._loadedPackCount, this._totalPackCount);
  59166. }
  59167. if (file.loaded || file.error)
  59168. {
  59169. // Item at the start of file list finished, can skip it in future
  59170. if (i === this._processingHead)
  59171. {
  59172. this._processingHead = i + 1;
  59173. }
  59174. }
  59175. else if (!file.loading && this._flightQueue.length < inflightLimit)
  59176. {
  59177. // -> not loaded/failed, not loading
  59178. if (file.type === 'packfile' && !file.data)
  59179. {
  59180. // Fetches the pack data: the pack is processed above as it reaches queue-start.
  59181. // (Packs do not trigger onLoadStart or onFileStart.)
  59182. this._flightQueue.push(file);
  59183. file.loading = true;
  59184. this.loadFile(file);
  59185. }
  59186. else if (!syncblock)
  59187. {
  59188. if (!this._fileLoadStarted)
  59189. {
  59190. this._fileLoadStarted = true;
  59191. this.onLoadStart.dispatch();
  59192. }
  59193. this._flightQueue.push(file);
  59194. file.loading = true;
  59195. this.onFileStart.dispatch(this.progress, file.key, file.url);
  59196. this.loadFile(file);
  59197. }
  59198. }
  59199. if (!file.loaded && file.syncPoint)
  59200. {
  59201. syncblock = true;
  59202. }
  59203. // Stop looking if queue full - or if syncblocked and there are no more packs.
  59204. // (As only packs can be loaded around a syncblock)
  59205. if (this._flightQueue.length >= inflightLimit ||
  59206. (syncblock && this._loadedPackCount === this._totalPackCount))
  59207. {
  59208. break;
  59209. }
  59210. }
  59211. this.updateProgress();
  59212. // True when all items in the queue have been advanced over
  59213. // (There should be no inflight items as they are complete - loaded/error.)
  59214. if (this._processingHead >= this._fileList.length)
  59215. {
  59216. this.finishedLoading();
  59217. }
  59218. else if (!this._flightQueue.length)
  59219. {
  59220. // Flight queue is empty but file list is not done being processed.
  59221. // This indicates a critical internal error with no known recovery.
  59222. console.warn("Phaser.Loader - aborting: processing queue empty, loading may have stalled");
  59223. var _this = this;
  59224. setTimeout(function () {
  59225. _this.finishedLoading(true);
  59226. }, 2000);
  59227. }
  59228. },
  59229. /**
  59230. * The loading is all finished.
  59231. *
  59232. * @method Phaser.Loader#finishedLoading
  59233. * @private
  59234. * @param {boolean} [abnormal=true] - True if the loading finished abnormally.
  59235. */
  59236. finishedLoading: function (abnormal) {
  59237. if (this.hasLoaded)
  59238. {
  59239. return;
  59240. }
  59241. this.hasLoaded = true;
  59242. this.isLoading = false;
  59243. // If there were no files make sure to trigger the event anyway, for consistency
  59244. if (!abnormal && !this._fileLoadStarted)
  59245. {
  59246. this._fileLoadStarted = true;
  59247. this.onLoadStart.dispatch();
  59248. }
  59249. this.onLoadComplete.dispatch();
  59250. this.game.state.loadComplete();
  59251. this.reset();
  59252. },
  59253. /**
  59254. * Informs the loader that the given file resource has been fetched and processed;
  59255. * or such a request has failed.
  59256. *
  59257. * @method Phaser.Loader#asyncComplete
  59258. * @private
  59259. * @param {object} file
  59260. * @param {string} [error=''] - The error message, if any. No message implies no error.
  59261. */
  59262. asyncComplete: function (file, errorMessage) {
  59263. if (errorMessage === undefined) { errorMessage = ''; }
  59264. file.loaded = true;
  59265. file.error = !!errorMessage;
  59266. if (errorMessage)
  59267. {
  59268. file.errorMessage = errorMessage;
  59269. console.warn('Phaser.Loader - ' + file.type + '[' + file.key + ']' + ': ' + errorMessage);
  59270. // debugger;
  59271. }
  59272. this.processLoadQueue();
  59273. },
  59274. /**
  59275. * Process pack data. This will usually modify the file list.
  59276. *
  59277. * @method Phaser.Loader#processPack
  59278. * @private
  59279. * @param {object} pack
  59280. */
  59281. processPack: function (pack) {
  59282. var packData = pack.data[pack.key];
  59283. if (!packData)
  59284. {
  59285. console.warn('Phaser.Loader - ' + pack.key + ': pack has data, but not for pack key');
  59286. return;
  59287. }
  59288. for (var i = 0; i < packData.length; i++)
  59289. {
  59290. var file = packData[i];
  59291. switch (file.type)
  59292. {
  59293. case "image":
  59294. this.image(file.key, file.url, file.overwrite);
  59295. break;
  59296. case "text":
  59297. this.text(file.key, file.url, file.overwrite);
  59298. break;
  59299. case "json":
  59300. this.json(file.key, file.url, file.overwrite);
  59301. break;
  59302. case "xml":
  59303. this.xml(file.key, file.url, file.overwrite);
  59304. break;
  59305. case "script":
  59306. this.script(file.key, file.url, file.callback, pack.callbackContext || this);
  59307. break;
  59308. case "binary":
  59309. this.binary(file.key, file.url, file.callback, pack.callbackContext || this);
  59310. break;
  59311. case "spritesheet":
  59312. this.spritesheet(file.key, file.url, file.frameWidth, file.frameHeight, file.frameMax, file.margin, file.spacing);
  59313. break;
  59314. case "video":
  59315. this.video(file.key, file.urls);
  59316. break;
  59317. case "audio":
  59318. this.audio(file.key, file.urls, file.autoDecode);
  59319. break;
  59320. case "audiosprite":
  59321. this.audiosprite(file.key, file.urls, file.jsonURL, file.jsonData, file.autoDecode);
  59322. break;
  59323. case "tilemap":
  59324. this.tilemap(file.key, file.url, file.data, Phaser.Tilemap[file.format]);
  59325. break;
  59326. case "physics":
  59327. this.physics(file.key, file.url, file.data, Phaser.Loader[file.format]);
  59328. break;
  59329. case "bitmapFont":
  59330. this.bitmapFont(file.key, file.textureURL, file.atlasURL, file.atlasData, file.xSpacing, file.ySpacing);
  59331. break;
  59332. case "atlasJSONArray":
  59333. this.atlasJSONArray(file.key, file.textureURL, file.atlasURL, file.atlasData);
  59334. break;
  59335. case "atlasJSONHash":
  59336. this.atlasJSONHash(file.key, file.textureURL, file.atlasURL, file.atlasData);
  59337. break;
  59338. case "atlasXML":
  59339. this.atlasXML(file.key, file.textureURL, file.atlasURL, file.atlasData);
  59340. break;
  59341. case "atlas":
  59342. this.atlas(file.key, file.textureURL, file.atlasURL, file.atlasData, Phaser.Loader[file.format]);
  59343. break;
  59344. case "shader":
  59345. this.shader(file.key, file.url, file.overwrite);
  59346. break;
  59347. }
  59348. }
  59349. },
  59350. /**
  59351. * Transforms the asset URL.
  59352. *
  59353. * The default implementation prepends the baseURL if the url doesn't begin with http or //
  59354. *
  59355. * @method Phaser.Loader#transformUrl
  59356. * @protected
  59357. * @param {string} url - The url to transform.
  59358. * @param {object} file - The file object being transformed.
  59359. * @return {string} The transformed url. In rare cases where the url isn't specified it will return false instead.
  59360. */
  59361. transformUrl: function (url, file) {
  59362. if (!url)
  59363. {
  59364. return false;
  59365. }
  59366. if (url.match(/^(?:blob:|data:|http:\/\/|https:\/\/|\/\/)/))
  59367. {
  59368. return url;
  59369. }
  59370. else
  59371. {
  59372. return this.baseURL + file.path + url;
  59373. }
  59374. },
  59375. /**
  59376. * Start fetching a resource.
  59377. *
  59378. * All code paths, async or otherwise, from this function must return to `asyncComplete`.
  59379. *
  59380. * @method Phaser.Loader#loadFile
  59381. * @private
  59382. * @param {object} file
  59383. */
  59384. loadFile: function (file) {
  59385. // Image or Data?
  59386. switch (file.type)
  59387. {
  59388. case 'packfile':
  59389. this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.fileComplete);
  59390. break;
  59391. case 'image':
  59392. case 'spritesheet':
  59393. case 'textureatlas':
  59394. case 'bitmapfont':
  59395. this.loadImageTag(file);
  59396. break;
  59397. case 'audio':
  59398. file.url = this.getAudioURL(file.url);
  59399. if (file.url)
  59400. {
  59401. // WebAudio or Audio Tag?
  59402. if (this.game.sound.usingWebAudio)
  59403. {
  59404. this.xhrLoad(file, this.transformUrl(file.url, file), 'arraybuffer', this.fileComplete);
  59405. }
  59406. else if (this.game.sound.usingAudioTag)
  59407. {
  59408. this.loadAudioTag(file);
  59409. }
  59410. }
  59411. else
  59412. {
  59413. this.fileError(file, null, 'No supported audio URL specified or device does not have audio playback support');
  59414. }
  59415. break;
  59416. case 'video':
  59417. file.url = this.getVideoURL(file.url);
  59418. if (file.url)
  59419. {
  59420. if (file.asBlob)
  59421. {
  59422. this.xhrLoad(file, this.transformUrl(file.url, file), 'blob', this.fileComplete);
  59423. }
  59424. else
  59425. {
  59426. this.loadVideoTag(file);
  59427. }
  59428. }
  59429. else
  59430. {
  59431. this.fileError(file, null, 'No supported video URL specified or device does not have video playback support');
  59432. }
  59433. break;
  59434. case 'json':
  59435. this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.jsonLoadComplete);
  59436. break;
  59437. case 'xml':
  59438. this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.xmlLoadComplete);
  59439. break;
  59440. case 'tilemap':
  59441. if (file.format === Phaser.Tilemap.TILED_JSON)
  59442. {
  59443. this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.jsonLoadComplete);
  59444. }
  59445. else if (file.format === Phaser.Tilemap.CSV)
  59446. {
  59447. this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.csvLoadComplete);
  59448. }
  59449. else
  59450. {
  59451. this.asyncComplete(file, "invalid Tilemap format: " + file.format);
  59452. }
  59453. break;
  59454. case 'text':
  59455. case 'script':
  59456. case 'shader':
  59457. case 'physics':
  59458. this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.fileComplete);
  59459. break;
  59460. case 'binary':
  59461. this.xhrLoad(file, this.transformUrl(file.url, file), 'arraybuffer', this.fileComplete);
  59462. break;
  59463. }
  59464. },
  59465. /**
  59466. * Continue async loading through an Image tag.
  59467. * @private
  59468. */
  59469. loadImageTag: function (file) {
  59470. var _this = this;
  59471. file.data = new Image();
  59472. file.data.name = file.key;
  59473. if (this.crossOrigin)
  59474. {
  59475. file.data.crossOrigin = this.crossOrigin;
  59476. }
  59477. file.data.onload = function () {
  59478. if (file.data.onload)
  59479. {
  59480. file.data.onload = null;
  59481. file.data.onerror = null;
  59482. _this.fileComplete(file);
  59483. }
  59484. };
  59485. file.data.onerror = function () {
  59486. if (file.data.onload)
  59487. {
  59488. file.data.onload = null;
  59489. file.data.onerror = null;
  59490. _this.fileError(file);
  59491. }
  59492. };
  59493. file.data.src = this.transformUrl(file.url, file);
  59494. // Image is immediately-available/cached
  59495. if (file.data.complete && file.data.width && file.data.height)
  59496. {
  59497. file.data.onload = null;
  59498. file.data.onerror = null;
  59499. this.fileComplete(file);
  59500. }
  59501. },
  59502. /**
  59503. * Continue async loading through a Video tag.
  59504. * @private
  59505. */
  59506. loadVideoTag: function (file) {
  59507. var _this = this;
  59508. file.data = document.createElement("video");
  59509. file.data.name = file.key;
  59510. file.data.controls = false;
  59511. file.data.autoplay = false;
  59512. var videoLoadEvent = function () {
  59513. file.data.removeEventListener(file.loadEvent, videoLoadEvent, false);
  59514. file.data.onerror = null;
  59515. file.data.canplay = true;
  59516. Phaser.GAMES[_this.game.id].load.fileComplete(file);
  59517. };
  59518. file.data.onerror = function () {
  59519. file.data.removeEventListener(file.loadEvent, videoLoadEvent, false);
  59520. file.data.onerror = null;
  59521. file.data.canplay = false;
  59522. _this.fileError(file);
  59523. };
  59524. file.data.addEventListener(file.loadEvent, videoLoadEvent, false);
  59525. file.data.src = this.transformUrl(file.url, file);
  59526. file.data.load();
  59527. },
  59528. /**
  59529. * Continue async loading through an Audio tag.
  59530. * @private
  59531. */
  59532. loadAudioTag: function (file) {
  59533. var _this = this;
  59534. if (this.game.sound.touchLocked)
  59535. {
  59536. // If audio is locked we can't do this yet, so need to queue this load request. Bum.
  59537. file.data = new Audio();
  59538. file.data.name = file.key;
  59539. file.data.preload = 'auto';
  59540. file.data.src = this.transformUrl(file.url, file);
  59541. this.fileComplete(file);
  59542. }
  59543. else
  59544. {
  59545. file.data = new Audio();
  59546. file.data.name = file.key;
  59547. var playThroughEvent = function () {
  59548. file.data.removeEventListener('canplaythrough', playThroughEvent, false);
  59549. file.data.onerror = null;
  59550. _this.fileComplete(file);
  59551. };
  59552. file.data.onerror = function () {
  59553. file.data.removeEventListener('canplaythrough', playThroughEvent, false);
  59554. file.data.onerror = null;
  59555. _this.fileError(file);
  59556. };
  59557. file.data.preload = 'auto';
  59558. file.data.src = this.transformUrl(file.url, file);
  59559. file.data.addEventListener('canplaythrough', playThroughEvent, false);
  59560. file.data.load();
  59561. }
  59562. },
  59563. /**
  59564. * Starts the xhr loader.
  59565. *
  59566. * This is designed specifically to use with asset file processing.
  59567. *
  59568. * @method Phaser.Loader#xhrLoad
  59569. * @private
  59570. * @param {object} file - The file/pack to load.
  59571. * @param {string} url - The URL of the file.
  59572. * @param {string} type - The xhr responseType.
  59573. * @param {function} onload - The function to call on success. Invoked in `this` context and supplied with `(file, xhr)` arguments.
  59574. * @param {function} [onerror=fileError] The function to call on error. Invoked in `this` context and supplied with `(file, xhr)` arguments.
  59575. */
  59576. xhrLoad: function (file, url, type, onload, onerror) {
  59577. if (this.useXDomainRequest && window.XDomainRequest)
  59578. {
  59579. this.xhrLoadWithXDR(file, url, type, onload, onerror);
  59580. return;
  59581. }
  59582. var xhr = new XMLHttpRequest();
  59583. xhr.open("GET", url, true);
  59584. xhr.responseType = type;
  59585. onerror = onerror || this.fileError;
  59586. var _this = this;
  59587. xhr.onload = function () {
  59588. try {
  59589. if (xhr.readyState == 4 && xhr.status >= 400 && xhr.status <= 599) { // Handle HTTP status codes of 4xx and 5xx as errors, even if xhr.onerror was not called.
  59590. return onerror.call(_this, file, xhr);
  59591. }
  59592. else {
  59593. return onload.call(_this, file, xhr);
  59594. }
  59595. } catch (e) {
  59596. // If this was the last file in the queue and an error is thrown in the create method
  59597. // then it's caught here, so be sure we don't carry on processing it
  59598. if (!_this.hasLoaded)
  59599. {
  59600. _this.asyncComplete(file, e.message || 'Exception');
  59601. }
  59602. else
  59603. {
  59604. if (window['console'])
  59605. {
  59606. console.error(e);
  59607. }
  59608. }
  59609. }
  59610. };
  59611. xhr.onerror = function () {
  59612. try {
  59613. return onerror.call(_this, file, xhr);
  59614. } catch (e) {
  59615. if (!_this.hasLoaded)
  59616. {
  59617. _this.asyncComplete(file, e.message || 'Exception');
  59618. }
  59619. else
  59620. {
  59621. if (window['console'])
  59622. {
  59623. console.error(e);
  59624. }
  59625. }
  59626. }
  59627. };
  59628. file.requestObject = xhr;
  59629. file.requestUrl = url;
  59630. xhr.send();
  59631. },
  59632. /**
  59633. * Starts the xhr loader - using XDomainRequest.
  59634. * This should _only_ be used with IE 9. Phaser does not support IE 8 and XDR is deprecated in IE 10.
  59635. *
  59636. * This is designed specifically to use with asset file processing.
  59637. *
  59638. * @method Phaser.Loader#xhrLoad
  59639. * @private
  59640. * @param {object} file - The file/pack to load.
  59641. * @param {string} url - The URL of the file.
  59642. * @param {string} type - The xhr responseType.
  59643. * @param {function} onload - The function to call on success. Invoked in `this` context and supplied with `(file, xhr)` arguments.
  59644. * @param {function} [onerror=fileError] The function to call on error. Invoked in `this` context and supplied with `(file, xhr)` arguments.
  59645. * @deprecated This is only relevant for IE 9.
  59646. */
  59647. xhrLoadWithXDR: function (file, url, type, onload, onerror) {
  59648. // Special IE9 magic .. only
  59649. if (!this._warnedAboutXDomainRequest &&
  59650. (!this.game.device.ie || this.game.device.ieVersion >= 10))
  59651. {
  59652. this._warnedAboutXDomainRequest = true;
  59653. console.warn("Phaser.Loader - using XDomainRequest outside of IE 9");
  59654. }
  59655. // Ref: http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
  59656. var xhr = new window.XDomainRequest();
  59657. xhr.open('GET', url, true);
  59658. xhr.responseType = type;
  59659. // XDomainRequest has a few quirks. Occasionally it will abort requests
  59660. // A way to avoid this is to make sure ALL callbacks are set even if not used
  59661. // More info here: http://stackoverflow.com/questions/15786966/xdomainrequest-aborts-post-on-ie-9
  59662. xhr.timeout = 3000;
  59663. onerror = onerror || this.fileError;
  59664. var _this = this;
  59665. xhr.onerror = function () {
  59666. try {
  59667. return onerror.call(_this, file, xhr);
  59668. } catch (e) {
  59669. _this.asyncComplete(file, e.message || 'Exception');
  59670. }
  59671. };
  59672. xhr.ontimeout = function () {
  59673. try {
  59674. return onerror.call(_this, file, xhr);
  59675. } catch (e) {
  59676. _this.asyncComplete(file, e.message || 'Exception');
  59677. }
  59678. };
  59679. xhr.onprogress = function() {};
  59680. xhr.onload = function () {
  59681. try {
  59682. if (xhr.readyState == 4 && xhr.status >= 400 && xhr.status <= 599) { // Handle HTTP status codes of 4xx and 5xx as errors, even if xhr.onerror was not called.
  59683. return onerror.call(_this, file, xhr);
  59684. }
  59685. else {
  59686. return onload.call(_this, file, xhr);
  59687. }
  59688. return onload.call(_this, file, xhr);
  59689. } catch (e) {
  59690. _this.asyncComplete(file, e.message || 'Exception');
  59691. }
  59692. };
  59693. file.requestObject = xhr;
  59694. file.requestUrl = url;
  59695. // Note: The xdr.send() call is wrapped in a timeout to prevent an issue with the interface where some requests are lost
  59696. // if multiple XDomainRequests are being sent at the same time.
  59697. setTimeout(function () {
  59698. xhr.send();
  59699. }, 0);
  59700. },
  59701. /**
  59702. * Give a bunch of URLs, return the first URL that has an extension this device thinks it can play.
  59703. *
  59704. * It is assumed that the device can play "blob:" or "data:" URIs - There is no mime-type checking on data URIs.
  59705. *
  59706. * @method Phaser.Loader#getVideoURL
  59707. * @private
  59708. * @param {object[]|string[]} urls - See {@link #video} for format.
  59709. * @return {string} The URL to try and fetch; or null.
  59710. */
  59711. getVideoURL: function (urls) {
  59712. for (var i = 0; i < urls.length; i++)
  59713. {
  59714. var url = urls[i];
  59715. var videoType;
  59716. if (url.uri) // {uri: .., type: ..} pair
  59717. {
  59718. videoType = url.type;
  59719. url = url.uri;
  59720. if (this.game.device.canPlayVideo(videoType))
  59721. {
  59722. return url;
  59723. }
  59724. }
  59725. else
  59726. {
  59727. // Assume direct-data URI can be played if not in a paired form; select immediately
  59728. if (url.indexOf("blob:") === 0 || url.indexOf("data:") === 0)
  59729. {
  59730. return url;
  59731. }
  59732. if (url.indexOf("?") >= 0) // Remove query from URL
  59733. {
  59734. url = url.substr(0, url.indexOf("?"));
  59735. }
  59736. var extension = url.substr((Math.max(0, url.lastIndexOf(".")) || Infinity) + 1);
  59737. videoType = extension.toLowerCase();
  59738. if (this.game.device.canPlayVideo(videoType))
  59739. {
  59740. return urls[i];
  59741. }
  59742. }
  59743. }
  59744. return null;
  59745. },
  59746. /**
  59747. * Give a bunch of URLs, return the first URL that has an extension this device thinks it can play.
  59748. *
  59749. * It is assumed that the device can play "blob:" or "data:" URIs - There is no mime-type checking on data URIs.
  59750. *
  59751. * @method Phaser.Loader#getAudioURL
  59752. * @private
  59753. * @param {object[]|string[]} urls - See {@link #audio} for format.
  59754. * @return {string} The URL to try and fetch; or null.
  59755. */
  59756. getAudioURL: function (urls) {
  59757. if (this.game.sound.noAudio)
  59758. {
  59759. return null;
  59760. }
  59761. for (var i = 0; i < urls.length; i++)
  59762. {
  59763. var url = urls[i];
  59764. var audioType;
  59765. if (url.uri) // {uri: .., type: ..} pair
  59766. {
  59767. audioType = url.type;
  59768. url = url.uri;
  59769. if (this.game.device.canPlayAudio(audioType))
  59770. {
  59771. return url;
  59772. }
  59773. }
  59774. else
  59775. {
  59776. // Assume direct-data URI can be played if not in a paired form; select immediately
  59777. if (url.indexOf("blob:") === 0 || url.indexOf("data:") === 0)
  59778. {
  59779. return url;
  59780. }
  59781. if (url.indexOf("?") >= 0) // Remove query from URL
  59782. {
  59783. url = url.substr(0, url.indexOf("?"));
  59784. }
  59785. var extension = url.substr((Math.max(0, url.lastIndexOf(".")) || Infinity) + 1);
  59786. audioType = extension.toLowerCase();
  59787. if (this.game.device.canPlayAudio(audioType))
  59788. {
  59789. return urls[i];
  59790. }
  59791. }
  59792. }
  59793. return null;
  59794. },
  59795. /**
  59796. * Error occurred when loading a file.
  59797. *
  59798. * @method Phaser.Loader#fileError
  59799. * @private
  59800. * @param {object} file
  59801. * @param {?XMLHttpRequest} xhr - XHR request, unspecified if loaded via other means (eg. tags)
  59802. * @param {string} reason
  59803. */
  59804. fileError: function (file, xhr, reason) {
  59805. var url = file.requestUrl || this.transformUrl(file.url, file);
  59806. var message = 'error loading asset from URL ' + url;
  59807. if (!reason && xhr)
  59808. {
  59809. reason = xhr.status;
  59810. }
  59811. if (reason)
  59812. {
  59813. message = message + ' (' + reason + ')';
  59814. }
  59815. this.asyncComplete(file, message);
  59816. },
  59817. /**
  59818. * Called when a file/resources had been downloaded and needs to be processed further.
  59819. *
  59820. * @method Phaser.Loader#fileComplete
  59821. * @private
  59822. * @param {object} file - File loaded
  59823. * @param {?XMLHttpRequest} xhr - XHR request, unspecified if loaded via other means (eg. tags)
  59824. */
  59825. fileComplete: function (file, xhr) {
  59826. var loadNext = true;
  59827. switch (file.type)
  59828. {
  59829. case 'packfile':
  59830. // Pack data must never be false-ish after it is fetched without error
  59831. var data = JSON.parse(xhr.responseText);
  59832. file.data = data || {};
  59833. break;
  59834. case 'image':
  59835. this.cache.addImage(file.key, file.url, file.data);
  59836. break;
  59837. case 'spritesheet':
  59838. this.cache.addSpriteSheet(file.key, file.url, file.data, file.frameWidth, file.frameHeight, file.frameMax, file.margin, file.spacing);
  59839. break;
  59840. case 'textureatlas':
  59841. if (file.atlasURL == null)
  59842. {
  59843. this.cache.addTextureAtlas(file.key, file.url, file.data, file.atlasData, file.format);
  59844. }
  59845. else
  59846. {
  59847. // Load the JSON or XML before carrying on with the next file
  59848. loadNext = false;
  59849. if (file.format == Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY || file.format == Phaser.Loader.TEXTURE_ATLAS_JSON_HASH || file.format == Phaser.Loader.TEXTURE_ATLAS_JSON_PYXEL)
  59850. {
  59851. this.xhrLoad(file, this.transformUrl(file.atlasURL, file), 'text', this.jsonLoadComplete);
  59852. }
  59853. else if (file.format == Phaser.Loader.TEXTURE_ATLAS_XML_STARLING)
  59854. {
  59855. this.xhrLoad(file, this.transformUrl(file.atlasURL, file), 'text', this.xmlLoadComplete);
  59856. }
  59857. else
  59858. {
  59859. throw new Error("Phaser.Loader. Invalid Texture Atlas format: " + file.format);
  59860. }
  59861. }
  59862. break;
  59863. case 'bitmapfont':
  59864. if (!file.atlasURL)
  59865. {
  59866. this.cache.addBitmapFont(file.key, file.url, file.data, file.atlasData, file.atlasType, file.xSpacing, file.ySpacing);
  59867. }
  59868. else
  59869. {
  59870. // Load the XML before carrying on with the next file
  59871. loadNext = false;
  59872. this.xhrLoad(file, this.transformUrl(file.atlasURL, file), 'text', function (file, xhr) {
  59873. var json;
  59874. try
  59875. {
  59876. // Try to parse as JSON, if it fails, then it's hopefully XML
  59877. json = JSON.parse(xhr.responseText);
  59878. }
  59879. catch (e) {}
  59880. if (!!json)
  59881. {
  59882. file.atlasType = 'json';
  59883. this.jsonLoadComplete(file, xhr);
  59884. }
  59885. else
  59886. {
  59887. file.atlasType = 'xml';
  59888. this.xmlLoadComplete(file, xhr);
  59889. }
  59890. });
  59891. }
  59892. break;
  59893. case 'video':
  59894. if (file.asBlob)
  59895. {
  59896. try
  59897. {
  59898. file.data = xhr.response;
  59899. }
  59900. catch (e)
  59901. {
  59902. throw new Error("Phaser.Loader. Unable to parse video file as Blob: " + file.key);
  59903. }
  59904. }
  59905. this.cache.addVideo(file.key, file.url, file.data, file.asBlob);
  59906. break;
  59907. case 'audio':
  59908. if (this.game.sound.usingWebAudio)
  59909. {
  59910. file.data = xhr.response;
  59911. this.cache.addSound(file.key, file.url, file.data, true, false);
  59912. if (file.autoDecode)
  59913. {
  59914. this.game.sound.decode(file.key);
  59915. }
  59916. }
  59917. else
  59918. {
  59919. this.cache.addSound(file.key, file.url, file.data, false, true);
  59920. }
  59921. break;
  59922. case 'text':
  59923. file.data = xhr.responseText;
  59924. this.cache.addText(file.key, file.url, file.data);
  59925. break;
  59926. case 'shader':
  59927. file.data = xhr.responseText;
  59928. this.cache.addShader(file.key, file.url, file.data);
  59929. break;
  59930. case 'physics':
  59931. var data = JSON.parse(xhr.responseText);
  59932. this.cache.addPhysicsData(file.key, file.url, data, file.format);
  59933. break;
  59934. case 'script':
  59935. file.data = document.createElement('script');
  59936. file.data.language = 'javascript';
  59937. file.data.type = 'text/javascript';
  59938. file.data.defer = false;
  59939. file.data.text = xhr.responseText;
  59940. document.head.appendChild(file.data);
  59941. if (file.callback)
  59942. {
  59943. file.data = file.callback.call(file.callbackContext, file.key, xhr.responseText);
  59944. }
  59945. break;
  59946. case 'binary':
  59947. if (file.callback)
  59948. {
  59949. file.data = file.callback.call(file.callbackContext, file.key, xhr.response);
  59950. }
  59951. else
  59952. {
  59953. file.data = xhr.response;
  59954. }
  59955. this.cache.addBinary(file.key, file.data);
  59956. break;
  59957. }
  59958. if (loadNext)
  59959. {
  59960. this.asyncComplete(file);
  59961. }
  59962. },
  59963. /**
  59964. * Successfully loaded a JSON file - only used for certain types.
  59965. *
  59966. * @method Phaser.Loader#jsonLoadComplete
  59967. * @private
  59968. * @param {object} file - File associated with this request
  59969. * @param {XMLHttpRequest} xhr
  59970. */
  59971. jsonLoadComplete: function (file, xhr) {
  59972. var data = JSON.parse(xhr.responseText);
  59973. if (file.type === 'tilemap')
  59974. {
  59975. this.cache.addTilemap(file.key, file.url, data, file.format);
  59976. }
  59977. else if (file.type === 'bitmapfont')
  59978. {
  59979. this.cache.addBitmapFont(file.key, file.url, file.data, data, file.atlasType, file.xSpacing, file.ySpacing);
  59980. }
  59981. else if (file.type === 'json')
  59982. {
  59983. this.cache.addJSON(file.key, file.url, data);
  59984. }
  59985. else
  59986. {
  59987. this.cache.addTextureAtlas(file.key, file.url, file.data, data, file.format);
  59988. }
  59989. this.asyncComplete(file);
  59990. },
  59991. /**
  59992. * Successfully loaded a CSV file - only used for certain types.
  59993. *
  59994. * @method Phaser.Loader#csvLoadComplete
  59995. * @private
  59996. * @param {object} file - File associated with this request
  59997. * @param {XMLHttpRequest} xhr
  59998. */
  59999. csvLoadComplete: function (file, xhr) {
  60000. var data = xhr.responseText;
  60001. this.cache.addTilemap(file.key, file.url, data, file.format);
  60002. this.asyncComplete(file);
  60003. },
  60004. /**
  60005. * Successfully loaded an XML file - only used for certain types.
  60006. *
  60007. * @method Phaser.Loader#xmlLoadComplete
  60008. * @private
  60009. * @param {object} file - File associated with this request
  60010. * @param {XMLHttpRequest} xhr
  60011. */
  60012. xmlLoadComplete: function (file, xhr) {
  60013. // Always try parsing the content as XML, regardless of actually response type
  60014. var data = xhr.responseText;
  60015. var xml = this.parseXml(data);
  60016. if (!xml)
  60017. {
  60018. var responseType = xhr.responseType || xhr.contentType; // contentType for MS-XDomainRequest
  60019. console.warn('Phaser.Loader - ' + file.key + ': invalid XML (' + responseType + ')');
  60020. this.asyncComplete(file, "invalid XML");
  60021. return;
  60022. }
  60023. if (file.type === 'bitmapfont')
  60024. {
  60025. this.cache.addBitmapFont(file.key, file.url, file.data, xml, file.atlasType, file.xSpacing, file.ySpacing);
  60026. }
  60027. else if (file.type === 'textureatlas')
  60028. {
  60029. this.cache.addTextureAtlas(file.key, file.url, file.data, xml, file.format);
  60030. }
  60031. else if (file.type === 'xml')
  60032. {
  60033. this.cache.addXML(file.key, file.url, xml);
  60034. }
  60035. this.asyncComplete(file);
  60036. },
  60037. /**
  60038. * Parses string data as XML.
  60039. *
  60040. * @method Phaser.Loader#parseXml
  60041. * @private
  60042. * @param {string} data - The XML text to parse
  60043. * @return {?XMLDocument} Returns the xml document, or null if such could not parsed to a valid document.
  60044. */
  60045. parseXml: function (data) {
  60046. var xml;
  60047. try
  60048. {
  60049. if (window['DOMParser'])
  60050. {
  60051. var domparser = new DOMParser();
  60052. xml = domparser.parseFromString(data, "text/xml");
  60053. }
  60054. else
  60055. {
  60056. xml = new ActiveXObject("Microsoft.XMLDOM");
  60057. // Why is this 'false'?
  60058. xml.async = 'false';
  60059. xml.loadXML(data);
  60060. }
  60061. }
  60062. catch (e)
  60063. {
  60064. xml = null;
  60065. }
  60066. if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length)
  60067. {
  60068. return null;
  60069. }
  60070. else
  60071. {
  60072. return xml;
  60073. }
  60074. },
  60075. /**
  60076. * Update the loading sprite progress.
  60077. *
  60078. * @method Phaser.Loader#nextFile
  60079. * @private
  60080. * @param {object} previousFile
  60081. * @param {boolean} success - Whether the previous asset loaded successfully or not.
  60082. */
  60083. updateProgress: function () {
  60084. if (this.preloadSprite)
  60085. {
  60086. if (this.preloadSprite.direction === 0)
  60087. {
  60088. this.preloadSprite.rect.width = Math.floor((this.preloadSprite.width / 100) * this.progress);
  60089. }
  60090. else
  60091. {
  60092. this.preloadSprite.rect.height = Math.floor((this.preloadSprite.height / 100) * this.progress);
  60093. }
  60094. if (this.preloadSprite.sprite)
  60095. {
  60096. this.preloadSprite.sprite.updateCrop();
  60097. }
  60098. else
  60099. {
  60100. // We seem to have lost our sprite - maybe it was destroyed?
  60101. this.preloadSprite = null;
  60102. }
  60103. }
  60104. },
  60105. /**
  60106. * Returns the number of files that have already been loaded, even if they errored.
  60107. *
  60108. * @method Phaser.Loader#totalLoadedFiles
  60109. * @protected
  60110. * @return {number} The number of files that have already been loaded (even if they errored)
  60111. */
  60112. totalLoadedFiles: function () {
  60113. return this._loadedFileCount;
  60114. },
  60115. /**
  60116. * Returns the number of files still waiting to be processed in the load queue. This value decreases as each file in the queue is loaded.
  60117. *
  60118. * @method Phaser.Loader#totalQueuedFiles
  60119. * @protected
  60120. * @return {number} The number of files that still remain in the load queue.
  60121. */
  60122. totalQueuedFiles: function () {
  60123. return this._totalFileCount - this._loadedFileCount;
  60124. },
  60125. /**
  60126. * Returns the number of asset packs that have already been loaded, even if they errored.
  60127. *
  60128. * @method Phaser.Loader#totalLoadedPacks
  60129. * @protected
  60130. * @return {number} The number of asset packs that have already been loaded (even if they errored)
  60131. */
  60132. totalLoadedPacks: function () {
  60133. return this._totalPackCount;
  60134. },
  60135. /**
  60136. * Returns the number of asset packs still waiting to be processed in the load queue. This value decreases as each pack in the queue is loaded.
  60137. *
  60138. * @method Phaser.Loader#totalQueuedPacks
  60139. * @protected
  60140. * @return {number} The number of asset packs that still remain in the load queue.
  60141. */
  60142. totalQueuedPacks: function () {
  60143. return this._totalPackCount - this._loadedPackCount;
  60144. }
  60145. };
  60146. /**
  60147. * The non-rounded load progress value (from 0.0 to 100.0).
  60148. *
  60149. * A general indicator of the progress.
  60150. * It is possible for the progress to decrease, after `onLoadStart`, if more files are dynamically added.
  60151. *
  60152. * @name Phaser.Loader#progressFloat
  60153. * @property {number}
  60154. */
  60155. Object.defineProperty(Phaser.Loader.prototype, "progressFloat", {
  60156. get: function () {
  60157. var progress = (this._loadedFileCount / this._totalFileCount) * 100;
  60158. return Phaser.Math.clamp(progress || 0, 0, 100);
  60159. }
  60160. });
  60161. /**
  60162. * The rounded load progress percentage value (from 0 to 100). See {@link Phaser.Loader#progressFloat}.
  60163. *
  60164. * @name Phaser.Loader#progress
  60165. * @property {integer}
  60166. */
  60167. Object.defineProperty(Phaser.Loader.prototype, "progress", {
  60168. get: function () {
  60169. return Math.round(this.progressFloat);
  60170. }
  60171. });
  60172. Phaser.Loader.prototype.constructor = Phaser.Loader;
  60173. /**
  60174. * @author Richard Davey <rich@photonstorm.com>
  60175. * @copyright 2016 Photon Storm Ltd.
  60176. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  60177. */
  60178. /**
  60179. * Phaser.LoaderParser parses data objects from Phaser.Loader that need more preparation before they can be inserted into the Cache.
  60180. *
  60181. * @class Phaser.LoaderParser
  60182. */
  60183. Phaser.LoaderParser = {
  60184. /**
  60185. * Alias for xmlBitmapFont, for backwards compatibility.
  60186. *
  60187. * @method Phaser.LoaderParser.bitmapFont
  60188. * @param {object} xml - XML data you want to parse.
  60189. * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses.
  60190. * @param {number} [xSpacing=0] - Additional horizontal spacing between the characters.
  60191. * @param {number} [ySpacing=0] - Additional vertical spacing between the characters.
  60192. * @return {object} The parsed Bitmap Font data.
  60193. */
  60194. bitmapFont: function (xml, baseTexture, xSpacing, ySpacing) {
  60195. return this.xmlBitmapFont(xml, baseTexture, xSpacing, ySpacing);
  60196. },
  60197. /**
  60198. * Parse a Bitmap Font from an XML file.
  60199. *
  60200. * @method Phaser.LoaderParser.xmlBitmapFont
  60201. * @param {object} xml - XML data you want to parse.
  60202. * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses.
  60203. * @param {number} [xSpacing=0] - Additional horizontal spacing between the characters.
  60204. * @param {number} [ySpacing=0] - Additional vertical spacing between the characters.
  60205. * @return {object} The parsed Bitmap Font data.
  60206. */
  60207. xmlBitmapFont: function (xml, baseTexture, xSpacing, ySpacing) {
  60208. var data = {};
  60209. var info = xml.getElementsByTagName('info')[0];
  60210. var common = xml.getElementsByTagName('common')[0];
  60211. data.font = info.getAttribute('face');
  60212. data.size = parseInt(info.getAttribute('size'), 10);
  60213. data.lineHeight = parseInt(common.getAttribute('lineHeight'), 10) + ySpacing;
  60214. data.chars = {};
  60215. var letters = xml.getElementsByTagName('char');
  60216. for (var i = 0; i < letters.length; i++)
  60217. {
  60218. var charCode = parseInt(letters[i].getAttribute('id'), 10);
  60219. data.chars[charCode] = {
  60220. x: parseInt(letters[i].getAttribute('x'), 10),
  60221. y: parseInt(letters[i].getAttribute('y'), 10),
  60222. width: parseInt(letters[i].getAttribute('width'), 10),
  60223. height: parseInt(letters[i].getAttribute('height'), 10),
  60224. xOffset: parseInt(letters[i].getAttribute('xoffset'), 10),
  60225. yOffset: parseInt(letters[i].getAttribute('yoffset'), 10),
  60226. xAdvance: parseInt(letters[i].getAttribute('xadvance'), 10) + xSpacing,
  60227. kerning: {}
  60228. };
  60229. }
  60230. var kernings = xml.getElementsByTagName('kerning');
  60231. for (i = 0; i < kernings.length; i++)
  60232. {
  60233. var first = parseInt(kernings[i].getAttribute('first'), 10);
  60234. var second = parseInt(kernings[i].getAttribute('second'), 10);
  60235. var amount = parseInt(kernings[i].getAttribute('amount'), 10);
  60236. data.chars[second].kerning[first] = amount;
  60237. }
  60238. return this.finalizeBitmapFont(baseTexture, data);
  60239. },
  60240. /**
  60241. * Parse a Bitmap Font from a JSON file.
  60242. *
  60243. * @method Phaser.LoaderParser.jsonBitmapFont
  60244. * @param {object} json - JSON data you want to parse.
  60245. * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses.
  60246. * @param {number} [xSpacing=0] - Additional horizontal spacing between the characters.
  60247. * @param {number} [ySpacing=0] - Additional vertical spacing between the characters.
  60248. * @return {object} The parsed Bitmap Font data.
  60249. */
  60250. jsonBitmapFont: function (json, baseTexture, xSpacing, ySpacing) {
  60251. var data = {
  60252. font: json.font.info._face,
  60253. size: parseInt(json.font.info._size, 10),
  60254. lineHeight: parseInt(json.font.common._lineHeight, 10) + ySpacing,
  60255. chars: {}
  60256. };
  60257. json.font.chars["char"].forEach(
  60258. function parseChar(letter) {
  60259. var charCode = parseInt(letter._id, 10);
  60260. data.chars[charCode] = {
  60261. x: parseInt(letter._x, 10),
  60262. y: parseInt(letter._y, 10),
  60263. width: parseInt(letter._width, 10),
  60264. height: parseInt(letter._height, 10),
  60265. xOffset: parseInt(letter._xoffset, 10),
  60266. yOffset: parseInt(letter._yoffset, 10),
  60267. xAdvance: parseInt(letter._xadvance, 10) + xSpacing,
  60268. kerning: {}
  60269. };
  60270. }
  60271. );
  60272. if (json.font.kernings && json.font.kernings.kerning) {
  60273. json.font.kernings.kerning.forEach(
  60274. function parseKerning(kerning) {
  60275. data.chars[kerning._second].kerning[kerning._first] = parseInt(kerning._amount, 10);
  60276. }
  60277. );
  60278. }
  60279. return this.finalizeBitmapFont(baseTexture, data);
  60280. },
  60281. /**
  60282. * Finalize Bitmap Font parsing.
  60283. *
  60284. * @method Phaser.LoaderParser.finalizeBitmapFont
  60285. * @private
  60286. * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses.
  60287. * @param {object} bitmapFontData - Pre-parsed bitmap font data.
  60288. * @return {object} The parsed Bitmap Font data.
  60289. */
  60290. finalizeBitmapFont: function (baseTexture, bitmapFontData) {
  60291. Object.keys(bitmapFontData.chars).forEach(
  60292. function addTexture(charCode) {
  60293. var letter = bitmapFontData.chars[charCode];
  60294. letter.texture = new PIXI.Texture(baseTexture, new Phaser.Rectangle(letter.x, letter.y, letter.width, letter.height));
  60295. }
  60296. );
  60297. return bitmapFontData;
  60298. }
  60299. };
  60300. /**
  60301. * @author Jeremy Dowell <jeremy@codevinsky.com>
  60302. * @author Richard Davey <rich@photonstorm.com>
  60303. * @copyright 2016 Photon Storm Ltd.
  60304. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  60305. */
  60306. /**
  60307. * Audio Sprites are a combination of audio files and a JSON configuration.
  60308. * The JSON follows the format of that created by https://github.com/tonistiigi/audiosprite
  60309. *
  60310. * @class Phaser.AudioSprite
  60311. * @constructor
  60312. * @param {Phaser.Game} game - Reference to the current game instance.
  60313. * @param {string} key - Asset key for the sound.
  60314. */
  60315. Phaser.AudioSprite = function (game, key) {
  60316. /**
  60317. * A reference to the currently running Game.
  60318. * @property {Phaser.Game} game
  60319. */
  60320. this.game = game;
  60321. /**
  60322. * Asset key for the Audio Sprite.
  60323. * @property {string} key
  60324. */
  60325. this.key = key;
  60326. /**
  60327. * JSON audio atlas object.
  60328. * @property {object} config
  60329. */
  60330. this.config = this.game.cache.getJSON(key + '-audioatlas');
  60331. /**
  60332. * If a sound is set to auto play, this holds the marker key of it.
  60333. * @property {string} autoplayKey
  60334. */
  60335. this.autoplayKey = null;
  60336. /**
  60337. * Is a sound set to autoplay or not?
  60338. * @property {boolean} autoplay
  60339. * @default
  60340. */
  60341. this.autoplay = false;
  60342. /**
  60343. * An object containing the Phaser.Sound objects for the Audio Sprite.
  60344. * @property {object} sounds
  60345. */
  60346. this.sounds = {};
  60347. for (var k in this.config.spritemap)
  60348. {
  60349. var marker = this.config.spritemap[k];
  60350. var sound = this.game.add.sound(this.key);
  60351. sound.addMarker(k, marker.start, (marker.end - marker.start), null, marker.loop);
  60352. this.sounds[k] = sound;
  60353. }
  60354. if (this.config.autoplay)
  60355. {
  60356. this.autoplayKey = this.config.autoplay;
  60357. this.play(this.autoplayKey);
  60358. this.autoplay = this.sounds[this.autoplayKey];
  60359. }
  60360. };
  60361. Phaser.AudioSprite.prototype = {
  60362. /**
  60363. * Play a sound with the given name.
  60364. *
  60365. * @method Phaser.AudioSprite#play
  60366. * @param {string} [marker] - The name of sound to play
  60367. * @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).
  60368. * @return {Phaser.Sound} This sound instance.
  60369. */
  60370. play: function (marker, volume) {
  60371. if (volume === undefined) { volume = 1; }
  60372. return this.sounds[marker].play(marker, null, volume);
  60373. },
  60374. /**
  60375. * Stop a sound with the given name.
  60376. *
  60377. * @method Phaser.AudioSprite#stop
  60378. * @param {string} [marker=''] - The name of sound to stop. If none is given it will stop all sounds in the audio sprite.
  60379. */
  60380. stop: function (marker) {
  60381. if (!marker)
  60382. {
  60383. for (var key in this.sounds)
  60384. {
  60385. this.sounds[key].stop();
  60386. }
  60387. }
  60388. else
  60389. {
  60390. this.sounds[marker].stop();
  60391. }
  60392. },
  60393. /**
  60394. * Get a sound with the given name.
  60395. *
  60396. * @method Phaser.AudioSprite#get
  60397. * @param {string} marker - The name of sound to get.
  60398. * @return {Phaser.Sound} The sound instance.
  60399. */
  60400. get: function(marker) {
  60401. return this.sounds[marker];
  60402. }
  60403. };
  60404. Phaser.AudioSprite.prototype.constructor = Phaser.AudioSprite;
  60405. /**
  60406. * @author Richard Davey <rich@photonstorm.com>
  60407. * @copyright 2016 Photon Storm Ltd.
  60408. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  60409. */
  60410. /**
  60411. * The Sound class constructor.
  60412. *
  60413. * @class Phaser.Sound
  60414. * @constructor
  60415. * @param {Phaser.Game} game - Reference to the current game instance.
  60416. * @param {string} key - Asset key for the sound.
  60417. * @param {number} [volume=1] - Default value for the volume, between 0 and 1.
  60418. * @param {boolean} [loop=false] - Whether or not the sound will loop.
  60419. */
  60420. Phaser.Sound = function (game, key, volume, loop, connect) {
  60421. if (volume === undefined) { volume = 1; }
  60422. if (loop === undefined) { loop = false; }
  60423. if (connect === undefined) { connect = game.sound.connectToMaster; }
  60424. /**
  60425. * A reference to the currently running Game.
  60426. * @property {Phaser.Game} game
  60427. */
  60428. this.game = game;
  60429. /**
  60430. * @property {string} name - Name of the sound.
  60431. */
  60432. this.name = key;
  60433. /**
  60434. * @property {string} key - Asset key for the sound.
  60435. */
  60436. this.key = key;
  60437. /**
  60438. * @property {boolean} loop - Whether or not the sound or current sound marker will loop.
  60439. */
  60440. this.loop = loop;
  60441. /**
  60442. * @property {number} volume - The sound or sound marker volume. A value between 0 (silence) and 1 (full volume).
  60443. */
  60444. this.volume = volume;
  60445. /**
  60446. * @property {object} markers - The sound markers.
  60447. */
  60448. this.markers = {};
  60449. /**
  60450. * @property {AudioContext} context - Reference to the AudioContext instance.
  60451. */
  60452. this.context = null;
  60453. /**
  60454. * @property {boolean} autoplay - Boolean indicating whether the sound should start automatically.
  60455. */
  60456. this.autoplay = false;
  60457. /**
  60458. * @property {number} totalDuration - The total duration of the sound in seconds.
  60459. */
  60460. this.totalDuration = 0;
  60461. /**
  60462. * @property {number} startTime - The time the Sound starts at (typically 0 unless starting from a marker)
  60463. * @default
  60464. */
  60465. this.startTime = 0;
  60466. /**
  60467. * @property {number} currentTime - The current time the sound is at.
  60468. */
  60469. this.currentTime = 0;
  60470. /**
  60471. * @property {number} duration - The duration of the current sound marker in seconds.
  60472. */
  60473. this.duration = 0;
  60474. /**
  60475. * @property {number} durationMS - The duration of the current sound marker in ms.
  60476. */
  60477. this.durationMS = 0;
  60478. /**
  60479. * @property {number} position - The position of the current sound marker.
  60480. */
  60481. this.position = 0;
  60482. /**
  60483. * @property {number} stopTime - The time the sound stopped.
  60484. */
  60485. this.stopTime = 0;
  60486. /**
  60487. * @property {boolean} paused - true if the sound is paused, otherwise false.
  60488. * @default
  60489. */
  60490. this.paused = false;
  60491. /**
  60492. * @property {number} pausedPosition - The position the sound had reached when it was paused.
  60493. */
  60494. this.pausedPosition = 0;
  60495. /**
  60496. * @property {number} pausedTime - The game time at which the sound was paused.
  60497. */
  60498. this.pausedTime = 0;
  60499. /**
  60500. * @property {boolean} isPlaying - true if the sound is currently playing, otherwise false.
  60501. * @default
  60502. */
  60503. this.isPlaying = false;
  60504. /**
  60505. * @property {string} currentMarker - The string ID of the currently playing marker, if any.
  60506. * @default
  60507. */
  60508. this.currentMarker = '';
  60509. /**
  60510. * @property {Phaser.Tween} fadeTween - The tween that fades the audio, set via Sound.fadeIn and Sound.fadeOut.
  60511. */
  60512. this.fadeTween = null;
  60513. /**
  60514. * @property {boolean} pendingPlayback - true if the sound file is pending playback
  60515. * @readonly
  60516. */
  60517. this.pendingPlayback = false;
  60518. /**
  60519. * @property {boolean} override - if true when you play this sound it will always start from the beginning.
  60520. * @default
  60521. */
  60522. this.override = false;
  60523. /**
  60524. * @property {boolean} allowMultiple - This will allow you to have multiple instances of this Sound playing at once. This is only useful when running under Web Audio, and we recommend you implement a local pooling system to not flood the sound channels.
  60525. * @default
  60526. */
  60527. this.allowMultiple = false;
  60528. /**
  60529. * @property {boolean} usingWebAudio - true if this sound is being played with Web Audio.
  60530. * @readonly
  60531. */
  60532. this.usingWebAudio = this.game.sound.usingWebAudio;
  60533. /**
  60534. * @property {boolean} usingAudioTag - true if the sound is being played via the Audio tag.
  60535. */
  60536. this.usingAudioTag = this.game.sound.usingAudioTag;
  60537. /**
  60538. * @property {object} externalNode - If defined this Sound won't connect to the SoundManager master gain node, but will instead connect to externalNode.
  60539. */
  60540. this.externalNode = null;
  60541. /**
  60542. * @property {object} masterGainNode - The master gain node in a Web Audio system.
  60543. */
  60544. this.masterGainNode = null;
  60545. /**
  60546. * @property {object} gainNode - The gain node in a Web Audio system.
  60547. */
  60548. this.gainNode = null;
  60549. /**
  60550. * @property {object} _sound - Internal var.
  60551. * @private
  60552. */
  60553. this._sound = null;
  60554. if (this.usingWebAudio)
  60555. {
  60556. this.context = this.game.sound.context;
  60557. this.masterGainNode = this.game.sound.masterGain;
  60558. if (this.context.createGain === undefined)
  60559. {
  60560. this.gainNode = this.context.createGainNode();
  60561. }
  60562. else
  60563. {
  60564. this.gainNode = this.context.createGain();
  60565. }
  60566. this.gainNode.gain.value = volume * this.game.sound.volume;
  60567. if (connect)
  60568. {
  60569. this.gainNode.connect(this.masterGainNode);
  60570. }
  60571. }
  60572. else if (this.usingAudioTag)
  60573. {
  60574. if (this.game.cache.getSound(key) && this.game.cache.isSoundReady(key))
  60575. {
  60576. this._sound = this.game.cache.getSoundData(key);
  60577. this.totalDuration = 0;
  60578. if (this._sound.duration)
  60579. {
  60580. this.totalDuration = this._sound.duration;
  60581. }
  60582. }
  60583. else
  60584. {
  60585. this.game.cache.onSoundUnlock.add(this.soundHasUnlocked, this);
  60586. }
  60587. }
  60588. /**
  60589. * @property {Phaser.Signal} onDecoded - The onDecoded event is dispatched when the sound has finished decoding (typically for mp3 files)
  60590. */
  60591. this.onDecoded = new Phaser.Signal();
  60592. /**
  60593. * @property {Phaser.Signal} onPlay - The onPlay event is dispatched each time this sound is played.
  60594. */
  60595. this.onPlay = new Phaser.Signal();
  60596. /**
  60597. * @property {Phaser.Signal} onPause - The onPause event is dispatched when this sound is paused.
  60598. */
  60599. this.onPause = new Phaser.Signal();
  60600. /**
  60601. * @property {Phaser.Signal} onResume - The onResume event is dispatched when this sound is resumed from a paused state.
  60602. */
  60603. this.onResume = new Phaser.Signal();
  60604. /**
  60605. * @property {Phaser.Signal} onLoop - The onLoop event is dispatched when this sound loops during playback.
  60606. */
  60607. this.onLoop = new Phaser.Signal();
  60608. /**
  60609. * @property {Phaser.Signal} onStop - The onStop event is dispatched when this sound stops playback.
  60610. */
  60611. this.onStop = new Phaser.Signal();
  60612. /**
  60613. * @property {Phaser.Signal} onMute - The onMouse event is dispatched when this sound is muted.
  60614. */
  60615. this.onMute = new Phaser.Signal();
  60616. /**
  60617. * @property {Phaser.Signal} onMarkerComplete - The onMarkerComplete event is dispatched when a marker within this sound completes playback.
  60618. */
  60619. this.onMarkerComplete = new Phaser.Signal();
  60620. /**
  60621. * @property {Phaser.Signal} onFadeComplete - The onFadeComplete event is dispatched when this sound finishes fading either in or out.
  60622. */
  60623. this.onFadeComplete = new Phaser.Signal();
  60624. /**
  60625. * @property {number} _volume - The global audio volume. A value between 0 (silence) and 1 (full volume).
  60626. * @private
  60627. */
  60628. this._volume = volume;
  60629. /**
  60630. * @property {any} _buffer - Decoded data buffer / Audio tag.
  60631. * @private
  60632. */
  60633. this._buffer = null;
  60634. /**
  60635. * @property {boolean} _muted - Boolean indicating whether the sound is muted or not.
  60636. * @private
  60637. */
  60638. this._muted = false;
  60639. /**
  60640. * @property {number} _tempMarker - Internal marker var.
  60641. * @private
  60642. */
  60643. this._tempMarker = 0;
  60644. /**
  60645. * @property {number} _tempPosition - Internal marker var.
  60646. * @private
  60647. */
  60648. this._tempPosition = 0;
  60649. /**
  60650. * @property {number} _tempVolume - Internal marker var.
  60651. * @private
  60652. */
  60653. this._tempVolume = 0;
  60654. /**
  60655. * @property {number} _muteVolume - Internal cache var.
  60656. * @private
  60657. */
  60658. this._muteVolume = 0;
  60659. /**
  60660. * @property {boolean} _tempLoop - Internal cache var.
  60661. * @private
  60662. */
  60663. this._tempLoop = 0;
  60664. /**
  60665. * @property {boolean} _paused - Was this sound paused via code or a game event?
  60666. * @private
  60667. */
  60668. this._paused = false;
  60669. /**
  60670. * @property {boolean} _onDecodedEventDispatched - Was the onDecoded event dispatched?
  60671. * @private
  60672. */
  60673. this._onDecodedEventDispatched = false;
  60674. };
  60675. Phaser.Sound.prototype = {
  60676. /**
  60677. * Called automatically when this sound is unlocked.
  60678. * @method Phaser.Sound#soundHasUnlocked
  60679. * @param {string} key - The Phaser.Cache key of the sound file to check for decoding.
  60680. * @protected
  60681. */
  60682. soundHasUnlocked: function (key) {
  60683. if (key === this.key)
  60684. {
  60685. this._sound = this.game.cache.getSoundData(this.key);
  60686. this.totalDuration = this._sound.duration;
  60687. }
  60688. },
  60689. /**
  60690. * Adds a marker into the current Sound. A marker is represented by a unique key and a start time and duration.
  60691. * This allows you to bundle multiple sounds together into a single audio file and use markers to jump between them for playback.
  60692. *
  60693. * @method Phaser.Sound#addMarker
  60694. * @param {string} name - A unique name for this marker, i.e. 'explosion', 'gunshot', etc.
  60695. * @param {number} start - The start point of this marker in the audio file, given in seconds. 2.5 = 2500ms, 0.5 = 500ms, etc.
  60696. * @param {number} duration - The duration of the marker in seconds. 2.5 = 2500ms, 0.5 = 500ms, etc.
  60697. * @param {number} [volume=1] - The volume the sound will play back at, between 0 (silent) and 1 (full volume).
  60698. * @param {boolean} [loop=false] - Sets if the sound will loop or not.
  60699. */
  60700. addMarker: function (name, start, duration, volume, loop) {
  60701. if (volume === undefined || volume === null) { volume = 1; }
  60702. if (loop === undefined) { loop = false; }
  60703. this.markers[name] = {
  60704. name: name,
  60705. start: start,
  60706. stop: start + duration,
  60707. volume: volume,
  60708. duration: duration,
  60709. durationMS: duration * 1000,
  60710. loop: loop
  60711. };
  60712. },
  60713. /**
  60714. * Removes a marker from the sound.
  60715. * @method Phaser.Sound#removeMarker
  60716. * @param {string} name - The key of the marker to remove.
  60717. */
  60718. removeMarker: function (name) {
  60719. delete this.markers[name];
  60720. },
  60721. /**
  60722. * Called automatically by the AudioContext when the sound stops playing.
  60723. * Doesn't get called if the sound is set to loop or is a section of an Audio Sprite.
  60724. *
  60725. * @method Phaser.Sound#onEndedHandler
  60726. * @protected
  60727. */
  60728. onEndedHandler: function () {
  60729. this._sound.onended = null;
  60730. this.isPlaying = false;
  60731. this.currentTime = this.durationMS;
  60732. this.stop();
  60733. },
  60734. /**
  60735. * Called automatically by Phaser.SoundManager.
  60736. * @method Phaser.Sound#update
  60737. * @protected
  60738. */
  60739. update: function () {
  60740. if (!this.game.cache.checkSoundKey(this.key))
  60741. {
  60742. this.destroy();
  60743. return;
  60744. }
  60745. if (this.isDecoded && !this._onDecodedEventDispatched)
  60746. {
  60747. this.onDecoded.dispatch(this);
  60748. this._onDecodedEventDispatched = true;
  60749. }
  60750. if (this.pendingPlayback && this.game.cache.isSoundReady(this.key))
  60751. {
  60752. this.pendingPlayback = false;
  60753. this.play(this._tempMarker, this._tempPosition, this._tempVolume, this._tempLoop);
  60754. }
  60755. if (this.isPlaying)
  60756. {
  60757. this.currentTime = this.game.time.time - this.startTime;
  60758. if (this.currentTime >= this.durationMS)
  60759. {
  60760. if (this.usingWebAudio)
  60761. {
  60762. if (this.loop)
  60763. {
  60764. // won't work with markers, needs to reset the position
  60765. this.onLoop.dispatch(this);
  60766. if (this.currentMarker === '')
  60767. {
  60768. this.currentTime = 0;
  60769. this.startTime = this.game.time.time;
  60770. }
  60771. else
  60772. {
  60773. this.onMarkerComplete.dispatch(this.currentMarker, this);
  60774. this.play(this.currentMarker, 0, this.volume, true, true);
  60775. }
  60776. }
  60777. else
  60778. {
  60779. // Stop if we're using an audio marker, otherwise we let onended handle it
  60780. if (this.currentMarker !== '')
  60781. {
  60782. this.stop();
  60783. }
  60784. }
  60785. }
  60786. else
  60787. {
  60788. if (this.loop)
  60789. {
  60790. this.onLoop.dispatch(this);
  60791. this.play(this.currentMarker, 0, this.volume, true, true);
  60792. }
  60793. else
  60794. {
  60795. this.stop();
  60796. }
  60797. }
  60798. }
  60799. }
  60800. },
  60801. /**
  60802. * Loops this entire sound. If you need to loop a section of it then use Sound.play and the marker and loop parameters.
  60803. *
  60804. * @method Phaser.Sound#loopFull
  60805. * @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).
  60806. * @return {Phaser.Sound} This sound instance.
  60807. */
  60808. loopFull: function (volume) {
  60809. this.play(null, 0, volume, true);
  60810. },
  60811. /**
  60812. * Play this sound, or a marked section of it.
  60813. *
  60814. * @method Phaser.Sound#play
  60815. * @param {string} [marker=''] - If you want to play a marker then give the key here, otherwise leave blank to play the full sound.
  60816. * @param {number} [position=0] - The starting position to play the sound from - this is ignored if you provide a marker.
  60817. * @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).
  60818. * @param {boolean} [loop=false] - Loop when finished playing? If not using a marker / audio sprite the looping will be done via the WebAudio loop property, otherwise it's time based.
  60819. * @param {boolean} [forceRestart=true] - If the sound is already playing you can set forceRestart to restart it from the beginning.
  60820. * @return {Phaser.Sound} This sound instance.
  60821. */
  60822. play: function (marker, position, volume, loop, forceRestart) {
  60823. if (marker === undefined || marker === false || marker === null) { marker = ''; }
  60824. if (forceRestart === undefined) { forceRestart = true; }
  60825. if (this.isPlaying && !this.allowMultiple && !forceRestart && !this.override)
  60826. {
  60827. // Use Restart instead
  60828. return this;
  60829. }
  60830. if (this._sound && this.isPlaying && !this.allowMultiple && (this.override || forceRestart))
  60831. {
  60832. if (this.usingWebAudio)
  60833. {
  60834. if (this._sound.stop === undefined)
  60835. {
  60836. this._sound.noteOff(0);
  60837. }
  60838. else
  60839. {
  60840. try {
  60841. this._sound.stop(0);
  60842. }
  60843. catch (e) {
  60844. }
  60845. }
  60846. if (this.externalNode)
  60847. {
  60848. this._sound.disconnect(this.externalNode);
  60849. }
  60850. else
  60851. {
  60852. this._sound.disconnect(this.gainNode);
  60853. }
  60854. }
  60855. else if (this.usingAudioTag)
  60856. {
  60857. this._sound.pause();
  60858. this._sound.currentTime = 0;
  60859. }
  60860. }
  60861. if (marker === '' && Object.keys(this.markers).length > 0)
  60862. {
  60863. // If they didn't specify a marker but this is an audio sprite,
  60864. // we should never play the entire thing
  60865. return this;
  60866. }
  60867. if (marker !== '')
  60868. {
  60869. this.currentMarker = marker;
  60870. if (this.markers[marker])
  60871. {
  60872. // Playing a marker? Then we default to the marker values
  60873. this.position = this.markers[marker].start;
  60874. this.volume = this.markers[marker].volume;
  60875. this.loop = this.markers[marker].loop;
  60876. this.duration = this.markers[marker].duration;
  60877. this.durationMS = this.markers[marker].durationMS;
  60878. if (typeof volume !== 'undefined')
  60879. {
  60880. this.volume = volume;
  60881. }
  60882. if (typeof loop !== 'undefined')
  60883. {
  60884. this.loop = loop;
  60885. }
  60886. this._tempMarker = marker;
  60887. this._tempPosition = this.position;
  60888. this._tempVolume = this.volume;
  60889. this._tempLoop = this.loop;
  60890. }
  60891. else
  60892. {
  60893. // console.warn("Phaser.Sound.play: audio marker " + marker + " doesn't exist");
  60894. return this;
  60895. }
  60896. }
  60897. else
  60898. {
  60899. position = position || 0;
  60900. if (volume === undefined) { volume = this._volume; }
  60901. if (loop === undefined) { loop = this.loop; }
  60902. this.position = Math.max(0, position);
  60903. this.volume = volume;
  60904. this.loop = loop;
  60905. this.duration = 0;
  60906. this.durationMS = 0;
  60907. this._tempMarker = marker;
  60908. this._tempPosition = position;
  60909. this._tempVolume = volume;
  60910. this._tempLoop = loop;
  60911. }
  60912. if (this.usingWebAudio)
  60913. {
  60914. // Does the sound need decoding?
  60915. if (this.game.cache.isSoundDecoded(this.key))
  60916. {
  60917. this._sound = this.context.createBufferSource();
  60918. if (this.externalNode)
  60919. {
  60920. this._sound.connect(this.externalNode);
  60921. }
  60922. else
  60923. {
  60924. this._sound.connect(this.gainNode);
  60925. }
  60926. this._buffer = this.game.cache.getSoundData(this.key);
  60927. this._sound.buffer = this._buffer;
  60928. if (this.loop && marker === '')
  60929. {
  60930. this._sound.loop = true;
  60931. }
  60932. if (!this.loop && marker === '')
  60933. {
  60934. this._sound.onended = this.onEndedHandler.bind(this);
  60935. }
  60936. this.totalDuration = this._sound.buffer.duration;
  60937. if (this.duration === 0)
  60938. {
  60939. this.duration = this.totalDuration;
  60940. this.durationMS = Math.ceil(this.totalDuration * 1000);
  60941. }
  60942. // Useful to cache this somewhere perhaps?
  60943. if (this._sound.start === undefined)
  60944. {
  60945. this._sound.noteGrainOn(0, this.position, this.duration);
  60946. }
  60947. else
  60948. {
  60949. if (this.loop && marker === '')
  60950. {
  60951. this._sound.start(0, 0);
  60952. }
  60953. else
  60954. {
  60955. this._sound.start(0, this.position, this.duration);
  60956. }
  60957. }
  60958. this.isPlaying = true;
  60959. this.startTime = this.game.time.time;
  60960. this.currentTime = 0;
  60961. this.stopTime = this.startTime + this.durationMS;
  60962. this.onPlay.dispatch(this);
  60963. }
  60964. else
  60965. {
  60966. this.pendingPlayback = true;
  60967. if (this.game.cache.getSound(this.key) && this.game.cache.getSound(this.key).isDecoding === false)
  60968. {
  60969. this.game.sound.decode(this.key, this);
  60970. }
  60971. }
  60972. }
  60973. else
  60974. {
  60975. if (this.game.cache.getSound(this.key) && this.game.cache.getSound(this.key).locked)
  60976. {
  60977. this.game.cache.reloadSound(this.key);
  60978. this.pendingPlayback = true;
  60979. }
  60980. else
  60981. {
  60982. if (this._sound && (this.game.device.cocoonJS || this._sound.readyState === 4))
  60983. {
  60984. this._sound.play();
  60985. // This doesn't become available until you call play(), wonderful ...
  60986. this.totalDuration = this._sound.duration;
  60987. if (this.duration === 0)
  60988. {
  60989. this.duration = this.totalDuration;
  60990. this.durationMS = this.totalDuration * 1000;
  60991. }
  60992. this._sound.currentTime = this.position;
  60993. this._sound.muted = this._muted;
  60994. if (this._muted || this.game.sound.mute)
  60995. {
  60996. this._sound.volume = 0;
  60997. }
  60998. else
  60999. {
  61000. this._sound.volume = this._volume;
  61001. }
  61002. this.isPlaying = true;
  61003. this.startTime = this.game.time.time;
  61004. this.currentTime = 0;
  61005. this.stopTime = this.startTime + this.durationMS;
  61006. this.onPlay.dispatch(this);
  61007. }
  61008. else
  61009. {
  61010. this.pendingPlayback = true;
  61011. }
  61012. }
  61013. }
  61014. return this;
  61015. },
  61016. /**
  61017. * Restart the sound, or a marked section of it.
  61018. *
  61019. * @method Phaser.Sound#restart
  61020. * @param {string} [marker=''] - If you want to play a marker then give the key here, otherwise leave blank to play the full sound.
  61021. * @param {number} [position=0] - The starting position to play the sound from - this is ignored if you provide a marker.
  61022. * @param {number} [volume=1] - Volume of the sound you want to play.
  61023. * @param {boolean} [loop=false] - Loop when it finished playing?
  61024. */
  61025. restart: function (marker, position, volume, loop) {
  61026. marker = marker || '';
  61027. position = position || 0;
  61028. volume = volume || 1;
  61029. if (loop === undefined) { loop = false; }
  61030. this.play(marker, position, volume, loop, true);
  61031. },
  61032. /**
  61033. * Pauses the sound.
  61034. *
  61035. * @method Phaser.Sound#pause
  61036. */
  61037. pause: function () {
  61038. if (this.isPlaying && this._sound)
  61039. {
  61040. this.paused = true;
  61041. this.pausedPosition = this.currentTime;
  61042. this.pausedTime = this.game.time.time;
  61043. this.onPause.dispatch(this);
  61044. this.stop();
  61045. }
  61046. },
  61047. /**
  61048. * Resumes the sound.
  61049. *
  61050. * @method Phaser.Sound#resume
  61051. */
  61052. resume: function () {
  61053. if (this.paused && this._sound)
  61054. {
  61055. if (this.usingWebAudio)
  61056. {
  61057. var p = Math.max(0, this.position + (this.pausedPosition / 1000));
  61058. this._sound = this.context.createBufferSource();
  61059. this._sound.buffer = this._buffer;
  61060. if (this.externalNode)
  61061. {
  61062. this._sound.connect(this.externalNode);
  61063. }
  61064. else
  61065. {
  61066. this._sound.connect(this.gainNode);
  61067. }
  61068. if (this.loop)
  61069. {
  61070. this._sound.loop = true;
  61071. }
  61072. if (!this.loop && this.currentMarker === '')
  61073. {
  61074. this._sound.onended = this.onEndedHandler.bind(this);
  61075. }
  61076. var duration = this.duration - (this.pausedPosition / 1000);
  61077. if (this._sound.start === undefined)
  61078. {
  61079. this._sound.noteGrainOn(0, p, duration);
  61080. //this._sound.noteOn(0); // the zero is vitally important, crashes iOS6 without it
  61081. }
  61082. else
  61083. {
  61084. if (this.loop && this.game.device.chrome)
  61085. {
  61086. // Handle chrome bug: https://code.google.com/p/chromium/issues/detail?id=457099
  61087. if (this.game.device.chromeVersion === 42)
  61088. {
  61089. this._sound.start(0);
  61090. }
  61091. else
  61092. {
  61093. this._sound.start(0, p);
  61094. }
  61095. }
  61096. else
  61097. {
  61098. this._sound.start(0, p, duration);
  61099. }
  61100. }
  61101. }
  61102. else
  61103. {
  61104. this._sound.play();
  61105. }
  61106. this.isPlaying = true;
  61107. this.paused = false;
  61108. this.startTime += (this.game.time.time - this.pausedTime);
  61109. this.onResume.dispatch(this);
  61110. }
  61111. },
  61112. /**
  61113. * Stop playing this sound.
  61114. *
  61115. * @method Phaser.Sound#stop
  61116. */
  61117. stop: function () {
  61118. if (this.isPlaying && this._sound)
  61119. {
  61120. if (this.usingWebAudio)
  61121. {
  61122. if (this._sound.stop === undefined)
  61123. {
  61124. this._sound.noteOff(0);
  61125. }
  61126. else
  61127. {
  61128. try {
  61129. this._sound.stop(0);
  61130. }
  61131. catch (e)
  61132. {
  61133. // Thanks Android 4.4
  61134. }
  61135. }
  61136. if (this.externalNode)
  61137. {
  61138. this._sound.disconnect(this.externalNode);
  61139. }
  61140. else
  61141. {
  61142. this._sound.disconnect(this.gainNode);
  61143. }
  61144. }
  61145. else if (this.usingAudioTag)
  61146. {
  61147. this._sound.pause();
  61148. this._sound.currentTime = 0;
  61149. }
  61150. }
  61151. this.pendingPlayback = false;
  61152. this.isPlaying = false;
  61153. if (!this.paused)
  61154. {
  61155. var prevMarker = this.currentMarker;
  61156. if (this.currentMarker !== '')
  61157. {
  61158. this.onMarkerComplete.dispatch(this.currentMarker, this);
  61159. }
  61160. this.currentMarker = '';
  61161. if (this.fadeTween !== null)
  61162. {
  61163. this.fadeTween.stop();
  61164. }
  61165. this.onStop.dispatch(this, prevMarker);
  61166. }
  61167. },
  61168. /**
  61169. * Starts this sound playing (or restarts it if already doing so) and sets the volume to zero.
  61170. * Then increases the volume from 0 to 1 over the duration specified.
  61171. *
  61172. * At the end of the fade Sound.onFadeComplete is dispatched with this Sound object as the first parameter,
  61173. * and the final volume (1) as the second parameter.
  61174. *
  61175. * @method Phaser.Sound#fadeIn
  61176. * @param {number} [duration=1000] - The time in milliseconds over which the Sound should fade in.
  61177. * @param {boolean} [loop=false] - Should the Sound be set to loop? Note that this doesn't cause the fade to repeat.
  61178. * @param {string} [marker=(current marker)] - The marker to start at; defaults to the current (last played) marker. To start playing from the beginning specify specify a marker of `''`.
  61179. */
  61180. fadeIn: function (duration, loop, marker) {
  61181. if (loop === undefined) { loop = false; }
  61182. if (marker === undefined) { marker = this.currentMarker; }
  61183. if (this.paused)
  61184. {
  61185. return;
  61186. }
  61187. this.play(marker, 0, 0, loop);
  61188. this.fadeTo(duration, 1);
  61189. },
  61190. /**
  61191. * Decreases the volume of this Sound from its current value to 0 over the duration specified.
  61192. * At the end of the fade Sound.onFadeComplete is dispatched with this Sound object as the first parameter,
  61193. * and the final volume (0) as the second parameter.
  61194. *
  61195. * @method Phaser.Sound#fadeOut
  61196. * @param {number} [duration=1000] - The time in milliseconds over which the Sound should fade out.
  61197. */
  61198. fadeOut: function (duration) {
  61199. this.fadeTo(duration, 0);
  61200. },
  61201. /**
  61202. * Fades the volume of this Sound from its current value to the given volume over the duration specified.
  61203. * At the end of the fade Sound.onFadeComplete is dispatched with this Sound object as the first parameter,
  61204. * and the final volume (volume) as the second parameter.
  61205. *
  61206. * @method Phaser.Sound#fadeTo
  61207. * @param {number} [duration=1000] - The time in milliseconds during which the Sound should fade out.
  61208. * @param {number} [volume] - The volume which the Sound should fade to. This is a value between 0 and 1.
  61209. */
  61210. fadeTo: function (duration, volume) {
  61211. if (!this.isPlaying || this.paused || volume === this.volume)
  61212. {
  61213. return;
  61214. }
  61215. if (duration === undefined) { duration = 1000; }
  61216. if (volume === undefined)
  61217. {
  61218. console.warn("Phaser.Sound.fadeTo: No Volume Specified.");
  61219. return;
  61220. }
  61221. this.fadeTween = this.game.add.tween(this).to( { volume: volume }, duration, Phaser.Easing.Linear.None, true);
  61222. this.fadeTween.onComplete.add(this.fadeComplete, this);
  61223. },
  61224. /**
  61225. * Internal handler for Sound.fadeIn, Sound.fadeOut and Sound.fadeTo.
  61226. *
  61227. * @method Phaser.Sound#fadeComplete
  61228. * @private
  61229. */
  61230. fadeComplete: function () {
  61231. this.onFadeComplete.dispatch(this, this.volume);
  61232. if (this.volume === 0)
  61233. {
  61234. this.stop();
  61235. }
  61236. },
  61237. /**
  61238. * Called automatically by SoundManager.volume.
  61239. *
  61240. * Sets the volume of AudioTag Sounds as a percentage of the Global Volume.
  61241. *
  61242. * You should not normally call this directly.
  61243. *
  61244. * @method Phaser.Sound#updateGlobalVolume
  61245. * @protected
  61246. * @param {float} globalVolume - The global SoundManager volume.
  61247. */
  61248. updateGlobalVolume: function (globalVolume) {
  61249. // this._volume is the % of the global volume this sound should be played at
  61250. if (this.usingAudioTag && this._sound)
  61251. {
  61252. this._sound.volume = globalVolume * this._volume;
  61253. }
  61254. },
  61255. /**
  61256. * Destroys this sound and all associated events and removes it from the SoundManager.
  61257. *
  61258. * @method Phaser.Sound#destroy
  61259. * @param {boolean} [remove=true] - If true this Sound is automatically removed from the SoundManager.
  61260. */
  61261. destroy: function (remove) {
  61262. if (remove === undefined) { remove = true; }
  61263. this.stop();
  61264. if (remove)
  61265. {
  61266. this.game.sound.remove(this);
  61267. }
  61268. else
  61269. {
  61270. this.markers = {};
  61271. this.context = null;
  61272. this._buffer = null;
  61273. this.externalNode = null;
  61274. this.onDecoded.dispose();
  61275. this.onPlay.dispose();
  61276. this.onPause.dispose();
  61277. this.onResume.dispose();
  61278. this.onLoop.dispose();
  61279. this.onStop.dispose();
  61280. this.onMute.dispose();
  61281. this.onMarkerComplete.dispose();
  61282. }
  61283. }
  61284. };
  61285. Phaser.Sound.prototype.constructor = Phaser.Sound;
  61286. /**
  61287. * @name Phaser.Sound#isDecoding
  61288. * @property {boolean} isDecoding - Returns true if the sound file is still decoding.
  61289. * @readonly
  61290. */
  61291. Object.defineProperty(Phaser.Sound.prototype, "isDecoding", {
  61292. get: function () {
  61293. return this.game.cache.getSound(this.key).isDecoding;
  61294. }
  61295. });
  61296. /**
  61297. * @name Phaser.Sound#isDecoded
  61298. * @property {boolean} isDecoded - Returns true if the sound file has decoded.
  61299. * @readonly
  61300. */
  61301. Object.defineProperty(Phaser.Sound.prototype, "isDecoded", {
  61302. get: function () {
  61303. return this.game.cache.isSoundDecoded(this.key);
  61304. }
  61305. });
  61306. /**
  61307. * @name Phaser.Sound#mute
  61308. * @property {boolean} mute - Gets or sets the muted state of this sound.
  61309. */
  61310. Object.defineProperty(Phaser.Sound.prototype, "mute", {
  61311. get: function () {
  61312. return (this._muted || this.game.sound.mute);
  61313. },
  61314. set: function (value) {
  61315. value = value || false;
  61316. if (value === this._muted)
  61317. {
  61318. return;
  61319. }
  61320. if (value)
  61321. {
  61322. this._muted = true;
  61323. this._muteVolume = this._tempVolume;
  61324. if (this.usingWebAudio)
  61325. {
  61326. this.gainNode.gain.value = 0;
  61327. }
  61328. else if (this.usingAudioTag && this._sound)
  61329. {
  61330. this._sound.volume = 0;
  61331. }
  61332. }
  61333. else
  61334. {
  61335. this._muted = false;
  61336. if (this.usingWebAudio)
  61337. {
  61338. this.gainNode.gain.value = this._muteVolume;
  61339. }
  61340. else if (this.usingAudioTag && this._sound)
  61341. {
  61342. this._sound.volume = this._muteVolume;
  61343. }
  61344. }
  61345. this.onMute.dispatch(this);
  61346. }
  61347. });
  61348. /**
  61349. * @name Phaser.Sound#volume
  61350. * @property {number} volume - Gets or sets the volume of this sound, a value between 0 and 1.
  61351. * @readonly
  61352. */
  61353. Object.defineProperty(Phaser.Sound.prototype, "volume", {
  61354. get: function () {
  61355. return this._volume;
  61356. },
  61357. set: function (value) {
  61358. // Causes an Index size error in Firefox if you don't clamp the value
  61359. if (this.game.device.firefox && this.usingAudioTag)
  61360. {
  61361. value = this.game.math.clamp(value, 0, 1);
  61362. }
  61363. if (this._muted)
  61364. {
  61365. this._muteVolume = value;
  61366. return;
  61367. }
  61368. this._tempVolume = value;
  61369. this._volume = value;
  61370. if (this.usingWebAudio)
  61371. {
  61372. this.gainNode.gain.value = value;
  61373. }
  61374. else if (this.usingAudioTag && this._sound)
  61375. {
  61376. this._sound.volume = value;
  61377. }
  61378. }
  61379. });
  61380. /**
  61381. * @author Richard Davey <rich@photonstorm.com>
  61382. * @copyright 2016 Photon Storm Ltd.
  61383. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  61384. */
  61385. /**
  61386. * 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.
  61387. * Note: On Firefox 25+ on Linux if you have media.gstreamer disabled in about:config then it cannot play back mp3 or m4a files.
  61388. * The audio file type and the encoding of those files are extremely important. Not all browsers can play all audio formats.
  61389. * There is a good guide to what's supported here: http://hpr.dogphilosophy.net/test/
  61390. *
  61391. * If you are reloading a Phaser Game on a page that never properly refreshes (such as in an AngularJS project) then you will quickly run out
  61392. * of AudioContext nodes. If this is the case create a global var called PhaserGlobal on the window object before creating the game. The active
  61393. * AudioContext will then be saved to window.PhaserGlobal.audioContext when the Phaser game is destroyed, and re-used when it starts again.
  61394. *
  61395. * Mobile warning: There are some mobile devices (certain iPad 2 and iPad Mini revisions) that cannot play 48000 Hz audio.
  61396. * When they try to play the audio becomes extremely distorted and buzzes, eventually crashing the sound system.
  61397. * The solution is to use a lower encoding rate such as 44100 Hz. Sometimes the audio context will
  61398. * be created with a sampleRate of 48000. If this happens and audio distorts you should re-create the context.
  61399. *
  61400. * @class Phaser.SoundManager
  61401. * @constructor
  61402. * @param {Phaser.Game} game - Reference to the current game instance.
  61403. */
  61404. Phaser.SoundManager = function (game) {
  61405. /**
  61406. * @property {Phaser.Game} game - Local reference to game.
  61407. */
  61408. this.game = game;
  61409. /**
  61410. * @property {Phaser.Signal} onSoundDecode - The event dispatched when a sound decodes (typically only for mp3 files)
  61411. */
  61412. this.onSoundDecode = new Phaser.Signal();
  61413. /**
  61414. * This signal is dispatched whenever the global volume changes. The new volume is passed as the only parameter to your callback.
  61415. * @property {Phaser.Signal} onVolumeChange
  61416. */
  61417. this.onVolumeChange = new Phaser.Signal();
  61418. /**
  61419. * This signal is dispatched when the SoundManager is globally muted, either directly via game code or as a result of the game pausing.
  61420. * @property {Phaser.Signal} onMute
  61421. */
  61422. this.onMute = new Phaser.Signal();
  61423. /**
  61424. * This signal is dispatched when the SoundManager is globally un-muted, either directly via game code or as a result of the game resuming from a pause.
  61425. * @property {Phaser.Signal} onUnMute
  61426. */
  61427. this.onUnMute = new Phaser.Signal();
  61428. /**
  61429. * @property {AudioContext} context - The AudioContext being used for playback.
  61430. * @default
  61431. */
  61432. this.context = null;
  61433. /**
  61434. * @property {boolean} usingWebAudio - True the SoundManager and device are both using Web Audio.
  61435. * @readonly
  61436. */
  61437. this.usingWebAudio = false;
  61438. /**
  61439. * @property {boolean} usingAudioTag - True the SoundManager and device are both using the Audio tag instead of Web Audio.
  61440. * @readonly
  61441. */
  61442. this.usingAudioTag = false;
  61443. /**
  61444. * @property {boolean} noAudio - True if audio been disabled via the PhaserGlobal (useful if you need to use a 3rd party audio library) or the device doesn't support any audio.
  61445. * @default
  61446. */
  61447. this.noAudio = false;
  61448. /**
  61449. * @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.
  61450. * @default
  61451. */
  61452. this.connectToMaster = true;
  61453. /**
  61454. * @property {boolean} touchLocked - true if the audio system is currently locked awaiting a touch event.
  61455. * @default
  61456. */
  61457. this.touchLocked = false;
  61458. /**
  61459. * @property {number} channels - The number of audio channels to use in playback.
  61460. * @default
  61461. */
  61462. this.channels = 32;
  61463. /**
  61464. * Set to true to have all sound muted when the Phaser game pauses (such as on loss of focus),
  61465. * or set to false to keep audio playing, regardless of the game pause state. You may need to
  61466. * do this should you wish to control audio muting via external DOM buttons or similar.
  61467. * @property {boolean} muteOnPause
  61468. * @default
  61469. */
  61470. this.muteOnPause = true;
  61471. /**
  61472. * @property {boolean} _codeMuted - Internal mute tracking var.
  61473. * @private
  61474. * @default
  61475. */
  61476. this._codeMuted = false;
  61477. /**
  61478. * @property {boolean} _muted - Internal mute tracking var.
  61479. * @private
  61480. * @default
  61481. */
  61482. this._muted = false;
  61483. /**
  61484. * @property {AudioContext} _unlockSource - Internal unlock tracking var.
  61485. * @private
  61486. * @default
  61487. */
  61488. this._unlockSource = null;
  61489. /**
  61490. * @property {number} _volume - The global audio volume. A value between 0 (silence) and 1 (full volume).
  61491. * @private
  61492. * @default
  61493. */
  61494. this._volume = 1;
  61495. /**
  61496. * @property {array} _sounds - An array containing all the sounds
  61497. * @private
  61498. */
  61499. this._sounds = [];
  61500. /**
  61501. * @property {Phaser.ArraySet} _watchList - An array set containing all the sounds being monitored for decoding status.
  61502. * @private
  61503. */
  61504. this._watchList = new Phaser.ArraySet();
  61505. /**
  61506. * @property {boolean} _watching - Is the SoundManager monitoring the watchList?
  61507. * @private
  61508. */
  61509. this._watching = false;
  61510. /**
  61511. * @property {function} _watchCallback - The callback to invoke once the watchlist is clear.
  61512. * @private
  61513. */
  61514. this._watchCallback = null;
  61515. /**
  61516. * @property {object} _watchContext - The context in which to call the watchlist callback.
  61517. * @private
  61518. */
  61519. this._watchContext = null;
  61520. };
  61521. Phaser.SoundManager.prototype = {
  61522. /**
  61523. * Initialises the sound manager.
  61524. * @method Phaser.SoundManager#boot
  61525. * @protected
  61526. */
  61527. boot: function () {
  61528. if (this.game.device.iOS && this.game.device.webAudio === false)
  61529. {
  61530. this.channels = 1;
  61531. }
  61532. // PhaserGlobal overrides
  61533. if (window['PhaserGlobal'])
  61534. {
  61535. // Check to see if all audio playback is disabled (i.e. handled by a 3rd party class)
  61536. if (window['PhaserGlobal'].disableAudio === true)
  61537. {
  61538. this.noAudio = true;
  61539. this.touchLocked = false;
  61540. return;
  61541. }
  61542. // Check if the Web Audio API is disabled (for testing Audio Tag playback during development)
  61543. if (window['PhaserGlobal'].disableWebAudio === true)
  61544. {
  61545. this.usingAudioTag = true;
  61546. this.touchLocked = false;
  61547. return;
  61548. }
  61549. }
  61550. if (window['PhaserGlobal'] && window['PhaserGlobal'].audioContext)
  61551. {
  61552. this.context = window['PhaserGlobal'].audioContext;
  61553. }
  61554. else
  61555. {
  61556. if (!!window['AudioContext'])
  61557. {
  61558. try {
  61559. this.context = new window['AudioContext']();
  61560. } catch (error) {
  61561. this.context = null;
  61562. this.usingWebAudio = false;
  61563. this.touchLocked = false;
  61564. }
  61565. }
  61566. else if (!!window['webkitAudioContext'])
  61567. {
  61568. try {
  61569. this.context = new window['webkitAudioContext']();
  61570. } catch (error) {
  61571. this.context = null;
  61572. this.usingWebAudio = false;
  61573. this.touchLocked = false;
  61574. }
  61575. }
  61576. }
  61577. if (this.context === null)
  61578. {
  61579. // No Web Audio support - how about legacy Audio?
  61580. if (window['Audio'] === undefined)
  61581. {
  61582. this.noAudio = true;
  61583. return;
  61584. }
  61585. else
  61586. {
  61587. this.usingAudioTag = true;
  61588. }
  61589. }
  61590. else
  61591. {
  61592. this.usingWebAudio = true;
  61593. if (this.context.createGain === undefined)
  61594. {
  61595. this.masterGain = this.context.createGainNode();
  61596. }
  61597. else
  61598. {
  61599. this.masterGain = this.context.createGain();
  61600. }
  61601. this.masterGain.gain.value = 1;
  61602. this.masterGain.connect(this.context.destination);
  61603. }
  61604. if (!this.noAudio)
  61605. {
  61606. // On mobile we need a native touch event before we can play anything, so capture it here
  61607. if (!this.game.device.cocoonJS && this.game.device.iOS || (window['PhaserGlobal'] && window['PhaserGlobal'].fakeiOSTouchLock))
  61608. {
  61609. this.setTouchLock();
  61610. }
  61611. }
  61612. },
  61613. /**
  61614. * Sets the Input Manager touch callback to be SoundManager.unlock.
  61615. * Required for iOS audio device unlocking. Mostly just used internally.
  61616. *
  61617. * @method Phaser.SoundManager#setTouchLock
  61618. */
  61619. setTouchLock: function () {
  61620. if (this.noAudio || (window['PhaserGlobal'] && window['PhaserGlobal'].disableAudio === true))
  61621. {
  61622. return;
  61623. }
  61624. if (this.game.device.iOSVersion > 8)
  61625. {
  61626. this.game.input.touch.addTouchLockCallback(this.unlock, this, true);
  61627. }
  61628. else
  61629. {
  61630. this.game.input.touch.addTouchLockCallback(this.unlock, this);
  61631. }
  61632. this.touchLocked = true;
  61633. },
  61634. /**
  61635. * Enables the audio, usually after the first touch.
  61636. *
  61637. * @method Phaser.SoundManager#unlock
  61638. * @return {boolean} True if the callback should be removed, otherwise false.
  61639. */
  61640. unlock: function () {
  61641. if (this.noAudio || !this.touchLocked || this._unlockSource !== null)
  61642. {
  61643. return true;
  61644. }
  61645. // Global override (mostly for Audio Tag testing)
  61646. if (this.usingAudioTag)
  61647. {
  61648. this.touchLocked = false;
  61649. this._unlockSource = null;
  61650. }
  61651. else if (this.usingWebAudio)
  61652. {
  61653. // Create empty buffer and play it
  61654. // The SoundManager.update loop captures the state of it and then resets touchLocked to false
  61655. var buffer = this.context.createBuffer(1, 1, 22050);
  61656. this._unlockSource = this.context.createBufferSource();
  61657. this._unlockSource.buffer = buffer;
  61658. this._unlockSource.connect(this.context.destination);
  61659. if (this._unlockSource.start === undefined)
  61660. {
  61661. this._unlockSource.noteOn(0);
  61662. }
  61663. else
  61664. {
  61665. this._unlockSource.start(0);
  61666. }
  61667. }
  61668. // We can remove the event because we've done what we needed (started the unlock sound playing)
  61669. return true;
  61670. },
  61671. /**
  61672. * Stops all the sounds in the game.
  61673. *
  61674. * @method Phaser.SoundManager#stopAll
  61675. */
  61676. stopAll: function () {
  61677. if (this.noAudio)
  61678. {
  61679. return;
  61680. }
  61681. for (var i = 0; i < this._sounds.length; i++)
  61682. {
  61683. if (this._sounds[i])
  61684. {
  61685. this._sounds[i].stop();
  61686. }
  61687. }
  61688. },
  61689. /**
  61690. * Pauses all the sounds in the game.
  61691. *
  61692. * @method Phaser.SoundManager#pauseAll
  61693. */
  61694. pauseAll: function () {
  61695. if (this.noAudio)
  61696. {
  61697. return;
  61698. }
  61699. for (var i = 0; i < this._sounds.length; i++)
  61700. {
  61701. if (this._sounds[i])
  61702. {
  61703. this._sounds[i].pause();
  61704. }
  61705. }
  61706. },
  61707. /**
  61708. * Resumes every sound in the game.
  61709. *
  61710. * @method Phaser.SoundManager#resumeAll
  61711. */
  61712. resumeAll: function () {
  61713. if (this.noAudio)
  61714. {
  61715. return;
  61716. }
  61717. for (var i = 0; i < this._sounds.length; i++)
  61718. {
  61719. if (this._sounds[i])
  61720. {
  61721. this._sounds[i].resume();
  61722. }
  61723. }
  61724. },
  61725. /**
  61726. * Decode a sound by its asset key.
  61727. *
  61728. * @method Phaser.SoundManager#decode
  61729. * @param {string} key - Assets key of the sound to be decoded.
  61730. * @param {Phaser.Sound} [sound] - Its buffer will be set to decoded data.
  61731. */
  61732. decode: function (key, sound) {
  61733. sound = sound || null;
  61734. var soundData = this.game.cache.getSoundData(key);
  61735. if (soundData)
  61736. {
  61737. if (this.game.cache.isSoundDecoded(key) === false)
  61738. {
  61739. this.game.cache.updateSound(key, 'isDecoding', true);
  61740. var _this = this;
  61741. try {
  61742. this.context.decodeAudioData(soundData, function (buffer) {
  61743. if (buffer)
  61744. {
  61745. _this.game.cache.decodedSound(key, buffer);
  61746. _this.onSoundDecode.dispatch(key, sound);
  61747. }
  61748. });
  61749. }
  61750. catch (e) {}
  61751. }
  61752. }
  61753. },
  61754. /**
  61755. * This method allows you to give the SoundManager a list of Sound files, or keys, and a callback.
  61756. * Once all of the Sound files have finished decoding the callback will be invoked.
  61757. * The amount of time spent decoding depends on the codec used and file size.
  61758. * If all of the files given have already decoded the callback is triggered immediately.
  61759. *
  61760. * @method Phaser.SoundManager#setDecodedCallback
  61761. * @param {string|array} files - An array containing either Phaser.Sound objects or their key strings as found in the Phaser.Cache.
  61762. * @param {Function} callback - The callback which will be invoked once all files have finished decoding.
  61763. * @param {Object} callbackContext - The context in which the callback will run.
  61764. */
  61765. setDecodedCallback: function (files, callback, callbackContext) {
  61766. if (typeof files === 'string')
  61767. {
  61768. files = [ files ];
  61769. }
  61770. this._watchList.reset();
  61771. for (var i = 0; i < files.length; i++)
  61772. {
  61773. if (files[i] instanceof Phaser.Sound)
  61774. {
  61775. if (!this.game.cache.isSoundDecoded(files[i].key))
  61776. {
  61777. this._watchList.add(files[i].key);
  61778. }
  61779. }
  61780. else if (!this.game.cache.isSoundDecoded(files[i]))
  61781. {
  61782. this._watchList.add(files[i]);
  61783. }
  61784. }
  61785. // All decoded already?
  61786. if (this._watchList.total === 0)
  61787. {
  61788. this._watching = false;
  61789. callback.call(callbackContext);
  61790. }
  61791. else
  61792. {
  61793. this._watching = true;
  61794. this._watchCallback = callback;
  61795. this._watchContext = callbackContext;
  61796. }
  61797. },
  61798. /**
  61799. * Updates every sound in the game, checks for audio unlock on mobile and monitors the decoding watch list.
  61800. *
  61801. * @method Phaser.SoundManager#update
  61802. * @protected
  61803. */
  61804. update: function () {
  61805. if (this.noAudio)
  61806. {
  61807. return;
  61808. }
  61809. if (this.touchLocked && this._unlockSource !== null && (this._unlockSource.playbackState === this._unlockSource.PLAYING_STATE || this._unlockSource.playbackState === this._unlockSource.FINISHED_STATE))
  61810. {
  61811. this.touchLocked = false;
  61812. this._unlockSource = null;
  61813. }
  61814. for (var i = 0; i < this._sounds.length; i++)
  61815. {
  61816. this._sounds[i].update();
  61817. }
  61818. if (this._watching)
  61819. {
  61820. var key = this._watchList.first;
  61821. while (key)
  61822. {
  61823. if (this.game.cache.isSoundDecoded(key))
  61824. {
  61825. this._watchList.remove(key);
  61826. }
  61827. key = this._watchList.next;
  61828. }
  61829. if (this._watchList.total === 0)
  61830. {
  61831. this._watching = false;
  61832. this._watchCallback.call(this._watchContext);
  61833. }
  61834. }
  61835. },
  61836. /**
  61837. * Adds a new Sound into the SoundManager.
  61838. *
  61839. * @method Phaser.SoundManager#add
  61840. * @param {string} key - Asset key for the sound.
  61841. * @param {number} [volume=1] - Default value for the volume.
  61842. * @param {boolean} [loop=false] - Whether or not the sound will loop.
  61843. * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio.
  61844. * @return {Phaser.Sound} The new sound instance.
  61845. */
  61846. add: function (key, volume, loop, connect) {
  61847. if (volume === undefined) { volume = 1; }
  61848. if (loop === undefined) { loop = false; }
  61849. if (connect === undefined) { connect = this.connectToMaster; }
  61850. var sound = new Phaser.Sound(this.game, key, volume, loop, connect);
  61851. this._sounds.push(sound);
  61852. return sound;
  61853. },
  61854. /**
  61855. * Adds a new AudioSprite into the SoundManager.
  61856. *
  61857. * @method Phaser.SoundManager#addSprite
  61858. * @param {string} key - Asset key for the sound.
  61859. * @return {Phaser.AudioSprite} The new AudioSprite instance.
  61860. */
  61861. addSprite: function(key) {
  61862. var audioSprite = new Phaser.AudioSprite(this.game, key);
  61863. return audioSprite;
  61864. },
  61865. /**
  61866. * Removes a Sound from the SoundManager. The removed Sound is destroyed before removal.
  61867. *
  61868. * @method Phaser.SoundManager#remove
  61869. * @param {Phaser.Sound} sound - The sound object to remove.
  61870. * @return {boolean} True if the sound was removed successfully, otherwise false.
  61871. */
  61872. remove: function (sound) {
  61873. var i = this._sounds.length;
  61874. while (i--)
  61875. {
  61876. if (this._sounds[i] === sound)
  61877. {
  61878. this._sounds[i].destroy(false);
  61879. this._sounds.splice(i, 1);
  61880. return true;
  61881. }
  61882. }
  61883. return false;
  61884. },
  61885. /**
  61886. * Removes all Sounds from the SoundManager that have an asset key matching the given value.
  61887. * The removed Sounds are destroyed before removal.
  61888. *
  61889. * @method Phaser.SoundManager#removeByKey
  61890. * @param {string} key - The key to match when removing sound objects.
  61891. * @return {number} The number of matching sound objects that were removed.
  61892. */
  61893. removeByKey: function (key) {
  61894. var i = this._sounds.length;
  61895. var removed = 0;
  61896. while (i--)
  61897. {
  61898. if (this._sounds[i].key === key)
  61899. {
  61900. this._sounds[i].destroy(false);
  61901. this._sounds.splice(i, 1);
  61902. removed++;
  61903. }
  61904. }
  61905. return removed;
  61906. },
  61907. /**
  61908. * Adds a new Sound into the SoundManager and starts it playing.
  61909. *
  61910. * @method Phaser.SoundManager#play
  61911. * @param {string} key - Asset key for the sound.
  61912. * @param {number} [volume=1] - Default value for the volume.
  61913. * @param {boolean} [loop=false] - Whether or not the sound will loop.
  61914. * @return {Phaser.Sound} The new sound instance.
  61915. */
  61916. play: function (key, volume, loop) {
  61917. if (this.noAudio)
  61918. {
  61919. return;
  61920. }
  61921. var sound = this.add(key, volume, loop);
  61922. sound.play();
  61923. return sound;
  61924. },
  61925. /**
  61926. * Internal mute handler called automatically by the SoundManager.mute setter.
  61927. *
  61928. * @method Phaser.SoundManager#setMute
  61929. * @private
  61930. */
  61931. setMute: function () {
  61932. if (this._muted)
  61933. {
  61934. return;
  61935. }
  61936. this._muted = true;
  61937. if (this.usingWebAudio)
  61938. {
  61939. this._muteVolume = this.masterGain.gain.value;
  61940. this.masterGain.gain.value = 0;
  61941. }
  61942. // Loop through sounds
  61943. for (var i = 0; i < this._sounds.length; i++)
  61944. {
  61945. if (this._sounds[i].usingAudioTag)
  61946. {
  61947. this._sounds[i].mute = true;
  61948. }
  61949. }
  61950. this.onMute.dispatch();
  61951. },
  61952. /**
  61953. * Internal mute handler called automatically by the SoundManager.mute setter.
  61954. *
  61955. * @method Phaser.SoundManager#unsetMute
  61956. * @private
  61957. */
  61958. unsetMute: function () {
  61959. if (!this._muted || this._codeMuted)
  61960. {
  61961. return;
  61962. }
  61963. this._muted = false;
  61964. if (this.usingWebAudio)
  61965. {
  61966. this.masterGain.gain.value = this._muteVolume;
  61967. }
  61968. // Loop through sounds
  61969. for (var i = 0; i < this._sounds.length; i++)
  61970. {
  61971. if (this._sounds[i].usingAudioTag)
  61972. {
  61973. this._sounds[i].mute = false;
  61974. }
  61975. }
  61976. this.onUnMute.dispatch();
  61977. },
  61978. /**
  61979. * Stops all the sounds in the game, then destroys them and finally clears up any callbacks.
  61980. *
  61981. * @method Phaser.SoundManager#destroy
  61982. */
  61983. destroy: function () {
  61984. this.stopAll();
  61985. for (var i = 0; i < this._sounds.length; i++)
  61986. {
  61987. if (this._sounds[i])
  61988. {
  61989. this._sounds[i].destroy();
  61990. }
  61991. }
  61992. this._sounds = [];
  61993. this.onSoundDecode.dispose();
  61994. if (this.context)
  61995. {
  61996. if (window['PhaserGlobal'])
  61997. {
  61998. // Store this in the PhaserGlobal window var, if set, to allow for re-use if the game is created again without the page refreshing
  61999. window['PhaserGlobal'].audioContext = this.context;
  62000. }
  62001. else
  62002. {
  62003. if (this.context.close)
  62004. {
  62005. this.context.close();
  62006. }
  62007. }
  62008. }
  62009. }
  62010. };
  62011. Phaser.SoundManager.prototype.constructor = Phaser.SoundManager;
  62012. /**
  62013. * @name Phaser.SoundManager#mute
  62014. * @property {boolean} mute - Gets or sets the muted state of the SoundManager. This effects all sounds in the game.
  62015. */
  62016. Object.defineProperty(Phaser.SoundManager.prototype, "mute", {
  62017. get: function () {
  62018. return this._muted;
  62019. },
  62020. set: function (value) {
  62021. value = value || false;
  62022. if (value)
  62023. {
  62024. if (this._muted)
  62025. {
  62026. return;
  62027. }
  62028. this._codeMuted = true;
  62029. this.setMute();
  62030. }
  62031. else
  62032. {
  62033. if (!this._muted)
  62034. {
  62035. return;
  62036. }
  62037. this._codeMuted = false;
  62038. this.unsetMute();
  62039. }
  62040. }
  62041. });
  62042. /**
  62043. * @name Phaser.SoundManager#volume
  62044. * @property {number} volume - Gets or sets the global volume of the SoundManager, a value between 0 and 1. The value given is clamped to the range 0 to 1.
  62045. */
  62046. Object.defineProperty(Phaser.SoundManager.prototype, "volume", {
  62047. get: function () {
  62048. return this._volume;
  62049. },
  62050. set: function (value) {
  62051. if (value < 0)
  62052. {
  62053. value = 0;
  62054. }
  62055. else if (value > 1)
  62056. {
  62057. value = 1;
  62058. }
  62059. if (this._volume !== value)
  62060. {
  62061. this._volume = value;
  62062. if (this.usingWebAudio)
  62063. {
  62064. this.masterGain.gain.value = value;
  62065. }
  62066. else
  62067. {
  62068. // Loop through the sound cache and change the volume of all html audio tags
  62069. for (var i = 0; i < this._sounds.length; i++)
  62070. {
  62071. if (this._sounds[i].usingAudioTag)
  62072. {
  62073. this._sounds[i].updateGlobalVolume(value);
  62074. }
  62075. }
  62076. }
  62077. this.onVolumeChange.dispatch(value);
  62078. }
  62079. }
  62080. });
  62081. /**
  62082. * @author Richard Davey <rich@photonstorm.com>
  62083. * @copyright 2016 Photon Storm Ltd.
  62084. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  62085. */
  62086. /**
  62087. * @classdesc
  62088. * The ScaleManager object handles the the scaling, resizing, and alignment of the
  62089. * Game size and the game Display canvas.
  62090. *
  62091. * The Game size is the logical size of the game; the Display canvas has size as an HTML element.
  62092. *
  62093. * The calculations of these are heavily influenced by the bounding Parent size which is the computed
  62094. * dimensions of the Display canvas's Parent container/element - the _effective CSS rules of the
  62095. * canvas's Parent element play an important role_ in the operation of the ScaleManager.
  62096. *
  62097. * The Display canvas - or Game size, depending {@link #scaleMode} - is updated to best utilize the Parent size.
  62098. * When in Fullscreen mode or with {@link #parentIsWindow} the Parent size is that of the visual viewport (see {@link Phaser.ScaleManager#getParentBounds getParentBounds}).
  62099. *
  62100. * Parent and Display canvas containment guidelines:
  62101. *
  62102. * - Style the Parent element (of the game canvas) to control the Parent size and
  62103. * thus the Display canvas's size and layout.
  62104. *
  62105. * - The Parent element's CSS styles should _effectively_ apply maximum (and minimum) bounding behavior.
  62106. *
  62107. * - The Parent element should _not_ apply a padding as this is not accounted for.
  62108. * If a padding is required apply it to the Parent's parent or apply a margin to the Parent.
  62109. * If you need to add a border, margin or any other CSS around your game container, then use a parent element and
  62110. * apply the CSS to this instead, otherwise you'll be constantly resizing the shape of the game container.
  62111. *
  62112. * - The Display canvas layout CSS styles (i.e. margins, size) should not be altered/specified as
  62113. * they may be updated by the ScaleManager.
  62114. *
  62115. * @description
  62116. * Create a new ScaleManager object - this is done automatically by {@link Phaser.Game}
  62117. *
  62118. * The `width` and `height` constructor parameters can either be a number which represents pixels or a string that represents a percentage: e.g. `800` (for 800 pixels) or `"80%"` for 80%.
  62119. *
  62120. * @class
  62121. * @param {Phaser.Game} game - A reference to the currently running game.
  62122. * @param {number|string} width - The width of the game. See above.
  62123. * @param {number|string} height - The height of the game. See above.
  62124. */
  62125. Phaser.ScaleManager = function (game, width, height) {
  62126. /**
  62127. * A reference to the currently running game.
  62128. * @property {Phaser.Game} game
  62129. * @protected
  62130. * @readonly
  62131. */
  62132. this.game = game;
  62133. /**
  62134. * Provides access to some cross-device DOM functions.
  62135. * @property {Phaser.DOM} dom
  62136. * @protected
  62137. * @readonly
  62138. */
  62139. this.dom = Phaser.DOM;
  62140. /**
  62141. * _EXPERIMENTAL:_ A responsive grid on which you can align game objects.
  62142. * @property {Phaser.FlexGrid} grid
  62143. * @public
  62144. */
  62145. this.grid = null;
  62146. /**
  62147. * Target width (in pixels) of the Display canvas.
  62148. * @property {number} width
  62149. * @readonly
  62150. */
  62151. this.width = 0;
  62152. /**
  62153. * Target height (in pixels) of the Display canvas.
  62154. * @property {number} height
  62155. * @readonly
  62156. */
  62157. this.height = 0;
  62158. /**
  62159. * Minimum width the canvas should be scaled to (in pixels).
  62160. * Change with {@link #setMinMax}.
  62161. * @property {?number} minWidth
  62162. * @readonly
  62163. * @protected
  62164. */
  62165. this.minWidth = null;
  62166. /**
  62167. * Maximum width the canvas should be scaled to (in pixels).
  62168. * If null it will scale to whatever width the browser can handle.
  62169. * Change with {@link #setMinMax}.
  62170. * @property {?number} maxWidth
  62171. * @readonly
  62172. * @protected
  62173. */
  62174. this.maxWidth = null;
  62175. /**
  62176. * Minimum height the canvas should be scaled to (in pixels).
  62177. * Change with {@link #setMinMax}.
  62178. * @property {?number} minHeight
  62179. * @readonly
  62180. * @protected
  62181. */
  62182. this.minHeight = null;
  62183. /**
  62184. * Maximum height the canvas should be scaled to (in pixels).
  62185. * If null it will scale to whatever height the browser can handle.
  62186. * Change with {@link #setMinMax}.
  62187. * @property {?number} maxHeight
  62188. * @readonly
  62189. * @protected
  62190. */
  62191. this.maxHeight = null;
  62192. /**
  62193. * The offset coordinates of the Display canvas from the top-left of the browser window.
  62194. * The is used internally by Phaser.Pointer (for Input) and possibly other types.
  62195. * @property {Phaser.Point} offset
  62196. * @readonly
  62197. * @protected
  62198. */
  62199. this.offset = new Phaser.Point();
  62200. /**
  62201. * If true, the game should only run in a landscape orientation.
  62202. * Change with {@link #forceOrientation}.
  62203. * @property {boolean} forceLandscape
  62204. * @readonly
  62205. * @default
  62206. * @protected
  62207. */
  62208. this.forceLandscape = false;
  62209. /**
  62210. * If true, the game should only run in a portrait
  62211. * Change with {@link #forceOrientation}.
  62212. * @property {boolean} forcePortrait
  62213. * @readonly
  62214. * @default
  62215. * @protected
  62216. */
  62217. this.forcePortrait = false;
  62218. /**
  62219. * True if {@link #forceLandscape} or {@link #forcePortrait} are set and do not agree with the browser orientation.
  62220. *
  62221. * This value is not updated immediately.
  62222. *
  62223. * @property {boolean} incorrectOrientation
  62224. * @readonly
  62225. * @protected
  62226. */
  62227. this.incorrectOrientation = false;
  62228. /**
  62229. * See {@link #pageAlignHorizontally}.
  62230. * @property {boolean} _pageAlignHorizontally
  62231. * @private
  62232. */
  62233. this._pageAlignHorizontally = false;
  62234. /**
  62235. * See {@link #pageAlignVertically}.
  62236. * @property {boolean} _pageAlignVertically
  62237. * @private
  62238. */
  62239. this._pageAlignVertically = false;
  62240. /**
  62241. * This signal is dispatched when the orientation changes _or_ the validity of the current orientation changes.
  62242. *
  62243. * The signal is supplied with the following arguments:
  62244. * - `scale` - the ScaleManager object
  62245. * - `prevOrientation`, a string - The previous orientation as per {@link Phaser.ScaleManager#screenOrientation screenOrientation}.
  62246. * - `wasIncorrect`, a boolean - True if the previous orientation was last determined to be incorrect.
  62247. *
  62248. * Access the current orientation and validity with `scale.screenOrientation` and `scale.incorrectOrientation`.
  62249. * Thus the following tests can be done:
  62250. *
  62251. * // The orientation itself changed:
  62252. * scale.screenOrientation !== prevOrientation
  62253. * // The orientation just became incorrect:
  62254. * scale.incorrectOrientation && !wasIncorrect
  62255. *
  62256. * It is possible that this signal is triggered after {@link #forceOrientation} so the orientation
  62257. * correctness changes even if the orientation itself does not change.
  62258. *
  62259. * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused.
  62260. *
  62261. * @property {Phaser.Signal} onOrientationChange
  62262. * @public
  62263. */
  62264. this.onOrientationChange = new Phaser.Signal();
  62265. /**
  62266. * This signal is dispatched when the browser enters an incorrect orientation, as defined by {@link #forceOrientation}.
  62267. *
  62268. * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused.
  62269. *
  62270. * @property {Phaser.Signal} enterIncorrectOrientation
  62271. * @public
  62272. */
  62273. this.enterIncorrectOrientation = new Phaser.Signal();
  62274. /**
  62275. * This signal is dispatched when the browser leaves an incorrect orientation, as defined by {@link #forceOrientation}.
  62276. *
  62277. * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused.
  62278. *
  62279. * @property {Phaser.Signal} leaveIncorrectOrientation
  62280. * @public
  62281. */
  62282. this.leaveIncorrectOrientation = new Phaser.Signal();
  62283. /**
  62284. * If specified, this is the DOM element on which the Fullscreen API enter request will be invoked.
  62285. * The target element must have the correct CSS styling and contain the Display canvas.
  62286. *
  62287. * The elements style will be modified (ie. the width and height might be set to 100%)
  62288. * but it will not be added to, removed from, or repositioned within the DOM.
  62289. * An attempt is made to restore relevant style changes when fullscreen mode is left.
  62290. *
  62291. * For pre-2.2.0 behavior set `game.scale.fullScreenTarget = game.canvas`.
  62292. *
  62293. * @property {?DOMElement} fullScreenTarget
  62294. * @default
  62295. */
  62296. this.fullScreenTarget = null;
  62297. /**
  62298. * The fullscreen target, as created by {@link #createFullScreenTarget}.
  62299. * This is not set if {@link #fullScreenTarget} is used and is cleared when fullscreen mode ends.
  62300. * @property {?DOMElement} _createdFullScreenTarget
  62301. * @private
  62302. */
  62303. this._createdFullScreenTarget = null;
  62304. /**
  62305. * This signal is dispatched when fullscreen mode is ready to be initialized but
  62306. * before the fullscreen request.
  62307. *
  62308. * The signal is passed two arguments: `scale` (the ScaleManager), and an object in the form `{targetElement: DOMElement}`.
  62309. *
  62310. * The `targetElement` is the {@link #fullScreenTarget} element,
  62311. * if such is assigned, or a new element created by {@link #createFullScreenTarget}.
  62312. *
  62313. * Custom CSS styling or resets can be applied to `targetElement` as required.
  62314. *
  62315. * If `targetElement` is _not_ the same element as {@link #fullScreenTarget}:
  62316. * - After initialization the Display canvas is moved onto the `targetElement` for
  62317. * the duration of the fullscreen mode, and restored to it's original DOM location when fullscreen is exited.
  62318. * - The `targetElement` is moved/re-parented within the DOM and may have its CSS styles updated.
  62319. *
  62320. * The behavior of a pre-assigned target element is covered in {@link Phaser.ScaleManager#fullScreenTarget fullScreenTarget}.
  62321. *
  62322. * @property {Phaser.Signal} onFullScreenInit
  62323. * @public
  62324. */
  62325. this.onFullScreenInit = new Phaser.Signal();
  62326. /**
  62327. * This signal is dispatched when the browser enters or leaves fullscreen mode, if supported.
  62328. *
  62329. * The signal is supplied with a single argument: `scale` (the ScaleManager). Use `scale.isFullScreen` to determine
  62330. * if currently running in Fullscreen mode.
  62331. *
  62332. * @property {Phaser.Signal} onFullScreenChange
  62333. * @public
  62334. */
  62335. this.onFullScreenChange = new Phaser.Signal();
  62336. /**
  62337. * This signal is dispatched when the browser fails to enter fullscreen mode;
  62338. * or if the device does not support fullscreen mode and `startFullScreen` is invoked.
  62339. *
  62340. * The signal is supplied with a single argument: `scale` (the ScaleManager).
  62341. *
  62342. * @property {Phaser.Signal} onFullScreenError
  62343. * @public
  62344. */
  62345. this.onFullScreenError = new Phaser.Signal();
  62346. /**
  62347. * The _last known_ orientation of the screen, as defined in the Window Screen Web API.
  62348. * See {@link Phaser.DOM.getScreenOrientation} for possible values.
  62349. *
  62350. * @property {string} screenOrientation
  62351. * @readonly
  62352. * @public
  62353. */
  62354. this.screenOrientation = this.dom.getScreenOrientation();
  62355. /**
  62356. * The _current_ scale factor based on the game dimensions vs. the scaled dimensions.
  62357. * @property {Phaser.Point} scaleFactor
  62358. * @readonly
  62359. */
  62360. this.scaleFactor = new Phaser.Point(1, 1);
  62361. /**
  62362. * The _current_ inversed scale factor. The displayed dimensions divided by the game dimensions.
  62363. * @property {Phaser.Point} scaleFactorInversed
  62364. * @readonly
  62365. * @protected
  62366. */
  62367. this.scaleFactorInversed = new Phaser.Point(1, 1);
  62368. /**
  62369. * The Display canvas is aligned by adjusting the margins; the last margins are stored here.
  62370. *
  62371. * @property {Bounds-like} margin
  62372. * @readonly
  62373. * @protected
  62374. */
  62375. this.margin = {left: 0, top: 0, right: 0, bottom: 0, x: 0, y: 0};
  62376. /**
  62377. * The bounds of the scaled game. The x/y will match the offset of the canvas element and the width/height the scaled width and height.
  62378. * @property {Phaser.Rectangle} bounds
  62379. * @readonly
  62380. */
  62381. this.bounds = new Phaser.Rectangle();
  62382. /**
  62383. * The aspect ratio of the scaled Display canvas.
  62384. * @property {number} aspectRatio
  62385. * @readonly
  62386. */
  62387. this.aspectRatio = 0;
  62388. /**
  62389. * The aspect ratio of the original game dimensions.
  62390. * @property {number} sourceAspectRatio
  62391. * @readonly
  62392. */
  62393. this.sourceAspectRatio = 0;
  62394. /**
  62395. * The native browser events from Fullscreen API changes.
  62396. * @property {any} event
  62397. * @readonly
  62398. * @private
  62399. */
  62400. this.event = null;
  62401. /**
  62402. * The edges on which to constrain the game Display/canvas in _addition_ to the restrictions of the parent container.
  62403. *
  62404. * The properties are strings and can be '', 'visual', 'layout', or 'layout-soft'.
  62405. * - If 'visual', the edge will be constrained to the Window / displayed screen area
  62406. * - If 'layout', the edge will be constrained to the CSS Layout bounds
  62407. * - An invalid value is treated as 'visual'
  62408. *
  62409. * @member
  62410. * @property {string} bottom
  62411. * @property {string} right
  62412. * @default
  62413. */
  62414. this.windowConstraints = {
  62415. right: 'layout',
  62416. bottom: ''
  62417. };
  62418. /**
  62419. * Various compatibility settings.
  62420. * A value of "(auto)" indicates the setting is configured based on device and runtime information.
  62421. *
  62422. * A {@link #refresh} may need to be performed after making changes.
  62423. *
  62424. * @protected
  62425. *
  62426. * @property {boolean} [supportsFullScreen=(auto)] - True only if fullscreen support will be used. (Changing to fullscreen still might not work.)
  62427. *
  62428. * @property {boolean} [orientationFallback=(auto)] - See {@link Phaser.DOM.getScreenOrientation}.
  62429. *
  62430. * @property {boolean} [noMargins=false] - If true then the Display canvas's margins will not be updated anymore: existing margins must be manually cleared. Disabling margins prevents automatic canvas alignment/centering, possibly in fullscreen.
  62431. *
  62432. * @property {?Phaser.Point} [scrollTo=(auto)] - If specified the window will be scrolled to this position on every refresh.
  62433. *
  62434. * @property {boolean} [forceMinimumDocumentHeight=false] - If enabled the document elements minimum height is explicitly set on updates.
  62435. * The height set varies by device and may either be the height of the window or the viewport.
  62436. *
  62437. * @property {boolean} [canExpandParent=true] - If enabled then SHOW_ALL and USER_SCALE modes can try and expand the parent element. It may be necessary for the parent element to impose CSS width/height restrictions.
  62438. *
  62439. * @property {string} [clickTrampoline=(auto)] - On certain browsers (eg. IE) FullScreen events need to be triggered via 'click' events.
  62440. * A value of 'when-not-mouse' uses a click trampoline when a pointer that is not the primary mouse is used.
  62441. * Any other string value (including the empty string) prevents using click trampolines.
  62442. * For more details on click trampolines see {@link Phaser.Pointer#addClickTrampoline}.
  62443. */
  62444. this.compatibility = {
  62445. supportsFullScreen: false,
  62446. orientationFallback: null,
  62447. noMargins: false,
  62448. scrollTo: null,
  62449. forceMinimumDocumentHeight: false,
  62450. canExpandParent: true,
  62451. clickTrampoline: ''
  62452. };
  62453. /**
  62454. * Scale mode to be used when not in fullscreen.
  62455. * @property {number} _scaleMode
  62456. * @private
  62457. */
  62458. this._scaleMode = Phaser.ScaleManager.NO_SCALE;
  62459. /*
  62460. * Scale mode to be used in fullscreen.
  62461. * @property {number} _fullScreenScaleMode
  62462. * @private
  62463. */
  62464. this._fullScreenScaleMode = Phaser.ScaleManager.NO_SCALE;
  62465. /**
  62466. * If the parent container of the Game canvas is the browser window itself (i.e. document.body),
  62467. * rather than another div, this should set to `true`.
  62468. *
  62469. * The {@link #parentNode} property is generally ignored while this is in effect.
  62470. *
  62471. * @property {boolean} parentIsWindow
  62472. */
  62473. this.parentIsWindow = false;
  62474. /**
  62475. * The _original_ DOM element for the parent of the Display canvas.
  62476. * This may be different in fullscreen - see {@link #createFullScreenTarget}.
  62477. *
  62478. * This should only be changed after moving the Game canvas to a different DOM parent.
  62479. *
  62480. * @property {?DOMElement} parentNode
  62481. */
  62482. this.parentNode = null;
  62483. /**
  62484. * The scale of the game in relation to its parent container.
  62485. * @property {Phaser.Point} parentScaleFactor
  62486. * @readonly
  62487. */
  62488. this.parentScaleFactor = new Phaser.Point(1, 1);
  62489. /**
  62490. * The maximum time (in ms) between dimension update checks for the Canvas's parent element (or window).
  62491. * Update checks normally happen quicker in response to other events.
  62492. *
  62493. * @property {integer} trackParentInterval
  62494. * @default
  62495. * @protected
  62496. * @see {@link Phaser.ScaleManager#refresh refresh}
  62497. */
  62498. this.trackParentInterval = 2000;
  62499. /**
  62500. * This signal is dispatched when the size of the Display canvas changes _or_ the size of the Game changes.
  62501. * When invoked this is done _after_ the Canvas size/position have been updated.
  62502. *
  62503. * This signal is _only_ called when a change occurs and a reflow may be required.
  62504. * For example, if the canvas does not change sizes because of CSS settings (such as min-width)
  62505. * then this signal will _not_ be triggered.
  62506. *
  62507. * Use this to handle responsive game layout options.
  62508. *
  62509. * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused.
  62510. *
  62511. * @property {Phaser.Signal} onSizeChange
  62512. * @todo Formalize the arguments, if any, supplied to this signal.
  62513. */
  62514. this.onSizeChange = new Phaser.Signal();
  62515. /**
  62516. * The callback that will be called each the parent container resizes.
  62517. * @property {function} onResize
  62518. * @private
  62519. */
  62520. this.onResize = null;
  62521. /**
  62522. * The context in which the {@link #onResize} callback will be called.
  62523. * @property {object} onResizeContext
  62524. * @private
  62525. */
  62526. this.onResizeContext = null;
  62527. /**
  62528. * @property {integer} _pendingScaleMode - Used to retain the scale mode if set from config before Boot.
  62529. * @private
  62530. */
  62531. this._pendingScaleMode = null;
  62532. /**
  62533. * Information saved when fullscreen mode is started.
  62534. * @property {?object} _fullScreenRestore
  62535. * @private
  62536. */
  62537. this._fullScreenRestore = null;
  62538. /**
  62539. * The _actual_ game dimensions, as initially set or set by {@link #setGameSize}.
  62540. * @property {Phaser.Rectangle} _gameSize
  62541. * @private
  62542. */
  62543. this._gameSize = new Phaser.Rectangle();
  62544. /**
  62545. * The user-supplied scale factor, used with the USER_SCALE scaling mode.
  62546. * @property {Phaser.Point} _userScaleFactor
  62547. * @private
  62548. */
  62549. this._userScaleFactor = new Phaser.Point(1, 1);
  62550. /**
  62551. * The user-supplied scale trim, used with the USER_SCALE scaling mode.
  62552. * @property {Phaser.Point} _userScaleTrim
  62553. * @private
  62554. */
  62555. this._userScaleTrim = new Phaser.Point(0, 0);
  62556. /**
  62557. * The last time the bounds were checked in `preUpdate`.
  62558. * @property {number} _lastUpdate
  62559. * @private
  62560. */
  62561. this._lastUpdate = 0;
  62562. /**
  62563. * Size checks updates are delayed according to the throttle.
  62564. * The throttle increases to `trackParentInterval` over time and is used to more
  62565. * rapidly detect changes in certain browsers (eg. IE) while providing back-off safety.
  62566. * @property {integer} _updateThrottle
  62567. * @private
  62568. */
  62569. this._updateThrottle = 0;
  62570. /**
  62571. * The minimum throttle allowed until it has slowed down sufficiently.
  62572. * @property {integer} _updateThrottleReset
  62573. * @private
  62574. */
  62575. this._updateThrottleReset = 100;
  62576. /**
  62577. * The cached result of the parent (possibly window) bounds; used to invalidate sizing.
  62578. * @property {Phaser.Rectangle} _parentBounds
  62579. * @private
  62580. */
  62581. this._parentBounds = new Phaser.Rectangle();
  62582. /**
  62583. * Temporary bounds used for internal work to cut down on new objects created.
  62584. * @property {Phaser.Rectangle} _parentBounds
  62585. * @private
  62586. */
  62587. this._tempBounds = new Phaser.Rectangle();
  62588. /**
  62589. * The Canvas size at which the last onSizeChange signal was triggered.
  62590. * @property {Phaser.Rectangle} _lastReportedCanvasSize
  62591. * @private
  62592. */
  62593. this._lastReportedCanvasSize = new Phaser.Rectangle();
  62594. /**
  62595. * The Game size at which the last onSizeChange signal was triggered.
  62596. * @property {Phaser.Rectangle} _lastReportedGameSize
  62597. * @private
  62598. */
  62599. this._lastReportedGameSize = new Phaser.Rectangle();
  62600. /**
  62601. * @property {boolean} _booted - ScaleManager booted state.
  62602. * @private
  62603. */
  62604. this._booted = false;
  62605. if (game.config)
  62606. {
  62607. this.parseConfig(game.config);
  62608. }
  62609. this.setupScale(width, height);
  62610. };
  62611. /**
  62612. * A scale mode that stretches content to fill all available space - see {@link Phaser.ScaleManager#scaleMode scaleMode}.
  62613. *
  62614. * @constant
  62615. * @type {integer}
  62616. */
  62617. Phaser.ScaleManager.EXACT_FIT = 0;
  62618. /**
  62619. * A scale mode that prevents any scaling - see {@link Phaser.ScaleManager#scaleMode scaleMode}.
  62620. *
  62621. * @constant
  62622. * @type {integer}
  62623. */
  62624. Phaser.ScaleManager.NO_SCALE = 1;
  62625. /**
  62626. * A scale mode that shows the entire game while maintaining proportions - see {@link Phaser.ScaleManager#scaleMode scaleMode}.
  62627. *
  62628. * @constant
  62629. * @type {integer}
  62630. */
  62631. Phaser.ScaleManager.SHOW_ALL = 2;
  62632. /**
  62633. * A scale mode that causes the Game size to change - see {@link Phaser.ScaleManager#scaleMode scaleMode}.
  62634. *
  62635. * @constant
  62636. * @type {integer}
  62637. */
  62638. Phaser.ScaleManager.RESIZE = 3;
  62639. /**
  62640. * A scale mode that allows a custom scale factor - see {@link Phaser.ScaleManager#scaleMode scaleMode}.
  62641. *
  62642. * @constant
  62643. * @type {integer}
  62644. */
  62645. Phaser.ScaleManager.USER_SCALE = 4;
  62646. Phaser.ScaleManager.prototype = {
  62647. /**
  62648. * Start the ScaleManager.
  62649. *
  62650. * @method Phaser.ScaleManager#boot
  62651. * @protected
  62652. */
  62653. boot: function () {
  62654. // Configure device-dependent compatibility
  62655. var compat = this.compatibility;
  62656. compat.supportsFullScreen = this.game.device.fullscreen && !this.game.device.cocoonJS;
  62657. // We can't do anything about the status bars in iPads, web apps or desktops
  62658. if (!this.game.device.iPad && !this.game.device.webApp && !this.game.device.desktop)
  62659. {
  62660. if (this.game.device.android && !this.game.device.chrome)
  62661. {
  62662. compat.scrollTo = new Phaser.Point(0, 1);
  62663. }
  62664. else
  62665. {
  62666. compat.scrollTo = new Phaser.Point(0, 0);
  62667. }
  62668. }
  62669. if (this.game.device.desktop)
  62670. {
  62671. compat.orientationFallback = 'screen';
  62672. compat.clickTrampoline = 'when-not-mouse';
  62673. }
  62674. else
  62675. {
  62676. compat.orientationFallback = '';
  62677. compat.clickTrampoline = '';
  62678. }
  62679. // Configure event listeners
  62680. var _this = this;
  62681. this._orientationChange = function(event) {
  62682. return _this.orientationChange(event);
  62683. };
  62684. this._windowResize = function(event) {
  62685. return _this.windowResize(event);
  62686. };
  62687. // This does not appear to be on the standards track
  62688. window.addEventListener('orientationchange', this._orientationChange, false);
  62689. window.addEventListener('resize', this._windowResize, false);
  62690. if (this.compatibility.supportsFullScreen)
  62691. {
  62692. this._fullScreenChange = function(event) {
  62693. return _this.fullScreenChange(event);
  62694. };
  62695. this._fullScreenError = function(event) {
  62696. return _this.fullScreenError(event);
  62697. };
  62698. document.addEventListener('webkitfullscreenchange', this._fullScreenChange, false);
  62699. document.addEventListener('mozfullscreenchange', this._fullScreenChange, false);
  62700. document.addEventListener('MSFullscreenChange', this._fullScreenChange, false);
  62701. document.addEventListener('fullscreenchange', this._fullScreenChange, false);
  62702. document.addEventListener('webkitfullscreenerror', this._fullScreenError, false);
  62703. document.addEventListener('mozfullscreenerror', this._fullScreenError, false);
  62704. document.addEventListener('MSFullscreenError', this._fullScreenError, false);
  62705. document.addEventListener('fullscreenerror', this._fullScreenError, false);
  62706. }
  62707. this.game.onResume.add(this._gameResumed, this);
  62708. // Initialize core bounds
  62709. this.dom.getOffset(this.game.canvas, this.offset);
  62710. this.bounds.setTo(this.offset.x, this.offset.y, this.width, this.height);
  62711. this.setGameSize(this.game.width, this.game.height);
  62712. // Don't use updateOrientationState so events are not fired
  62713. this.screenOrientation = this.dom.getScreenOrientation(this.compatibility.orientationFallback);
  62714. if (Phaser.FlexGrid)
  62715. {
  62716. this.grid = new Phaser.FlexGrid(this, this.width, this.height);
  62717. }
  62718. this._booted = true;
  62719. if (this._pendingScaleMode !== null)
  62720. {
  62721. this.scaleMode = this._pendingScaleMode;
  62722. this._pendingScaleMode = null;
  62723. }
  62724. },
  62725. /**
  62726. * Load configuration settings.
  62727. *
  62728. * @method Phaser.ScaleManager#parseConfig
  62729. * @protected
  62730. * @param {object} config - The game configuration object.
  62731. */
  62732. parseConfig: function (config) {
  62733. if (config['scaleMode'] !== undefined)
  62734. {
  62735. if (this._booted)
  62736. {
  62737. this.scaleMode = config['scaleMode'];
  62738. }
  62739. else
  62740. {
  62741. this._pendingScaleMode = config['scaleMode'];
  62742. }
  62743. }
  62744. if (config['fullScreenScaleMode'] !== undefined)
  62745. {
  62746. this.fullScreenScaleMode = config['fullScreenScaleMode'];
  62747. }
  62748. if (config['fullScreenTarget'])
  62749. {
  62750. this.fullScreenTarget = config['fullScreenTarget'];
  62751. }
  62752. },
  62753. /**
  62754. * Calculates and sets the game dimensions based on the given width and height.
  62755. *
  62756. * This should _not_ be called when in fullscreen mode.
  62757. *
  62758. * @method Phaser.ScaleManager#setupScale
  62759. * @protected
  62760. * @param {number|string} width - The width of the game.
  62761. * @param {number|string} height - The height of the game.
  62762. */
  62763. setupScale: function (width, height) {
  62764. var target;
  62765. var rect = new Phaser.Rectangle();
  62766. if (this.game.parent !== '')
  62767. {
  62768. if (typeof this.game.parent === 'string')
  62769. {
  62770. // hopefully an element ID
  62771. target = document.getElementById(this.game.parent);
  62772. }
  62773. else if (this.game.parent && this.game.parent.nodeType === 1)
  62774. {
  62775. // quick test for a HTMLelement
  62776. target = this.game.parent;
  62777. }
  62778. }
  62779. // Fallback, covers an invalid ID and a non HTMLelement object
  62780. if (!target)
  62781. {
  62782. // Use the full window
  62783. this.parentNode = null;
  62784. this.parentIsWindow = true;
  62785. rect.width = this.dom.visualBounds.width;
  62786. rect.height = this.dom.visualBounds.height;
  62787. this.offset.set(0, 0);
  62788. }
  62789. else
  62790. {
  62791. this.parentNode = target;
  62792. this.parentIsWindow = false;
  62793. this.getParentBounds(this._parentBounds);
  62794. rect.width = this._parentBounds.width;
  62795. rect.height = this._parentBounds.height;
  62796. this.offset.set(this._parentBounds.x, this._parentBounds.y);
  62797. }
  62798. var newWidth = 0;
  62799. var newHeight = 0;
  62800. if (typeof width === 'number')
  62801. {
  62802. newWidth = width;
  62803. }
  62804. else
  62805. {
  62806. // Percentage based
  62807. this.parentScaleFactor.x = parseInt(width, 10) / 100;
  62808. newWidth = rect.width * this.parentScaleFactor.x;
  62809. }
  62810. if (typeof height === 'number')
  62811. {
  62812. newHeight = height;
  62813. }
  62814. else
  62815. {
  62816. // Percentage based
  62817. this.parentScaleFactor.y = parseInt(height, 10) / 100;
  62818. newHeight = rect.height * this.parentScaleFactor.y;
  62819. }
  62820. newWidth = Math.floor(newWidth);
  62821. newHeight = Math.floor(newHeight);
  62822. this._gameSize.setTo(0, 0, newWidth, newHeight);
  62823. this.updateDimensions(newWidth, newHeight, false);
  62824. },
  62825. /**
  62826. * Invoked when the game is resumed.
  62827. *
  62828. * @method Phaser.ScaleManager#_gameResumed
  62829. * @private
  62830. */
  62831. _gameResumed: function () {
  62832. this.queueUpdate(true);
  62833. },
  62834. /**
  62835. * Set the actual Game size.
  62836. * Use this instead of directly changing `game.width` or `game.height`.
  62837. *
  62838. * The actual physical display (Canvas element size) depends on various settings including
  62839. * - Scale mode
  62840. * - Scaling factor
  62841. * - Size of Canvas's parent element or CSS rules such as min-height/max-height;
  62842. * - The size of the Window
  62843. *
  62844. * @method Phaser.ScaleManager#setGameSize
  62845. * @public
  62846. * @param {integer} width - _Game width_, in pixels.
  62847. * @param {integer} height - _Game height_, in pixels.
  62848. */
  62849. setGameSize: function (width, height) {
  62850. this._gameSize.setTo(0, 0, width, height);
  62851. if (this.currentScaleMode !== Phaser.ScaleManager.RESIZE)
  62852. {
  62853. this.updateDimensions(width, height, true);
  62854. }
  62855. this.queueUpdate(true);
  62856. },
  62857. /**
  62858. * Set a User scaling factor used in the USER_SCALE scaling mode.
  62859. *
  62860. * The target canvas size is computed by:
  62861. *
  62862. * canvas.width = (game.width * hScale) - hTrim
  62863. * canvas.height = (game.height * vScale) - vTrim
  62864. *
  62865. * This method can be used in the {@link Phaser.ScaleManager#setResizeCallback resize callback}.
  62866. *
  62867. * @method Phaser.ScaleManager#setUserScale
  62868. * @param {number} hScale - Horizontal scaling factor.
  62869. * @param {numer} vScale - Vertical scaling factor.
  62870. * @param {integer} [hTrim=0] - Horizontal trim, applied after scaling.
  62871. * @param {integer} [vTrim=0] - Vertical trim, applied after scaling.
  62872. */
  62873. setUserScale: function (hScale, vScale, hTrim, vTrim) {
  62874. this._userScaleFactor.setTo(hScale, vScale);
  62875. this._userScaleTrim.setTo(hTrim | 0, vTrim | 0);
  62876. this.queueUpdate(true);
  62877. },
  62878. /**
  62879. * Sets the callback that will be invoked before sizing calculations.
  62880. *
  62881. * This is the appropriate place to call {@link #setUserScale} if needing custom dynamic scaling.
  62882. *
  62883. * The callback is supplied with two arguments `scale` and `parentBounds` where `scale` is the ScaleManager
  62884. * and `parentBounds`, a Phaser.Rectangle, is the size of the Parent element.
  62885. *
  62886. * This callback
  62887. * - May be invoked even though the parent container or canvas sizes have not changed
  62888. * - Unlike {@link #onSizeChange}, it runs _before_ the canvas is guaranteed to be updated
  62889. * - Will be invoked from `preUpdate`, _even when_ the game is paused
  62890. *
  62891. * See {@link #onSizeChange} for a better way of reacting to layout updates.
  62892. *
  62893. * @method Phaser.ScaleManager#setResizeCallback
  62894. * @public
  62895. * @param {function} callback - The callback that will be called each time a window.resize event happens or if set, the parent container resizes.
  62896. * @param {object} context - The context in which the callback will be called.
  62897. */
  62898. setResizeCallback: function (callback, context) {
  62899. this.onResize = callback;
  62900. this.onResizeContext = context;
  62901. },
  62902. /**
  62903. * Signals a resize - IF the canvas or Game size differs from the last signal.
  62904. *
  62905. * This also triggers updates on {@link #grid} (FlexGrid) and, if in a RESIZE mode, `game.state` (StateManager).
  62906. *
  62907. * @method Phaser.ScaleManager#signalSizeChange
  62908. * @private
  62909. */
  62910. signalSizeChange: function () {
  62911. if (!Phaser.Rectangle.sameDimensions(this, this._lastReportedCanvasSize) ||
  62912. !Phaser.Rectangle.sameDimensions(this.game, this._lastReportedGameSize))
  62913. {
  62914. var width = this.width;
  62915. var height = this.height;
  62916. this._lastReportedCanvasSize.setTo(0, 0, width, height);
  62917. this._lastReportedGameSize.setTo(0, 0, this.game.width, this.game.height);
  62918. if (this.grid)
  62919. {
  62920. this.grid.onResize(width, height);
  62921. }
  62922. this.onSizeChange.dispatch(this, width, height);
  62923. // Per StateManager#onResizeCallback, it only occurs when in RESIZE mode.
  62924. if (this.currentScaleMode === Phaser.ScaleManager.RESIZE)
  62925. {
  62926. this.game.state.resize(width, height);
  62927. this.game.load.resize(width, height);
  62928. }
  62929. }
  62930. },
  62931. /**
  62932. * Set the min and max dimensions for the Display canvas.
  62933. *
  62934. * _Note:_ The min/max dimensions are only applied in some cases
  62935. * - When the device is not in an incorrect orientation; or
  62936. * - The scale mode is EXACT_FIT when not in fullscreen
  62937. *
  62938. * @method Phaser.ScaleManager#setMinMax
  62939. * @public
  62940. * @param {number} minWidth - The minimum width the game is allowed to scale down to.
  62941. * @param {number} minHeight - The minimum height the game is allowed to scale down to.
  62942. * @param {number} [maxWidth] - The maximum width the game is allowed to scale up to; only changed if specified.
  62943. * @param {number} [maxHeight] - The maximum height the game is allowed to scale up to; only changed if specified.
  62944. * @todo These values are only sometimes honored.
  62945. */
  62946. setMinMax: function (minWidth, minHeight, maxWidth, maxHeight) {
  62947. this.minWidth = minWidth;
  62948. this.minHeight = minHeight;
  62949. if (typeof maxWidth !== 'undefined')
  62950. {
  62951. this.maxWidth = maxWidth;
  62952. }
  62953. if (typeof maxHeight !== 'undefined')
  62954. {
  62955. this.maxHeight = maxHeight;
  62956. }
  62957. },
  62958. /**
  62959. * The ScaleManager.preUpdate is called automatically by the core Game loop.
  62960. *
  62961. * @method Phaser.ScaleManager#preUpdate
  62962. * @protected
  62963. */
  62964. preUpdate: function () {
  62965. if (this.game.time.time < (this._lastUpdate + this._updateThrottle))
  62966. {
  62967. return;
  62968. }
  62969. var prevThrottle = this._updateThrottle;
  62970. this._updateThrottleReset = prevThrottle >= 400 ? 0 : 100;
  62971. this.dom.getOffset(this.game.canvas, this.offset);
  62972. var prevWidth = this._parentBounds.width;
  62973. var prevHeight = this._parentBounds.height;
  62974. var bounds = this.getParentBounds(this._parentBounds);
  62975. var boundsChanged = bounds.width !== prevWidth || bounds.height !== prevHeight;
  62976. // Always invalidate on a newly detected orientation change
  62977. var orientationChanged = this.updateOrientationState();
  62978. if (boundsChanged || orientationChanged)
  62979. {
  62980. if (this.onResize)
  62981. {
  62982. this.onResize.call(this.onResizeContext, this, bounds);
  62983. }
  62984. this.updateLayout();
  62985. this.signalSizeChange();
  62986. }
  62987. // Next throttle, eg. 25, 50, 100, 200..
  62988. var throttle = this._updateThrottle * 2;
  62989. // Don't let an update be too eager about resetting the throttle.
  62990. if (this._updateThrottle < prevThrottle)
  62991. {
  62992. throttle = Math.min(prevThrottle, this._updateThrottleReset);
  62993. }
  62994. this._updateThrottle = Phaser.Math.clamp(throttle, 25, this.trackParentInterval);
  62995. this._lastUpdate = this.game.time.time;
  62996. },
  62997. /**
  62998. * Update method while paused.
  62999. *
  63000. * @method Phaser.ScaleManager#pauseUpdate
  63001. * @private
  63002. */
  63003. pauseUpdate: function () {
  63004. this.preUpdate();
  63005. // Updates at slowest.
  63006. this._updateThrottle = this.trackParentInterval;
  63007. },
  63008. /**
  63009. * Update the dimensions taking the parent scaling factor into account.
  63010. *
  63011. * @method Phaser.ScaleManager#updateDimensions
  63012. * @private
  63013. * @param {number} width - The new width of the parent container.
  63014. * @param {number} height - The new height of the parent container.
  63015. * @param {boolean} resize - True if the renderer should be resized, otherwise false to just update the internal vars.
  63016. */
  63017. updateDimensions: function (width, height, resize) {
  63018. this.width = width * this.parentScaleFactor.x;
  63019. this.height = height * this.parentScaleFactor.y;
  63020. this.game.width = this.width;
  63021. this.game.height = this.height;
  63022. this.sourceAspectRatio = this.width / this.height;
  63023. this.updateScalingAndBounds();
  63024. if (resize)
  63025. {
  63026. // Resize the renderer (which in turn resizes the Display canvas!)
  63027. this.game.renderer.resize(this.width, this.height);
  63028. // The Camera can never be smaller than the Game size
  63029. this.game.camera.setSize(this.width, this.height);
  63030. // This should only happen if the world is smaller than the new canvas size
  63031. this.game.world.resize(this.width, this.height);
  63032. }
  63033. },
  63034. /**
  63035. * Update relevant scaling values based on the ScaleManager dimension and game dimensions,
  63036. * which should already be set. This does not change {@link #sourceAspectRatio}.
  63037. *
  63038. * @method Phaser.ScaleManager#updateScalingAndBounds
  63039. * @private
  63040. */
  63041. updateScalingAndBounds: function () {
  63042. this.scaleFactor.x = this.game.width / this.width;
  63043. this.scaleFactor.y = this.game.height / this.height;
  63044. this.scaleFactorInversed.x = this.width / this.game.width;
  63045. this.scaleFactorInversed.y = this.height / this.game.height;
  63046. this.aspectRatio = this.width / this.height;
  63047. // This can be invoked in boot pre-canvas
  63048. if (this.game.canvas)
  63049. {
  63050. this.dom.getOffset(this.game.canvas, this.offset);
  63051. }
  63052. this.bounds.setTo(this.offset.x, this.offset.y, this.width, this.height);
  63053. // Can be invoked in boot pre-input
  63054. if (this.game.input && this.game.input.scale)
  63055. {
  63056. this.game.input.scale.setTo(this.scaleFactor.x, this.scaleFactor.y);
  63057. }
  63058. },
  63059. /**
  63060. * Force the game to run in only one orientation.
  63061. *
  63062. * This enables generation of incorrect orientation signals and affects resizing but does not otherwise rotate or lock the orientation.
  63063. *
  63064. * Orientation checks are performed via the Screen Orientation API, if available in browser. This means it will check your monitor
  63065. * orientation on desktop, or your device orientation on mobile, rather than comparing actual game dimensions. If you need to check the
  63066. * viewport dimensions instead and bypass the Screen Orientation API then set: `ScaleManager.compatibility.orientationFallback = 'viewport'`
  63067. *
  63068. * @method Phaser.ScaleManager#forceOrientation
  63069. * @public
  63070. * @param {boolean} forceLandscape - true if the game should run in landscape mode only.
  63071. * @param {boolean} [forcePortrait=false] - true if the game should run in portrait mode only.
  63072. */
  63073. forceOrientation: function (forceLandscape, forcePortrait) {
  63074. if (forcePortrait === undefined) { forcePortrait = false; }
  63075. this.forceLandscape = forceLandscape;
  63076. this.forcePortrait = forcePortrait;
  63077. this.queueUpdate(true);
  63078. },
  63079. /**
  63080. * Classify the orientation, per `getScreenOrientation`.
  63081. *
  63082. * @method Phaser.ScaleManager#classifyOrientation
  63083. * @private
  63084. * @param {string} orientation - The orientation string, e.g. 'portrait-primary'.
  63085. * @return {?string} The classified orientation: 'portrait', 'landscape`, or null.
  63086. */
  63087. classifyOrientation: function (orientation) {
  63088. if (orientation === 'portrait-primary' || orientation === 'portrait-secondary')
  63089. {
  63090. return 'portrait';
  63091. }
  63092. else if (orientation === 'landscape-primary' || orientation === 'landscape-secondary')
  63093. {
  63094. return 'landscape';
  63095. }
  63096. else
  63097. {
  63098. return null;
  63099. }
  63100. },
  63101. /**
  63102. * Updates the current orientation and dispatches orientation change events.
  63103. *
  63104. * @method Phaser.ScaleManager#updateOrientationState
  63105. * @private
  63106. * @return {boolean} True if the orientation state changed which means a forced update is likely required.
  63107. */
  63108. updateOrientationState: function () {
  63109. var previousOrientation = this.screenOrientation;
  63110. var previouslyIncorrect = this.incorrectOrientation;
  63111. this.screenOrientation = this.dom.getScreenOrientation(this.compatibility.orientationFallback);
  63112. this.incorrectOrientation = (this.forceLandscape && !this.isLandscape) ||
  63113. (this.forcePortrait && !this.isPortrait);
  63114. var changed = previousOrientation !== this.screenOrientation;
  63115. var correctnessChanged = previouslyIncorrect !== this.incorrectOrientation;
  63116. if (correctnessChanged)
  63117. {
  63118. if (this.incorrectOrientation)
  63119. {
  63120. this.enterIncorrectOrientation.dispatch();
  63121. }
  63122. else
  63123. {
  63124. this.leaveIncorrectOrientation.dispatch();
  63125. }
  63126. }
  63127. if (changed || correctnessChanged)
  63128. {
  63129. this.onOrientationChange.dispatch(this, previousOrientation, previouslyIncorrect);
  63130. }
  63131. return changed || correctnessChanged;
  63132. },
  63133. /**
  63134. * window.orientationchange event handler.
  63135. *
  63136. * @method Phaser.ScaleManager#orientationChange
  63137. * @private
  63138. * @param {Event} event - The orientationchange event data.
  63139. */
  63140. orientationChange: function (event) {
  63141. this.event = event;
  63142. this.queueUpdate(true);
  63143. },
  63144. /**
  63145. * window.resize event handler.
  63146. *
  63147. * @method Phaser.ScaleManager#windowResize
  63148. * @private
  63149. * @param {Event} event - The resize event data.
  63150. */
  63151. windowResize: function (event) {
  63152. this.event = event;
  63153. this.queueUpdate(true);
  63154. },
  63155. /**
  63156. * Scroll to the top - in some environments. See `compatibility.scrollTo`.
  63157. *
  63158. * @method Phaser.ScaleManager#scrollTop
  63159. * @private
  63160. */
  63161. scrollTop: function () {
  63162. var scrollTo = this.compatibility.scrollTo;
  63163. if (scrollTo)
  63164. {
  63165. window.scrollTo(scrollTo.x, scrollTo.y);
  63166. }
  63167. },
  63168. /**
  63169. * The "refresh" methods informs the ScaleManager that a layout refresh is required.
  63170. *
  63171. * The ScaleManager automatically queues a layout refresh (eg. updates the Game size or Display canvas layout)
  63172. * when the browser is resized, the orientation changes, or when there is a detected change
  63173. * of the Parent size. Refreshing is also done automatically when public properties,
  63174. * such as {@link #scaleMode}, are updated or state-changing methods are invoked.
  63175. *
  63176. * The "refresh" method _may_ need to be used in a few (rare) situtations when
  63177. *
  63178. * - a device change event is not correctly detected; or
  63179. * - the Parent size changes (and an immediate reflow is desired); or
  63180. * - the ScaleManager state is updated by non-standard means; or
  63181. * - certain {@link #compatibility} properties are manually changed.
  63182. *
  63183. * The queued layout refresh is not immediate but will run promptly in an upcoming `preRender`.
  63184. *
  63185. * @method Phaser.ScaleManager#refresh
  63186. * @public
  63187. */
  63188. refresh: function () {
  63189. this.scrollTop();
  63190. this.queueUpdate(true);
  63191. },
  63192. /**
  63193. * Updates the game / canvas position and size.
  63194. *
  63195. * @method Phaser.ScaleManager#updateLayout
  63196. * @private
  63197. */
  63198. updateLayout: function () {
  63199. var scaleMode = this.currentScaleMode;
  63200. if (scaleMode === Phaser.ScaleManager.RESIZE)
  63201. {
  63202. this.reflowGame();
  63203. return;
  63204. }
  63205. this.scrollTop();
  63206. if (this.compatibility.forceMinimumDocumentHeight)
  63207. {
  63208. // (This came from older code, by why is it here?)
  63209. // Set minimum height of content to new window height
  63210. document.documentElement.style.minHeight = window.innerHeight + 'px';
  63211. }
  63212. if (this.incorrectOrientation)
  63213. {
  63214. this.setMaximum();
  63215. }
  63216. else
  63217. {
  63218. if (scaleMode === Phaser.ScaleManager.EXACT_FIT)
  63219. {
  63220. this.setExactFit();
  63221. }
  63222. else if (scaleMode === Phaser.ScaleManager.SHOW_ALL)
  63223. {
  63224. if (!this.isFullScreen && this.boundingParent &&
  63225. this.compatibility.canExpandParent)
  63226. {
  63227. // Try to expand parent out, but choosing maximizing dimensions.
  63228. // Then select minimize dimensions which should then honor parent
  63229. // maximum bound applications.
  63230. this.setShowAll(true);
  63231. this.resetCanvas();
  63232. this.setShowAll();
  63233. }
  63234. else
  63235. {
  63236. this.setShowAll();
  63237. }
  63238. }
  63239. else if (scaleMode === Phaser.ScaleManager.NO_SCALE)
  63240. {
  63241. this.width = this.game.width;
  63242. this.height = this.game.height;
  63243. }
  63244. else if (scaleMode === Phaser.ScaleManager.USER_SCALE)
  63245. {
  63246. this.width = (this.game.width * this._userScaleFactor.x) - this._userScaleTrim.x;
  63247. this.height = (this.game.height * this._userScaleFactor.y) - this._userScaleTrim.y;
  63248. }
  63249. }
  63250. if (!this.compatibility.canExpandParent &&
  63251. (scaleMode === Phaser.ScaleManager.SHOW_ALL || scaleMode === Phaser.ScaleManager.USER_SCALE))
  63252. {
  63253. var bounds = this.getParentBounds(this._tempBounds);
  63254. this.width = Math.min(this.width, bounds.width);
  63255. this.height = Math.min(this.height, bounds.height);
  63256. }
  63257. // Always truncate / force to integer
  63258. this.width = this.width | 0;
  63259. this.height = this.height | 0;
  63260. this.reflowCanvas();
  63261. },
  63262. /**
  63263. * Returns the computed Parent size/bounds that the Display canvas is allowed/expected to fill.
  63264. *
  63265. * If in fullscreen mode or without parent (see {@link #parentIsWindow}),
  63266. * this will be the bounds of the visual viewport itself.
  63267. *
  63268. * This function takes the {@link #windowConstraints} into consideration - if the parent is partially outside
  63269. * the viewport then this function may return a smaller than expected size.
  63270. *
  63271. * Values are rounded to the nearest pixel.
  63272. *
  63273. * @method Phaser.ScaleManager#getParentBounds
  63274. * @protected
  63275. * @param {Phaser.Rectangle} [target=(new Rectangle)] - The rectangle to update; a new one is created as needed.
  63276. * @return {Phaser.Rectangle} The established parent bounds.
  63277. */
  63278. getParentBounds: function (target) {
  63279. var bounds = target || new Phaser.Rectangle();
  63280. var parentNode = this.boundingParent;
  63281. var visualBounds = this.dom.visualBounds;
  63282. var layoutBounds = this.dom.layoutBounds;
  63283. if (!parentNode)
  63284. {
  63285. bounds.setTo(0, 0, visualBounds.width, visualBounds.height);
  63286. }
  63287. else
  63288. {
  63289. // Ref. http://msdn.microsoft.com/en-us/library/hh781509(v=vs.85).aspx for getBoundingClientRect
  63290. var clientRect = parentNode.getBoundingClientRect();
  63291. var parentRect = (parentNode.offsetParent) ? parentNode.offsetParent.getBoundingClientRect() : parentNode.getBoundingClientRect();
  63292. bounds.setTo(clientRect.left - parentRect.left, clientRect.top - parentRect.top, clientRect.width, clientRect.height);
  63293. var wc = this.windowConstraints;
  63294. if (wc.right)
  63295. {
  63296. var windowBounds = wc.right === 'layout' ? layoutBounds : visualBounds;
  63297. bounds.right = Math.min(bounds.right, windowBounds.width);
  63298. }
  63299. if (wc.bottom)
  63300. {
  63301. var windowBounds = wc.bottom === 'layout' ? layoutBounds : visualBounds;
  63302. bounds.bottom = Math.min(bounds.bottom, windowBounds.height);
  63303. }
  63304. }
  63305. bounds.setTo(
  63306. Math.round(bounds.x), Math.round(bounds.y),
  63307. Math.round(bounds.width), Math.round(bounds.height));
  63308. return bounds;
  63309. },
  63310. /**
  63311. * Update the canvas position/margins - for alignment within the parent container.
  63312. *
  63313. * The canvas margins _must_ be reset/cleared prior to invoking this.
  63314. *
  63315. * @method Phaser.ScaleManager#alignCanvas
  63316. * @private
  63317. * @param {boolean} horizontal - Align horizontally?
  63318. * @param {boolean} vertical - Align vertically?
  63319. */
  63320. alignCanvas: function (horizontal, vertical) {
  63321. var parentBounds = this.getParentBounds(this._tempBounds);
  63322. var canvas = this.game.canvas;
  63323. var margin = this.margin;
  63324. if (horizontal)
  63325. {
  63326. margin.left = margin.right = 0;
  63327. var canvasBounds = canvas.getBoundingClientRect();
  63328. if (this.width < parentBounds.width && !this.incorrectOrientation)
  63329. {
  63330. var currentEdge = canvasBounds.left - parentBounds.x;
  63331. var targetEdge = (parentBounds.width / 2) - (this.width / 2);
  63332. targetEdge = Math.max(targetEdge, 0);
  63333. var offset = targetEdge - currentEdge;
  63334. margin.left = Math.round(offset);
  63335. }
  63336. canvas.style.marginLeft = margin.left + 'px';
  63337. if (margin.left !== 0)
  63338. {
  63339. margin.right = -(parentBounds.width - canvasBounds.width - margin.left);
  63340. canvas.style.marginRight = margin.right + 'px';
  63341. }
  63342. }
  63343. if (vertical)
  63344. {
  63345. margin.top = margin.bottom = 0;
  63346. var canvasBounds = canvas.getBoundingClientRect();
  63347. if (this.height < parentBounds.height && !this.incorrectOrientation)
  63348. {
  63349. var currentEdge = canvasBounds.top - parentBounds.y;
  63350. var targetEdge = (parentBounds.height / 2) - (this.height / 2);
  63351. targetEdge = Math.max(targetEdge, 0);
  63352. var offset = targetEdge - currentEdge;
  63353. margin.top = Math.round(offset);
  63354. }
  63355. canvas.style.marginTop = margin.top + 'px';
  63356. if (margin.top !== 0)
  63357. {
  63358. margin.bottom = -(parentBounds.height - canvasBounds.height - margin.top);
  63359. canvas.style.marginBottom = margin.bottom + 'px';
  63360. }
  63361. }
  63362. // Silly backwards compatibility..
  63363. margin.x = margin.left;
  63364. margin.y = margin.top;
  63365. },
  63366. /**
  63367. * Updates the Game state / size.
  63368. *
  63369. * The canvas margins may always be adjusted, even if alignment is not in effect.
  63370. *
  63371. * @method Phaser.ScaleManager#reflowGame
  63372. * @private
  63373. */
  63374. reflowGame: function () {
  63375. this.resetCanvas('', '');
  63376. var bounds = this.getParentBounds(this._tempBounds);
  63377. this.updateDimensions(bounds.width, bounds.height, true);
  63378. },
  63379. /**
  63380. * Updates the Display canvas size.
  63381. *
  63382. * The canvas margins may always be adjusted, even alignment is not in effect.
  63383. *
  63384. * @method Phaser.ScaleManager#reflowCanvas
  63385. * @private
  63386. */
  63387. reflowCanvas: function () {
  63388. if (!this.incorrectOrientation)
  63389. {
  63390. this.width = Phaser.Math.clamp(this.width, this.minWidth || 0, this.maxWidth || this.width);
  63391. this.height = Phaser.Math.clamp(this.height, this.minHeight || 0, this.maxHeight || this.height);
  63392. }
  63393. this.resetCanvas();
  63394. if (!this.compatibility.noMargins)
  63395. {
  63396. if (this.isFullScreen && this._createdFullScreenTarget)
  63397. {
  63398. this.alignCanvas(true, true);
  63399. }
  63400. else
  63401. {
  63402. this.alignCanvas(this.pageAlignHorizontally, this.pageAlignVertically);
  63403. }
  63404. }
  63405. this.updateScalingAndBounds();
  63406. },
  63407. /**
  63408. * "Reset" the Display canvas and set the specified width/height.
  63409. *
  63410. * @method Phaser.ScaleManager#resetCanvas
  63411. * @private
  63412. * @param {string} [cssWidth=(current width)] - The css width to set.
  63413. * @param {string} [cssHeight=(current height)] - The css height to set.
  63414. */
  63415. resetCanvas: function (cssWidth, cssHeight) {
  63416. if (cssWidth === undefined) { cssWidth = this.width + 'px'; }
  63417. if (cssHeight === undefined) { cssHeight = this.height + 'px'; }
  63418. var canvas = this.game.canvas;
  63419. if (!this.compatibility.noMargins)
  63420. {
  63421. canvas.style.marginLeft = '';
  63422. canvas.style.marginTop = '';
  63423. canvas.style.marginRight = '';
  63424. canvas.style.marginBottom = '';
  63425. }
  63426. canvas.style.width = cssWidth;
  63427. canvas.style.height = cssHeight;
  63428. },
  63429. /**
  63430. * Queues/marks a size/bounds check as needing to occur (from `preUpdate`).
  63431. *
  63432. * @method Phaser.ScaleManager#queueUpdate
  63433. * @private
  63434. * @param {boolean} force - If true resets the parent bounds to ensure the check is dirty.
  63435. */
  63436. queueUpdate: function (force) {
  63437. if (force)
  63438. {
  63439. this._parentBounds.width = 0;
  63440. this._parentBounds.height = 0;
  63441. }
  63442. this._updateThrottle = this._updateThrottleReset;
  63443. },
  63444. /**
  63445. * Reset internal data/state.
  63446. *
  63447. * @method Phaser.ScaleManager#reset
  63448. * @private
  63449. */
  63450. reset: function (clearWorld) {
  63451. if (clearWorld && this.grid)
  63452. {
  63453. this.grid.reset();
  63454. }
  63455. },
  63456. /**
  63457. * Updates the width/height to that of the window.
  63458. *
  63459. * @method Phaser.ScaleManager#setMaximum
  63460. * @private
  63461. */
  63462. setMaximum: function () {
  63463. this.width = this.dom.visualBounds.width;
  63464. this.height = this.dom.visualBounds.height;
  63465. },
  63466. /**
  63467. * Updates the width/height such that the game is scaled proportionally.
  63468. *
  63469. * @method Phaser.ScaleManager#setShowAll
  63470. * @private
  63471. * @param {boolean} expanding - If true then the maximizing dimension is chosen.
  63472. */
  63473. setShowAll: function (expanding) {
  63474. var bounds = this.getParentBounds(this._tempBounds);
  63475. var width = bounds.width;
  63476. var height = bounds.height;
  63477. var multiplier;
  63478. if (expanding)
  63479. {
  63480. multiplier = Math.max((height / this.game.height), (width / this.game.width));
  63481. }
  63482. else
  63483. {
  63484. multiplier = Math.min((height / this.game.height), (width / this.game.width));
  63485. }
  63486. this.width = Math.round(this.game.width * multiplier);
  63487. this.height = Math.round(this.game.height * multiplier);
  63488. },
  63489. /**
  63490. * Updates the width/height such that the game is stretched to the available size.
  63491. * Honors {@link #maxWidth} and {@link #maxHeight} when _not_ in fullscreen.
  63492. *
  63493. * @method Phaser.ScaleManager#setExactFit
  63494. * @private
  63495. */
  63496. setExactFit: function () {
  63497. var bounds = this.getParentBounds(this._tempBounds);
  63498. this.width = bounds.width;
  63499. this.height = bounds.height;
  63500. if (this.isFullScreen)
  63501. {
  63502. // Max/min not honored fullscreen
  63503. return;
  63504. }
  63505. if (this.maxWidth)
  63506. {
  63507. this.width = Math.min(this.width, this.maxWidth);
  63508. }
  63509. if (this.maxHeight)
  63510. {
  63511. this.height = Math.min(this.height, this.maxHeight);
  63512. }
  63513. },
  63514. /**
  63515. * Creates a fullscreen target. This is called automatically as as needed when entering
  63516. * fullscreen mode and the resulting element is supplied to {@link #onFullScreenInit}.
  63517. *
  63518. * Use {@link #onFullScreenInit} to customize the created object.
  63519. *
  63520. * @method Phaser.ScaleManager#createFullScreenTarget
  63521. * @protected
  63522. */
  63523. createFullScreenTarget: function () {
  63524. var fsTarget = document.createElement('div');
  63525. fsTarget.style.margin = '0';
  63526. fsTarget.style.padding = '0';
  63527. fsTarget.style.background = '#000';
  63528. return fsTarget;
  63529. },
  63530. /**
  63531. * Start the browsers fullscreen mode - this _must_ be called from a user input Pointer or Mouse event.
  63532. *
  63533. * The Fullscreen API must be supported by the browser for this to work - it is not the same as setting
  63534. * the game size to fill the browser window. See {@link Phaser.ScaleManager#compatibility compatibility.supportsFullScreen} to check if the current
  63535. * device is reported to support fullscreen mode.
  63536. *
  63537. * The {@link #fullScreenFailed} signal will be dispatched if the fullscreen change request failed or the game does not support the Fullscreen API.
  63538. *
  63539. * @method Phaser.ScaleManager#startFullScreen
  63540. * @public
  63541. * @param {boolean} [antialias] - Changes the anti-alias feature of the canvas before jumping in to fullscreen (false = retain pixel art, true = smooth art). If not specified then no change is made. Only works in CANVAS mode.
  63542. * @param {boolean} [allowTrampoline=undefined] - Internal argument. If `false` click trampolining is suppressed.
  63543. * @return {boolean} Returns true if the device supports fullscreen mode and fullscreen mode was attempted to be started. (It might not actually start, wait for the signals.)
  63544. */
  63545. startFullScreen: function (antialias, allowTrampoline) {
  63546. if (this.isFullScreen)
  63547. {
  63548. return false;
  63549. }
  63550. if (!this.compatibility.supportsFullScreen)
  63551. {
  63552. // Error is called in timeout to emulate the real fullscreenerror event better
  63553. var _this = this;
  63554. setTimeout(function () {
  63555. _this.fullScreenError();
  63556. }, 10);
  63557. return;
  63558. }
  63559. if (this.compatibility.clickTrampoline === 'when-not-mouse')
  63560. {
  63561. var input = this.game.input;
  63562. if (input.activePointer &&
  63563. input.activePointer !== input.mousePointer &&
  63564. (allowTrampoline || allowTrampoline !== false))
  63565. {
  63566. input.activePointer.addClickTrampoline("startFullScreen", this.startFullScreen, this, [antialias, false]);
  63567. return;
  63568. }
  63569. }
  63570. if (typeof antialias !== 'undefined' && this.game.renderType === Phaser.CANVAS)
  63571. {
  63572. this.game.stage.smoothed = antialias;
  63573. }
  63574. var fsTarget = this.fullScreenTarget;
  63575. if (!fsTarget)
  63576. {
  63577. this.cleanupCreatedTarget();
  63578. this._createdFullScreenTarget = this.createFullScreenTarget();
  63579. fsTarget = this._createdFullScreenTarget;
  63580. }
  63581. var initData = {
  63582. targetElement: fsTarget
  63583. };
  63584. this.onFullScreenInit.dispatch(this, initData);
  63585. if (this._createdFullScreenTarget)
  63586. {
  63587. // Move the Display canvas inside of the target and add the target to the DOM
  63588. // (The target has to be added for the Fullscreen API to work.)
  63589. var canvas = this.game.canvas;
  63590. var parent = canvas.parentNode;
  63591. parent.insertBefore(fsTarget, canvas);
  63592. fsTarget.appendChild(canvas);
  63593. }
  63594. if (this.game.device.fullscreenKeyboard)
  63595. {
  63596. fsTarget[this.game.device.requestFullscreen](Element.ALLOW_KEYBOARD_INPUT);
  63597. }
  63598. else
  63599. {
  63600. fsTarget[this.game.device.requestFullscreen]();
  63601. }
  63602. return true;
  63603. },
  63604. /**
  63605. * Stops / exits fullscreen mode, if active.
  63606. *
  63607. * @method Phaser.ScaleManager#stopFullScreen
  63608. * @public
  63609. * @return {boolean} Returns true if the browser supports fullscreen mode and fullscreen mode will be exited.
  63610. */
  63611. stopFullScreen: function () {
  63612. if (!this.isFullScreen || !this.compatibility.supportsFullScreen)
  63613. {
  63614. return false;
  63615. }
  63616. document[this.game.device.cancelFullscreen]();
  63617. return true;
  63618. },
  63619. /**
  63620. * Cleans up the previous fullscreen target, if such was automatically created.
  63621. * This ensures the canvas is restored to its former parent, assuming the target didn't move.
  63622. *
  63623. * @method Phaser.ScaleManager#cleanupCreatedTarget
  63624. * @private
  63625. */
  63626. cleanupCreatedTarget: function () {
  63627. var fsTarget = this._createdFullScreenTarget;
  63628. if (fsTarget && fsTarget.parentNode)
  63629. {
  63630. // Make sure to cleanup synthetic target for sure;
  63631. // swap the canvas back to the parent.
  63632. var parent = fsTarget.parentNode;
  63633. parent.insertBefore(this.game.canvas, fsTarget);
  63634. parent.removeChild(fsTarget);
  63635. }
  63636. this._createdFullScreenTarget = null;
  63637. },
  63638. /**
  63639. * Used to prepare/restore extra fullscreen mode settings.
  63640. * (This does move any elements within the DOM tree.)
  63641. *
  63642. * @method Phaser.ScaleManager#prepScreenMode
  63643. * @private
  63644. * @param {boolean} enteringFullscreen - True if _entering_ fullscreen, false if _leaving_.
  63645. */
  63646. prepScreenMode: function (enteringFullscreen) {
  63647. var createdTarget = !!this._createdFullScreenTarget;
  63648. var fsTarget = this._createdFullScreenTarget || this.fullScreenTarget;
  63649. if (enteringFullscreen)
  63650. {
  63651. if (createdTarget || this.fullScreenScaleMode === Phaser.ScaleManager.EXACT_FIT)
  63652. {
  63653. // Resize target, as long as it's not the canvas
  63654. if (fsTarget !== this.game.canvas)
  63655. {
  63656. this._fullScreenRestore = {
  63657. targetWidth: fsTarget.style.width,
  63658. targetHeight: fsTarget.style.height
  63659. };
  63660. fsTarget.style.width = '100%';
  63661. fsTarget.style.height = '100%';
  63662. }
  63663. }
  63664. }
  63665. else
  63666. {
  63667. // Have restore information
  63668. if (this._fullScreenRestore)
  63669. {
  63670. fsTarget.style.width = this._fullScreenRestore.targetWidth;
  63671. fsTarget.style.height = this._fullScreenRestore.targetHeight;
  63672. this._fullScreenRestore = null;
  63673. }
  63674. // Always reset to game size
  63675. this.updateDimensions(this._gameSize.width, this._gameSize.height, true);
  63676. this.resetCanvas();
  63677. }
  63678. },
  63679. /**
  63680. * Called automatically when the browser enters of leaves fullscreen mode.
  63681. *
  63682. * @method Phaser.ScaleManager#fullScreenChange
  63683. * @private
  63684. * @param {Event} [event=undefined] - The fullscreenchange event
  63685. */
  63686. fullScreenChange: function (event) {
  63687. this.event = event;
  63688. if (this.isFullScreen)
  63689. {
  63690. this.prepScreenMode(true);
  63691. this.updateLayout();
  63692. this.queueUpdate(true);
  63693. }
  63694. else
  63695. {
  63696. this.prepScreenMode(false);
  63697. this.cleanupCreatedTarget();
  63698. this.updateLayout();
  63699. this.queueUpdate(true);
  63700. }
  63701. this.onFullScreenChange.dispatch(this, this.width, this.height);
  63702. },
  63703. /**
  63704. * Called automatically when the browser fullscreen request fails;
  63705. * or called when a fullscreen request is made on a device for which it is not supported.
  63706. *
  63707. * @method Phaser.ScaleManager#fullScreenError
  63708. * @private
  63709. * @param {Event} [event=undefined] - The fullscreenerror event; undefined if invoked on a device that does not support the Fullscreen API.
  63710. */
  63711. fullScreenError: function (event) {
  63712. this.event = event;
  63713. this.cleanupCreatedTarget();
  63714. console.warn('Phaser.ScaleManager: requestFullscreen failed or device does not support the Fullscreen API');
  63715. this.onFullScreenError.dispatch(this);
  63716. },
  63717. /**
  63718. * Takes a Sprite or Image object and scales it to fit the given dimensions.
  63719. * Scaling happens proportionally without distortion to the sprites texture.
  63720. * The letterBox parameter controls if scaling will produce a letter-box effect or zoom the
  63721. * sprite until it fills the given values. Note that with letterBox set to false the scaled sprite may spill out over either
  63722. * the horizontal or vertical sides of the target dimensions. If you wish to stop this you can crop the Sprite.
  63723. *
  63724. * @method Phaser.ScaleManager#scaleSprite
  63725. * @protected
  63726. * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite we want to scale.
  63727. * @param {integer} [width] - The target width that we want to fit the sprite in to. If not given it defaults to ScaleManager.width.
  63728. * @param {integer} [height] - The target height that we want to fit the sprite in to. If not given it defaults to ScaleManager.height.
  63729. * @param {boolean} [letterBox=false] - True if we want the `fitted` mode. Otherwise, the function uses the `zoom` mode.
  63730. * @return {Phaser.Sprite|Phaser.Image} The scaled sprite.
  63731. */
  63732. scaleSprite: function (sprite, width, height, letterBox) {
  63733. if (width === undefined) { width = this.width; }
  63734. if (height === undefined) { height = this.height; }
  63735. if (letterBox === undefined) { letterBox = false; }
  63736. if (!sprite || !sprite['scale'])
  63737. {
  63738. return sprite;
  63739. }
  63740. sprite.scale.x = 1;
  63741. sprite.scale.y = 1;
  63742. if ((sprite.width <= 0) || (sprite.height <= 0) || (width <= 0) || (height <= 0))
  63743. {
  63744. return sprite;
  63745. }
  63746. var scaleX1 = width;
  63747. var scaleY1 = (sprite.height * width) / sprite.width;
  63748. var scaleX2 = (sprite.width * height) / sprite.height;
  63749. var scaleY2 = height;
  63750. var scaleOnWidth = (scaleX2 > width);
  63751. if (scaleOnWidth)
  63752. {
  63753. scaleOnWidth = letterBox;
  63754. }
  63755. else
  63756. {
  63757. scaleOnWidth = !letterBox;
  63758. }
  63759. if (scaleOnWidth)
  63760. {
  63761. sprite.width = Math.floor(scaleX1);
  63762. sprite.height = Math.floor(scaleY1);
  63763. }
  63764. else
  63765. {
  63766. sprite.width = Math.floor(scaleX2);
  63767. sprite.height = Math.floor(scaleY2);
  63768. }
  63769. // Enable at some point?
  63770. // sprite.x = Math.floor((width - sprite.width) / 2);
  63771. // sprite.y = Math.floor((height - sprite.height) / 2);
  63772. return sprite;
  63773. },
  63774. /**
  63775. * Destroys the ScaleManager and removes any event listeners.
  63776. * This should probably only be called when the game is destroyed.
  63777. *
  63778. * @method Phaser.ScaleManager#destroy
  63779. * @protected
  63780. */
  63781. destroy: function () {
  63782. this.game.onResume.remove(this._gameResumed, this);
  63783. window.removeEventListener('orientationchange', this._orientationChange, false);
  63784. window.removeEventListener('resize', this._windowResize, false);
  63785. if (this.compatibility.supportsFullScreen)
  63786. {
  63787. document.removeEventListener('webkitfullscreenchange', this._fullScreenChange, false);
  63788. document.removeEventListener('mozfullscreenchange', this._fullScreenChange, false);
  63789. document.removeEventListener('MSFullscreenChange', this._fullScreenChange, false);
  63790. document.removeEventListener('fullscreenchange', this._fullScreenChange, false);
  63791. document.removeEventListener('webkitfullscreenerror', this._fullScreenError, false);
  63792. document.removeEventListener('mozfullscreenerror', this._fullScreenError, false);
  63793. document.removeEventListener('MSFullscreenError', this._fullScreenError, false);
  63794. document.removeEventListener('fullscreenerror', this._fullScreenError, false);
  63795. }
  63796. }
  63797. };
  63798. Phaser.ScaleManager.prototype.constructor = Phaser.ScaleManager;
  63799. /**
  63800. * The DOM element that is considered the Parent bounding element, if any.
  63801. *
  63802. * This `null` if {@link #parentIsWindow} is true or if fullscreen mode is entered and {@link #fullScreenTarget} is specified.
  63803. * It will also be null if there is no game canvas or if the game canvas has no parent.
  63804. *
  63805. * @name Phaser.ScaleManager#boundingParent
  63806. * @property {?DOMElement} boundingParent
  63807. * @readonly
  63808. */
  63809. Object.defineProperty(Phaser.ScaleManager.prototype, "boundingParent", {
  63810. get: function () {
  63811. if (this.parentIsWindow ||
  63812. (this.isFullScreen && !this._createdFullScreenTarget))
  63813. {
  63814. return null;
  63815. }
  63816. var parentNode = this.game.canvas && this.game.canvas.parentNode;
  63817. return parentNode || null;
  63818. }
  63819. });
  63820. /**
  63821. * The scaling method used by the ScaleManager when not in fullscreen.
  63822. *
  63823. * <dl>
  63824. * <dt>{@link Phaser.ScaleManager.NO_SCALE}</dt>
  63825. * <dd>
  63826. * The Game display area will not be scaled - even if it is too large for the canvas/screen.
  63827. * This mode _ignores_ any applied scaling factor and displays the canvas at the Game size.
  63828. * </dd>
  63829. * <dt>{@link Phaser.ScaleManager.EXACT_FIT}</dt>
  63830. * <dd>
  63831. * The Game display area will be _stretched_ to fill the entire size of the canvas's parent element and/or screen.
  63832. * Proportions are not maintained.
  63833. * </dd>
  63834. * <dt>{@link Phaser.ScaleManager.SHOW_ALL}</dt>
  63835. * <dd>
  63836. * Show the entire game display area while _maintaining_ the original aspect ratio.
  63837. * </dd>
  63838. * <dt>{@link Phaser.ScaleManager.RESIZE}</dt>
  63839. * <dd>
  63840. * The dimensions of the game display area are changed to match the size of the parent container.
  63841. * That is, this mode _changes the Game size_ to match the display size.
  63842. * <p>
  63843. * Any manually set Game size (see {@link #setGameSize}) is ignored while in effect.
  63844. * </dd>
  63845. * <dt>{@link Phaser.ScaleManager.USER_SCALE}</dt>
  63846. * <dd>
  63847. * The game Display is scaled according to the user-specified scale set by {@link Phaser.ScaleManager#setUserScale setUserScale}.
  63848. * <p>
  63849. * This scale can be adjusted in the {@link Phaser.ScaleManager#setResizeCallback resize callback}
  63850. * for flexible custom-sizing needs.
  63851. * </dd>
  63852. * </dl>
  63853. *
  63854. * @name Phaser.ScaleManager#scaleMode
  63855. * @property {integer} scaleMode
  63856. */
  63857. Object.defineProperty(Phaser.ScaleManager.prototype, "scaleMode", {
  63858. get: function () {
  63859. return this._scaleMode;
  63860. },
  63861. set: function (value) {
  63862. if (value !== this._scaleMode)
  63863. {
  63864. if (!this.isFullScreen)
  63865. {
  63866. this.updateDimensions(this._gameSize.width, this._gameSize.height, true);
  63867. this.queueUpdate(true);
  63868. }
  63869. this._scaleMode = value;
  63870. }
  63871. return this._scaleMode;
  63872. }
  63873. });
  63874. /**
  63875. * The scaling method used by the ScaleManager when in fullscreen.
  63876. *
  63877. * See {@link Phaser.ScaleManager#scaleMode scaleMode} for the different modes allowed.
  63878. *
  63879. * @name Phaser.ScaleManager#fullScreenScaleMode
  63880. * @property {integer} fullScreenScaleMode
  63881. */
  63882. Object.defineProperty(Phaser.ScaleManager.prototype, "fullScreenScaleMode", {
  63883. get: function () {
  63884. return this._fullScreenScaleMode;
  63885. },
  63886. set: function (value) {
  63887. if (value !== this._fullScreenScaleMode)
  63888. {
  63889. // If in fullscreen then need a wee bit more work
  63890. if (this.isFullScreen)
  63891. {
  63892. this.prepScreenMode(false);
  63893. this._fullScreenScaleMode = value;
  63894. this.prepScreenMode(true);
  63895. this.queueUpdate(true);
  63896. }
  63897. else
  63898. {
  63899. this._fullScreenScaleMode = value;
  63900. }
  63901. }
  63902. return this._fullScreenScaleMode;
  63903. }
  63904. });
  63905. /**
  63906. * Returns the current scale mode - for normal or fullscreen operation.
  63907. *
  63908. * See {@link Phaser.ScaleManager#scaleMode scaleMode} for the different modes allowed.
  63909. *
  63910. * @name Phaser.ScaleManager#currentScaleMode
  63911. * @property {number} currentScaleMode
  63912. * @protected
  63913. * @readonly
  63914. */
  63915. Object.defineProperty(Phaser.ScaleManager.prototype, "currentScaleMode", {
  63916. get: function () {
  63917. return this.isFullScreen ? this._fullScreenScaleMode : this._scaleMode;
  63918. }
  63919. });
  63920. /**
  63921. * When enabled the Display canvas will be horizontally-aligned _in the Parent container_ (or {@link Phaser.ScaleManager#parentIsWindow window}).
  63922. *
  63923. * To align horizontally across the page the Display canvas should be added directly to page;
  63924. * or the parent container should itself be horizontally aligned.
  63925. *
  63926. * Horizontal alignment is not applicable with the {@link .RESIZE} scaling mode.
  63927. *
  63928. * @name Phaser.ScaleManager#pageAlignHorizontally
  63929. * @property {boolean} pageAlignHorizontally
  63930. * @default false
  63931. */
  63932. Object.defineProperty(Phaser.ScaleManager.prototype, "pageAlignHorizontally", {
  63933. get: function () {
  63934. return this._pageAlignHorizontally;
  63935. },
  63936. set: function (value) {
  63937. if (value !== this._pageAlignHorizontally)
  63938. {
  63939. this._pageAlignHorizontally = value;
  63940. this.queueUpdate(true);
  63941. }
  63942. }
  63943. });
  63944. /**
  63945. * When enabled the Display canvas will be vertically-aligned _in the Parent container_ (or {@link Phaser.ScaleManager#parentIsWindow window}).
  63946. *
  63947. * To align vertically the Parent element should have a _non-collapsible_ height, such that it will maintain
  63948. * a height _larger_ than the height of the contained Game canvas - the game canvas will then be scaled vertically
  63949. * _within_ the remaining available height dictated by the Parent element.
  63950. *
  63951. * One way to prevent the parent from collapsing is to add an absolute "min-height" CSS property to the parent element.
  63952. * If specifying a relative "min-height/height" or adjusting margins, the Parent height must still be non-collapsible (see note).
  63953. *
  63954. * _Note_: In version 2.2 the minimum document height is _not_ automatically set to the viewport/window height.
  63955. * To automatically update the minimum document height set {@link Phaser.ScaleManager#compatibility compatibility.forceMinimumDocumentHeight} to true.
  63956. *
  63957. * Vertical alignment is not applicable with the {@link .RESIZE} scaling mode.
  63958. *
  63959. * @name Phaser.ScaleManager#pageAlignVertically
  63960. * @property {boolean} pageAlignVertically
  63961. * @default false
  63962. */
  63963. Object.defineProperty(Phaser.ScaleManager.prototype, "pageAlignVertically", {
  63964. get: function () {
  63965. return this._pageAlignVertically;
  63966. },
  63967. set: function (value) {
  63968. if (value !== this._pageAlignVertically)
  63969. {
  63970. this._pageAlignVertically = value;
  63971. this.queueUpdate(true);
  63972. }
  63973. }
  63974. });
  63975. /**
  63976. * Returns true if the browser is in fullscreen mode, otherwise false.
  63977. * @name Phaser.ScaleManager#isFullScreen
  63978. * @property {boolean} isFullScreen
  63979. * @readonly
  63980. */
  63981. Object.defineProperty(Phaser.ScaleManager.prototype, "isFullScreen", {
  63982. get: function () {
  63983. return !!(document['fullscreenElement'] ||
  63984. document['webkitFullscreenElement'] ||
  63985. document['mozFullScreenElement'] ||
  63986. document['msFullscreenElement']);
  63987. }
  63988. });
  63989. /**
  63990. * Returns true if the screen orientation is in portrait mode.
  63991. *
  63992. * @name Phaser.ScaleManager#isPortrait
  63993. * @property {boolean} isPortrait
  63994. * @readonly
  63995. */
  63996. Object.defineProperty(Phaser.ScaleManager.prototype, "isPortrait", {
  63997. get: function () {
  63998. return this.classifyOrientation(this.screenOrientation) === 'portrait';
  63999. }
  64000. });
  64001. /**
  64002. * Returns true if the screen orientation is in landscape mode.
  64003. *
  64004. * @name Phaser.ScaleManager#isLandscape
  64005. * @property {boolean} isLandscape
  64006. * @readonly
  64007. */
  64008. Object.defineProperty(Phaser.ScaleManager.prototype, "isLandscape", {
  64009. get: function () {
  64010. return this.classifyOrientation(this.screenOrientation) === 'landscape';
  64011. }
  64012. });
  64013. /**
  64014. * Returns true if the game dimensions are portrait (height > width).
  64015. * This is especially useful to check when using the RESIZE scale mode
  64016. * but wanting to maintain game orientation on desktop browsers,
  64017. * where typically the screen orientation will always be landscape regardless of the browser viewport.
  64018. *
  64019. * @name Phaser.ScaleManager#isGamePortrait
  64020. * @property {boolean} isGamePortrait
  64021. * @readonly
  64022. */
  64023. Object.defineProperty(Phaser.ScaleManager.prototype, "isGamePortrait", {
  64024. get: function () {
  64025. return (this.height > this.width);
  64026. }
  64027. });
  64028. /**
  64029. * Returns true if the game dimensions are landscape (width > height).
  64030. * This is especially useful to check when using the RESIZE scale mode
  64031. * but wanting to maintain game orientation on desktop browsers,
  64032. * where typically the screen orientation will always be landscape regardless of the browser viewport.
  64033. *
  64034. * @name Phaser.ScaleManager#isGameLandscape
  64035. * @property {boolean} isGameLandscape
  64036. * @readonly
  64037. */
  64038. Object.defineProperty(Phaser.ScaleManager.prototype, "isGameLandscape", {
  64039. get: function () {
  64040. return (this.width > this.height);
  64041. }
  64042. });
  64043. /**
  64044. * @author Richard Davey <rich@photonstorm.com>
  64045. * @copyright 2016 Photon Storm Ltd.
  64046. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  64047. */
  64048. /**
  64049. * A collection of methods for displaying debug information about game objects.
  64050. * If your game is running in WebGL then Debug will create a Sprite that is placed at the top of the Stage display list and bind a canvas texture
  64051. * to it, which must be uploaded every frame. Be advised: this is very expensive, especially in browsers like Firefox. So please only enable Debug
  64052. * in WebGL mode if you really need it (or your desktop can cope with it well) and disable it for production!
  64053. * If your game is using a Canvas renderer then the debug information is literally drawn on the top of the active game canvas and no Sprite is used.
  64054. *
  64055. * @class Phaser.Utils.Debug
  64056. * @constructor
  64057. * @param {Phaser.Game} game - A reference to the currently running game.
  64058. */
  64059. Phaser.Utils.Debug = function (game) {
  64060. /**
  64061. * @property {Phaser.Game} game - A reference to the currently running Game.
  64062. */
  64063. this.game = game;
  64064. /**
  64065. * @property {Phaser.Image} sprite - If debugging in WebGL mode we need this.
  64066. */
  64067. this.sprite = null;
  64068. /**
  64069. * @property {Phaser.BitmapData} bmd - In WebGL mode this BitmapData contains a copy of the debug canvas.
  64070. */
  64071. this.bmd = null;
  64072. /**
  64073. * @property {HTMLCanvasElement} canvas - The canvas to which Debug calls draws.
  64074. */
  64075. this.canvas = null;
  64076. /**
  64077. * @property {CanvasRenderingContext2D} context - The 2d context of the canvas.
  64078. */
  64079. this.context = null;
  64080. /**
  64081. * @property {string} font - The font that the debug information is rendered in.
  64082. * @default '14px Courier'
  64083. */
  64084. this.font = '14px Courier';
  64085. /**
  64086. * @property {number} columnWidth - The spacing between columns.
  64087. */
  64088. this.columnWidth = 100;
  64089. /**
  64090. * @property {number} lineHeight - The line height between the debug text.
  64091. */
  64092. this.lineHeight = 16;
  64093. /**
  64094. * @property {boolean} renderShadow - Should the text be rendered with a slight shadow? Makes it easier to read on different types of background.
  64095. */
  64096. this.renderShadow = true;
  64097. /**
  64098. * @property {number} currentX - The current X position the debug information will be rendered at.
  64099. * @default
  64100. */
  64101. this.currentX = 0;
  64102. /**
  64103. * @property {number} currentY - The current Y position the debug information will be rendered at.
  64104. * @default
  64105. */
  64106. this.currentY = 0;
  64107. /**
  64108. * @property {number} currentAlpha - The alpha of the Debug context, set before all debug information is rendered to it.
  64109. * @default
  64110. */
  64111. this.currentAlpha = 1;
  64112. /**
  64113. * @property {boolean} dirty - Does the canvas need re-rendering?
  64114. */
  64115. this.dirty = false;
  64116. };
  64117. Phaser.Utils.Debug.prototype = {
  64118. /**
  64119. * Internal method that boots the debug displayer.
  64120. *
  64121. * @method Phaser.Utils.Debug#boot
  64122. * @protected
  64123. */
  64124. boot: function () {
  64125. if (this.game.renderType === Phaser.CANVAS)
  64126. {
  64127. this.context = this.game.context;
  64128. }
  64129. else
  64130. {
  64131. this.bmd = this.game.make.bitmapData(this.game.width, this.game.height);
  64132. this.sprite = this.game.make.image(0, 0, this.bmd);
  64133. this.game.stage.addChild(this.sprite);
  64134. this.game.scale.onSizeChange.add(this.resize, this);
  64135. this.canvas = PIXI.CanvasPool.create(this, this.game.width, this.game.height);
  64136. this.context = this.canvas.getContext('2d');
  64137. }
  64138. },
  64139. /**
  64140. * Internal method that resizes the BitmapData and Canvas.
  64141. * Called by ScaleManager.onSizeChange only in WebGL mode.
  64142. *
  64143. * @method Phaser.Utils.Debug#resize
  64144. * @protected
  64145. * @param {Phaser.ScaleManager} scaleManager - The Phaser ScaleManager.
  64146. * @param {number} width - The new width of the game.
  64147. * @param {number} height - The new height of the game.
  64148. */
  64149. resize: function (scaleManager, width, height) {
  64150. this.bmd.resize(width, height);
  64151. this.canvas.width = width;
  64152. this.canvas.height = height;
  64153. },
  64154. /**
  64155. * Internal method that clears the canvas (if a Sprite) ready for a new debug session.
  64156. *
  64157. * @method Phaser.Utils.Debug#preUpdate
  64158. * @protected
  64159. */
  64160. preUpdate: function () {
  64161. if (this.dirty && this.sprite)
  64162. {
  64163. this.bmd.clear();
  64164. this.bmd.draw(this.canvas, 0, 0);
  64165. this.context.clearRect(0, 0, this.game.width, this.game.height);
  64166. this.dirty = false;
  64167. }
  64168. },
  64169. /**
  64170. * Clears the Debug canvas.
  64171. *
  64172. * @method Phaser.Utils.Debug#reset
  64173. */
  64174. reset: function () {
  64175. if (this.context)
  64176. {
  64177. this.context.clearRect(0, 0, this.game.width, this.game.height);
  64178. }
  64179. if (this.sprite)
  64180. {
  64181. this.bmd.clear();
  64182. }
  64183. },
  64184. /**
  64185. * Internal method that resets and starts the debug output values.
  64186. *
  64187. * @method Phaser.Utils.Debug#start
  64188. * @protected
  64189. * @param {number} [x=0] - The X value the debug info will start from.
  64190. * @param {number} [y=0] - The Y value the debug info will start from.
  64191. * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in.
  64192. * @param {number} [columnWidth=0] - The spacing between columns.
  64193. */
  64194. start: function (x, y, color, columnWidth) {
  64195. if (typeof x !== 'number') { x = 0; }
  64196. if (typeof y !== 'number') { y = 0; }
  64197. color = color || 'rgb(255,255,255)';
  64198. if (columnWidth === undefined) { columnWidth = 0; }
  64199. this.currentX = x;
  64200. this.currentY = y;
  64201. this.currentColor = color;
  64202. this.columnWidth = columnWidth;
  64203. this.dirty = true;
  64204. this.context.save();
  64205. this.context.setTransform(1, 0, 0, 1, 0, 0);
  64206. this.context.strokeStyle = color;
  64207. this.context.fillStyle = color;
  64208. this.context.font = this.font;
  64209. this.context.globalAlpha = this.currentAlpha;
  64210. },
  64211. /**
  64212. * Internal method that stops the debug output.
  64213. *
  64214. * @method Phaser.Utils.Debug#stop
  64215. * @protected
  64216. */
  64217. stop: function () {
  64218. this.context.restore();
  64219. },
  64220. /**
  64221. * Internal method that outputs a single line of text split over as many columns as needed, one per parameter.
  64222. *
  64223. * @method Phaser.Utils.Debug#line
  64224. * @protected
  64225. */
  64226. line: function () {
  64227. var x = this.currentX;
  64228. for (var i = 0; i < arguments.length; i++)
  64229. {
  64230. if (this.renderShadow)
  64231. {
  64232. this.context.fillStyle = 'rgb(0,0,0)';
  64233. this.context.fillText(arguments[i], x + 1, this.currentY + 1);
  64234. this.context.fillStyle = this.currentColor;
  64235. }
  64236. this.context.fillText(arguments[i], x, this.currentY);
  64237. x += this.columnWidth;
  64238. }
  64239. this.currentY += this.lineHeight;
  64240. },
  64241. /**
  64242. * Render Sound information, including decoded state, duration, volume and more.
  64243. *
  64244. * @method Phaser.Utils.Debug#soundInfo
  64245. * @param {Phaser.Sound} sound - The sound object to debug.
  64246. * @param {number} x - X position of the debug info to be rendered.
  64247. * @param {number} y - Y position of the debug info to be rendered.
  64248. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  64249. */
  64250. soundInfo: function (sound, x, y, color) {
  64251. this.start(x, y, color);
  64252. this.line('Sound: ' + sound.key + ' Locked: ' + sound.game.sound.touchLocked);
  64253. this.line('Is Ready?: ' + this.game.cache.isSoundReady(sound.key) + ' Pending Playback: ' + sound.pendingPlayback);
  64254. this.line('Decoded: ' + sound.isDecoded + ' Decoding: ' + sound.isDecoding);
  64255. this.line('Total Duration: ' + sound.totalDuration + ' Playing: ' + sound.isPlaying);
  64256. this.line('Time: ' + sound.currentTime);
  64257. this.line('Volume: ' + sound.volume + ' Muted: ' + sound.mute);
  64258. this.line('WebAudio: ' + sound.usingWebAudio + ' Audio: ' + sound.usingAudioTag);
  64259. if (sound.currentMarker !== '')
  64260. {
  64261. this.line('Marker: ' + sound.currentMarker + ' Duration: ' + sound.duration + ' (ms: ' + sound.durationMS + ')');
  64262. this.line('Start: ' + sound.markers[sound.currentMarker].start + ' Stop: ' + sound.markers[sound.currentMarker].stop);
  64263. this.line('Position: ' + sound.position);
  64264. }
  64265. this.stop();
  64266. },
  64267. /**
  64268. * Render camera information including dimensions and location.
  64269. *
  64270. * @method Phaser.Utils.Debug#cameraInfo
  64271. * @param {Phaser.Camera} camera - The Phaser.Camera to show the debug information for.
  64272. * @param {number} x - X position of the debug info to be rendered.
  64273. * @param {number} y - Y position of the debug info to be rendered.
  64274. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  64275. */
  64276. cameraInfo: function (camera, x, y, color) {
  64277. this.start(x, y, color);
  64278. this.line('Camera (' + camera.width + ' x ' + camera.height + ')');
  64279. this.line('X: ' + camera.x + ' Y: ' + camera.y);
  64280. if (camera.bounds)
  64281. {
  64282. this.line('Bounds x: ' + camera.bounds.x + ' Y: ' + camera.bounds.y + ' w: ' + camera.bounds.width + ' h: ' + camera.bounds.height);
  64283. }
  64284. this.line('View x: ' + camera.view.x + ' Y: ' + camera.view.y + ' w: ' + camera.view.width + ' h: ' + camera.view.height);
  64285. // this.line('Screen View x: ' + camera.screenView.x + ' Y: ' + camera.screenView.y + ' w: ' + camera.screenView.width + ' h: ' + camera.screenView.height);
  64286. this.line('Total in view: ' + camera.totalInView);
  64287. this.stop();
  64288. },
  64289. /**
  64290. * Render Timer information.
  64291. *
  64292. * @method Phaser.Utils.Debug#timer
  64293. * @param {Phaser.Timer} timer - The Phaser.Timer to show the debug information for.
  64294. * @param {number} x - X position of the debug info to be rendered.
  64295. * @param {number} y - Y position of the debug info to be rendered.
  64296. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  64297. */
  64298. timer: function (timer, x, y, color) {
  64299. this.start(x, y, color);
  64300. this.line('Timer (running: ' + timer.running + ' expired: ' + timer.expired + ')');
  64301. this.line('Next Tick: ' + timer.next + ' Duration: ' + timer.duration);
  64302. this.line('Paused: ' + timer.paused + ' Length: ' + timer.length);
  64303. this.stop();
  64304. },
  64305. /**
  64306. * Renders the Pointer.circle object onto the stage in green if down or red if up along with debug text.
  64307. *
  64308. * @method Phaser.Utils.Debug#pointer
  64309. * @param {Phaser.Pointer} pointer - The Pointer you wish to display.
  64310. * @param {boolean} [hideIfUp=false] - Doesn't render the circle if the pointer is up.
  64311. * @param {string} [downColor='rgba(0,255,0,0.5)'] - The color the circle is rendered in if down.
  64312. * @param {string} [upColor='rgba(255,0,0,0.5)'] - The color the circle is rendered in if up (and hideIfUp is false).
  64313. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  64314. */
  64315. pointer: function (pointer, hideIfUp, downColor, upColor, color) {
  64316. if (pointer == null)
  64317. {
  64318. return;
  64319. }
  64320. if (hideIfUp === undefined) { hideIfUp = false; }
  64321. downColor = downColor || 'rgba(0,255,0,0.5)';
  64322. upColor = upColor || 'rgba(255,0,0,0.5)';
  64323. if (hideIfUp === true && pointer.isUp === true)
  64324. {
  64325. return;
  64326. }
  64327. this.start(pointer.x, pointer.y - 100, color);
  64328. this.context.beginPath();
  64329. this.context.arc(pointer.x, pointer.y, pointer.circle.radius, 0, Math.PI * 2);
  64330. if (pointer.active)
  64331. {
  64332. this.context.fillStyle = downColor;
  64333. }
  64334. else
  64335. {
  64336. this.context.fillStyle = upColor;
  64337. }
  64338. this.context.fill();
  64339. this.context.closePath();
  64340. // Render the points
  64341. this.context.beginPath();
  64342. this.context.moveTo(pointer.positionDown.x, pointer.positionDown.y);
  64343. this.context.lineTo(pointer.position.x, pointer.position.y);
  64344. this.context.lineWidth = 2;
  64345. this.context.stroke();
  64346. this.context.closePath();
  64347. // Render the text
  64348. this.line('ID: ' + pointer.id + " Active: " + pointer.active);
  64349. this.line('World X: ' + pointer.worldX + " World Y: " + pointer.worldY);
  64350. this.line('Screen X: ' + pointer.x + " Screen Y: " + pointer.y + " In: " + pointer.withinGame);
  64351. this.line('Duration: ' + pointer.duration + " ms");
  64352. this.line('is Down: ' + pointer.isDown + " is Up: " + pointer.isUp);
  64353. this.stop();
  64354. },
  64355. /**
  64356. * Render Sprite Input Debug information.
  64357. *
  64358. * @method Phaser.Utils.Debug#spriteInputInfo
  64359. * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite to display the input data for.
  64360. * @param {number} x - X position of the debug info to be rendered.
  64361. * @param {number} y - Y position of the debug info to be rendered.
  64362. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  64363. */
  64364. spriteInputInfo: function (sprite, x, y, color) {
  64365. this.start(x, y, color);
  64366. this.line('Sprite Input: (' + sprite.width + ' x ' + sprite.height + ')');
  64367. this.line('x: ' + sprite.input.pointerX().toFixed(1) + ' y: ' + sprite.input.pointerY().toFixed(1));
  64368. this.line('over: ' + sprite.input.pointerOver() + ' duration: ' + sprite.input.overDuration().toFixed(0));
  64369. this.line('down: ' + sprite.input.pointerDown() + ' duration: ' + sprite.input.downDuration().toFixed(0));
  64370. this.line('just over: ' + sprite.input.justOver() + ' just out: ' + sprite.input.justOut());
  64371. this.stop();
  64372. },
  64373. /**
  64374. * Renders Phaser.Key object information.
  64375. *
  64376. * @method Phaser.Utils.Debug#key
  64377. * @param {Phaser.Key} key - The Key to render the information for.
  64378. * @param {number} x - X position of the debug info to be rendered.
  64379. * @param {number} y - Y position of the debug info to be rendered.
  64380. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  64381. */
  64382. key: function (key, x, y, color) {
  64383. this.start(x, y, color, 150);
  64384. this.line('Key:', key.keyCode, 'isDown:', key.isDown);
  64385. this.line('justDown:', key.justDown, 'justUp:', key.justUp);
  64386. this.line('Time Down:', key.timeDown.toFixed(0), 'duration:', key.duration.toFixed(0));
  64387. this.stop();
  64388. },
  64389. /**
  64390. * Render debug information about the Input object.
  64391. *
  64392. * @method Phaser.Utils.Debug#inputInfo
  64393. * @param {number} x - X position of the debug info to be rendered.
  64394. * @param {number} y - Y position of the debug info to be rendered.
  64395. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  64396. */
  64397. inputInfo: function (x, y, color) {
  64398. this.start(x, y, color);
  64399. this.line('Input');
  64400. this.line('X: ' + this.game.input.x + ' Y: ' + this.game.input.y);
  64401. this.line('World X: ' + this.game.input.worldX + ' World Y: ' + this.game.input.worldY);
  64402. this.line('Scale X: ' + this.game.input.scale.x.toFixed(1) + ' Scale Y: ' + this.game.input.scale.x.toFixed(1));
  64403. this.line('Screen X: ' + this.game.input.activePointer.screenX + ' Screen Y: ' + this.game.input.activePointer.screenY);
  64404. this.stop();
  64405. },
  64406. /**
  64407. * Renders the Sprites bounds. Note: This is really expensive as it has to calculate the bounds every time you call it!
  64408. *
  64409. * @method Phaser.Utils.Debug#spriteBounds
  64410. * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite to display the bounds of.
  64411. * @param {string} [color] - Color of the debug info to be rendered (format is css color string).
  64412. * @param {boolean} [filled=true] - Render the rectangle as a fillRect (default, true) or a strokeRect (false)
  64413. */
  64414. spriteBounds: function (sprite, color, filled) {
  64415. var bounds = sprite.getBounds();
  64416. bounds.x += this.game.camera.x;
  64417. bounds.y += this.game.camera.y;
  64418. this.rectangle(bounds, color, filled);
  64419. },
  64420. /**
  64421. * Renders the Rope's segments. Note: This is really expensive as it has to calculate new segments every time you call it
  64422. *
  64423. * @method Phaser.Utils.Debug#ropeSegments
  64424. * @param {Phaser.Rope} rope - The rope to display the segments of.
  64425. * @param {string} [color] - Color of the debug info to be rendered (format is css color string).
  64426. * @param {boolean} [filled=true] - Render the rectangle as a fillRect (default, true) or a strokeRect (false)
  64427. */
  64428. ropeSegments: function (rope, color, filled) {
  64429. var segments = rope.segments;
  64430. var self = this;
  64431. segments.forEach(function(segment) {
  64432. self.rectangle(segment, color, filled);
  64433. }, this);
  64434. },
  64435. /**
  64436. * Render debug infos (including name, bounds info, position and some other properties) about the Sprite.
  64437. *
  64438. * @method Phaser.Utils.Debug#spriteInfo
  64439. * @param {Phaser.Sprite} sprite - The Sprite to display the information of.
  64440. * @param {number} x - X position of the debug info to be rendered.
  64441. * @param {number} y - Y position of the debug info to be rendered.
  64442. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  64443. */
  64444. spriteInfo: function (sprite, x, y, color) {
  64445. this.start(x, y, color);
  64446. this.line('Sprite: ' + ' (' + sprite.width + ' x ' + sprite.height + ') anchor: ' + sprite.anchor.x + ' x ' + sprite.anchor.y);
  64447. this.line('x: ' + sprite.x.toFixed(1) + ' y: ' + sprite.y.toFixed(1));
  64448. this.line('angle: ' + sprite.angle.toFixed(1) + ' rotation: ' + sprite.rotation.toFixed(1));
  64449. this.line('visible: ' + sprite.visible + ' in camera: ' + sprite.inCamera);
  64450. this.line('bounds x: ' + sprite._bounds.x.toFixed(1) + ' y: ' + sprite._bounds.y.toFixed(1) + ' w: ' + sprite._bounds.width.toFixed(1) + ' h: ' + sprite._bounds.height.toFixed(1));
  64451. this.stop();
  64452. },
  64453. /**
  64454. * Renders the sprite coordinates in local, positional and world space.
  64455. *
  64456. * @method Phaser.Utils.Debug#spriteCoords
  64457. * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite to display the coordinates for.
  64458. * @param {number} x - X position of the debug info to be rendered.
  64459. * @param {number} y - Y position of the debug info to be rendered.
  64460. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  64461. */
  64462. spriteCoords: function (sprite, x, y, color) {
  64463. this.start(x, y, color, 100);
  64464. if (sprite.name)
  64465. {
  64466. this.line(sprite.name);
  64467. }
  64468. this.line('x:', sprite.x.toFixed(2), 'y:', sprite.y.toFixed(2));
  64469. this.line('pos x:', sprite.position.x.toFixed(2), 'pos y:', sprite.position.y.toFixed(2));
  64470. this.line('world x:', sprite.world.x.toFixed(2), 'world y:', sprite.world.y.toFixed(2));
  64471. this.stop();
  64472. },
  64473. /**
  64474. * Renders Line information in the given color.
  64475. *
  64476. * @method Phaser.Utils.Debug#lineInfo
  64477. * @param {Phaser.Line} line - The Line to display the data for.
  64478. * @param {number} x - X position of the debug info to be rendered.
  64479. * @param {number} y - Y position of the debug info to be rendered.
  64480. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  64481. */
  64482. lineInfo: function (line, x, y, color) {
  64483. this.start(x, y, color, 80);
  64484. this.line('start.x:', line.start.x.toFixed(2), 'start.y:', line.start.y.toFixed(2));
  64485. this.line('end.x:', line.end.x.toFixed(2), 'end.y:', line.end.y.toFixed(2));
  64486. this.line('length:', line.length.toFixed(2), 'angle:', line.angle);
  64487. this.stop();
  64488. },
  64489. /**
  64490. * Renders a single pixel at the given size.
  64491. *
  64492. * @method Phaser.Utils.Debug#pixel
  64493. * @param {number} x - X position of the pixel to be rendered.
  64494. * @param {number} y - Y position of the pixel to be rendered.
  64495. * @param {string} [color] - Color of the pixel (format is css color string).
  64496. * @param {number} [size=2] - The 'size' to render the pixel at.
  64497. */
  64498. pixel: function (x, y, color, size) {
  64499. size = size || 2;
  64500. this.start();
  64501. this.context.fillStyle = color;
  64502. this.context.fillRect(x, y, size, size);
  64503. this.stop();
  64504. },
  64505. /**
  64506. * Renders a Phaser geometry object including Rectangle, Circle, Point or Line.
  64507. *
  64508. * @method Phaser.Utils.Debug#geom
  64509. * @param {Phaser.Rectangle|Phaser.Circle|Phaser.Point|Phaser.Line} object - The geometry object to render.
  64510. * @param {string} [color] - Color of the debug info to be rendered (format is css color string).
  64511. * @param {boolean} [filled=true] - Render the objected as a filled (default, true) or a stroked (false)
  64512. * @param {number} [forceType=0] - Force rendering of a specific type. If 0 no type will be forced, otherwise 1 = Rectangle, 2 = Circle, 3 = Point and 4 = Line.
  64513. */
  64514. geom: function (object, color, filled, forceType) {
  64515. if (filled === undefined) { filled = true; }
  64516. if (forceType === undefined) { forceType = 0; }
  64517. color = color || 'rgba(0,255,0,0.4)';
  64518. this.start();
  64519. this.context.fillStyle = color;
  64520. this.context.strokeStyle = color;
  64521. if (object instanceof Phaser.Rectangle || forceType === 1)
  64522. {
  64523. if (filled)
  64524. {
  64525. this.context.fillRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height);
  64526. }
  64527. else
  64528. {
  64529. this.context.strokeRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height);
  64530. }
  64531. }
  64532. else if (object instanceof Phaser.Circle || forceType === 2)
  64533. {
  64534. this.context.beginPath();
  64535. this.context.arc(object.x - this.game.camera.x, object.y - this.game.camera.y, object.radius, 0, Math.PI * 2, false);
  64536. this.context.closePath();
  64537. if (filled)
  64538. {
  64539. this.context.fill();
  64540. }
  64541. else
  64542. {
  64543. this.context.stroke();
  64544. }
  64545. }
  64546. else if (object instanceof Phaser.Point || forceType === 3)
  64547. {
  64548. this.context.fillRect(object.x - this.game.camera.x, object.y - this.game.camera.y, 4, 4);
  64549. }
  64550. else if (object instanceof Phaser.Line || forceType === 4)
  64551. {
  64552. this.context.lineWidth = 1;
  64553. this.context.beginPath();
  64554. this.context.moveTo((object.start.x + 0.5) - this.game.camera.x, (object.start.y + 0.5) - this.game.camera.y);
  64555. this.context.lineTo((object.end.x + 0.5) - this.game.camera.x, (object.end.y + 0.5) - this.game.camera.y);
  64556. this.context.closePath();
  64557. this.context.stroke();
  64558. }
  64559. this.stop();
  64560. },
  64561. /**
  64562. * Renders a Rectangle.
  64563. *
  64564. * @method Phaser.Utils.Debug#geom
  64565. * @param {Phaser.Rectangle|object} object - The geometry object to render.
  64566. * @param {string} [color] - Color of the debug info to be rendered (format is css color string).
  64567. * @param {boolean} [filled=true] - Render the objected as a filled (default, true) or a stroked (false)
  64568. */
  64569. rectangle: function (object, color, filled) {
  64570. if (filled === undefined) { filled = true; }
  64571. color = color || 'rgba(0, 255, 0, 0.4)';
  64572. this.start();
  64573. if (filled)
  64574. {
  64575. this.context.fillStyle = color;
  64576. this.context.fillRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height);
  64577. }
  64578. else
  64579. {
  64580. this.context.strokeStyle = color;
  64581. this.context.strokeRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height);
  64582. }
  64583. this.stop();
  64584. },
  64585. /**
  64586. * Render a string of text.
  64587. *
  64588. * @method Phaser.Utils.Debug#text
  64589. * @param {string} text - The line of text to draw.
  64590. * @param {number} x - X position of the debug info to be rendered.
  64591. * @param {number} y - Y position of the debug info to be rendered.
  64592. * @param {string} [color] - Color of the debug info to be rendered (format is css color string).
  64593. * @param {string} [font] - The font of text to draw.
  64594. */
  64595. text: function (text, x, y, color, font) {
  64596. color = color || 'rgb(255,255,255)';
  64597. font = font || '16px Courier';
  64598. this.start();
  64599. this.context.font = font;
  64600. if (this.renderShadow)
  64601. {
  64602. this.context.fillStyle = 'rgb(0,0,0)';
  64603. this.context.fillText(text, x + 1, y + 1);
  64604. }
  64605. this.context.fillStyle = color;
  64606. this.context.fillText(text, x, y);
  64607. this.stop();
  64608. },
  64609. /**
  64610. * Visually renders a QuadTree to the display.
  64611. *
  64612. * @method Phaser.Utils.Debug#quadTree
  64613. * @param {Phaser.QuadTree} quadtree - The quadtree to render.
  64614. * @param {string} color - The color of the lines in the quadtree.
  64615. */
  64616. quadTree: function (quadtree, color) {
  64617. color = color || 'rgba(255,0,0,0.3)';
  64618. this.start();
  64619. var bounds = quadtree.bounds;
  64620. if (quadtree.nodes.length === 0)
  64621. {
  64622. this.context.strokeStyle = color;
  64623. this.context.strokeRect(bounds.x, bounds.y, bounds.width, bounds.height);
  64624. this.text('size: ' + quadtree.objects.length, bounds.x + 4, bounds.y + 16, 'rgb(0,200,0)', '12px Courier');
  64625. this.context.strokeStyle = 'rgb(0,255,0)';
  64626. for (var i = 0; i < quadtree.objects.length; i++)
  64627. {
  64628. this.context.strokeRect(quadtree.objects[i].x, quadtree.objects[i].y, quadtree.objects[i].width, quadtree.objects[i].height);
  64629. }
  64630. }
  64631. else
  64632. {
  64633. for (var i = 0; i < quadtree.nodes.length; i++)
  64634. {
  64635. this.quadTree(quadtree.nodes[i]);
  64636. }
  64637. }
  64638. this.stop();
  64639. },
  64640. /**
  64641. * Render a Sprites Physics body if it has one set. The body is rendered as a filled or stroked rectangle.
  64642. * This only works for Arcade Physics, Ninja Physics (AABB and Circle only) and Box2D Physics bodies.
  64643. * To display a P2 Physics body you should enable debug mode on the body when creating it.
  64644. *
  64645. * @method Phaser.Utils.Debug#body
  64646. * @param {Phaser.Sprite} sprite - The Sprite who's body will be rendered.
  64647. * @param {string} [color='rgba(0,255,0,0.4)'] - Color of the debug rectangle to be rendered. The format is a CSS color string such as '#ff0000' or 'rgba(255,0,0,0.5)'.
  64648. * @param {boolean} [filled=true] - Render the body as a filled rectangle (true) or a stroked rectangle (false)
  64649. */
  64650. body: function (sprite, color, filled) {
  64651. if (sprite.body)
  64652. {
  64653. this.start();
  64654. if (sprite.body.type === Phaser.Physics.ARCADE)
  64655. {
  64656. Phaser.Physics.Arcade.Body.render(this.context, sprite.body, color, filled);
  64657. }
  64658. else if (sprite.body.type === Phaser.Physics.NINJA)
  64659. {
  64660. Phaser.Physics.Ninja.Body.render(this.context, sprite.body, color, filled);
  64661. }
  64662. else if (sprite.body.type === Phaser.Physics.BOX2D)
  64663. {
  64664. Phaser.Physics.Box2D.renderBody(this.context, sprite.body, color);
  64665. }
  64666. this.stop();
  64667. }
  64668. },
  64669. /**
  64670. * Render a Sprites Physic Body information.
  64671. *
  64672. * @method Phaser.Utils.Debug#bodyInfo
  64673. * @param {Phaser.Sprite} sprite - The sprite to be rendered.
  64674. * @param {number} x - X position of the debug info to be rendered.
  64675. * @param {number} y - Y position of the debug info to be rendered.
  64676. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  64677. */
  64678. bodyInfo: function (sprite, x, y, color) {
  64679. if (sprite.body)
  64680. {
  64681. this.start(x, y, color, 210);
  64682. if (sprite.body.type === Phaser.Physics.ARCADE)
  64683. {
  64684. Phaser.Physics.Arcade.Body.renderBodyInfo(this, sprite.body);
  64685. }
  64686. else if (sprite.body.type === Phaser.Physics.BOX2D)
  64687. {
  64688. this.game.physics.box2d.renderBodyInfo(this, sprite.body);
  64689. }
  64690. this.stop();
  64691. }
  64692. },
  64693. /**
  64694. * Renders 'debug draw' data for the Box2D world if it exists.
  64695. * This uses the standard debug drawing feature of Box2D, so colors will be decided by
  64696. * the Box2D engine.
  64697. *
  64698. * @method Phaser.Utils.Debug#box2dWorld
  64699. */
  64700. box2dWorld: function () {
  64701. this.start();
  64702. this.context.translate(-this.game.camera.view.x, -this.game.camera.view.y, 0);
  64703. this.game.physics.box2d.renderDebugDraw(this.context);
  64704. this.stop();
  64705. },
  64706. /**
  64707. * Renders 'debug draw' data for the given Box2D body.
  64708. * This uses the standard debug drawing feature of Box2D, so colors will be decided by the Box2D engine.
  64709. *
  64710. * @method Phaser.Utils.Debug#box2dBody
  64711. * @param {Phaser.Sprite} sprite - The sprite whos body will be rendered.
  64712. * @param {string} [color='rgb(0,255,0)'] - color of the debug info to be rendered. (format is css color string).
  64713. */
  64714. box2dBody: function (body, color) {
  64715. this.start();
  64716. Phaser.Physics.Box2D.renderBody(this.context, body, color);
  64717. this.stop();
  64718. },
  64719. /**
  64720. * Destroy this object.
  64721. *
  64722. * @method Phaser.Utils.Debug#destroy
  64723. */
  64724. destroy: function () {
  64725. PIXI.CanvasPool.remove(this);
  64726. }
  64727. };
  64728. Phaser.Utils.Debug.prototype.constructor = Phaser.Utils.Debug;
  64729. /**
  64730. * @author Richard Davey <rich@photonstorm.com>
  64731. * @copyright 2016 Photon Storm Ltd.
  64732. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  64733. */
  64734. /**
  64735. * DOM utility class.
  64736. *
  64737. * Provides a useful Window and Element functions as well as cross-browser compatibility buffer.
  64738. *
  64739. * Some code originally derived from {@link https://github.com/ryanve/verge verge}.
  64740. * Some parts were inspired by the research of Ryan Van Etten, released under MIT License 2013.
  64741. *
  64742. * @class Phaser.DOM
  64743. * @static
  64744. */
  64745. Phaser.DOM = {
  64746. /**
  64747. * Get the [absolute] position of the element relative to the Document.
  64748. *
  64749. * The value may vary slightly as the page is scrolled due to rounding errors.
  64750. *
  64751. * @method Phaser.DOM.getOffset
  64752. * @param {DOMElement} element - The targeted element that we want to retrieve the offset.
  64753. * @param {Phaser.Point} [point] - The point we want to take the x/y values of the offset.
  64754. * @return {Phaser.Point} - A point objet with the offsetX and Y as its properties.
  64755. */
  64756. getOffset: function (element, point) {
  64757. point = point || new Phaser.Point();
  64758. var box = element.getBoundingClientRect();
  64759. var scrollTop = Phaser.DOM.scrollY;
  64760. var scrollLeft = Phaser.DOM.scrollX;
  64761. var clientTop = document.documentElement.clientTop;
  64762. var clientLeft = document.documentElement.clientLeft;
  64763. point.x = box.left + scrollLeft - clientLeft;
  64764. point.y = box.top + scrollTop - clientTop;
  64765. return point;
  64766. },
  64767. /**
  64768. * A cross-browser element.getBoundingClientRect method with optional cushion.
  64769. *
  64770. * Returns a plain object containing the properties `top/bottom/left/right/width/height` with respect to the top-left corner of the current viewport.
  64771. * Its properties match the native rectangle.
  64772. * The cushion parameter is an amount of pixels (+/-) to cushion the element.
  64773. * It adjusts the measurements such that it is possible to detect when an element is near the viewport.
  64774. *
  64775. * @method Phaser.DOM.getBounds
  64776. * @param {DOMElement|Object} element - The element or stack (uses first item) to get the bounds for.
  64777. * @param {number} [cushion] - A +/- pixel adjustment amount.
  64778. * @return {Object|boolean} A plain object containing the properties `top/bottom/left/right/width/height` or `false` if a non-valid element is given.
  64779. */
  64780. getBounds: function (element, cushion) {
  64781. if (cushion === undefined) { cushion = 0; }
  64782. element = element && !element.nodeType ? element[0] : element;
  64783. if (!element || element.nodeType !== 1)
  64784. {
  64785. return false;
  64786. }
  64787. else
  64788. {
  64789. return this.calibrate(element.getBoundingClientRect(), cushion);
  64790. }
  64791. },
  64792. /**
  64793. * Calibrates element coordinates for `inLayoutViewport` checks.
  64794. *
  64795. * @method Phaser.DOM.calibrate
  64796. * @private
  64797. * @param {object} coords - An object containing the following properties: `{top: number, right: number, bottom: number, left: number}`
  64798. * @param {number} [cushion] - A value to adjust the coordinates by.
  64799. * @return {object} The calibrated element coordinates
  64800. */
  64801. calibrate: function (coords, cushion) {
  64802. cushion = +cushion || 0;
  64803. var output = { width: 0, height: 0, left: 0, right: 0, top: 0, bottom: 0 };
  64804. output.width = (output.right = coords.right + cushion) - (output.left = coords.left - cushion);
  64805. output.height = (output.bottom = coords.bottom + cushion) - (output.top = coords.top - cushion);
  64806. return output;
  64807. },
  64808. /**
  64809. * Get the Visual viewport aspect ratio (or the aspect ratio of an object or element)
  64810. *
  64811. * @method Phaser.DOM.getAspectRatio
  64812. * @param {(DOMElement|Object)} [object=(visualViewport)] - The object to determine the aspect ratio for. Must have public `width` and `height` properties or methods.
  64813. * @return {number} The aspect ratio.
  64814. */
  64815. getAspectRatio: function (object) {
  64816. object = null == object ? this.visualBounds : 1 === object.nodeType ? this.getBounds(object) : object;
  64817. var w = object['width'];
  64818. var h = object['height'];
  64819. if (typeof w === 'function')
  64820. {
  64821. w = w.call(object);
  64822. }
  64823. if (typeof h === 'function')
  64824. {
  64825. h = h.call(object);
  64826. }
  64827. return w / h;
  64828. },
  64829. /**
  64830. * Tests if the given DOM element is within the Layout viewport.
  64831. *
  64832. * The optional cushion parameter allows you to specify a distance.
  64833. *
  64834. * inLayoutViewport(element, 100) is `true` if the element is in the viewport or 100px near it.
  64835. * inLayoutViewport(element, -100) is `true` if the element is in the viewport or at least 100px near it.
  64836. *
  64837. * @method Phaser.DOM.inLayoutViewport
  64838. * @param {DOMElement|Object} element - The DOM element to check. If no element is given it defaults to the Phaser game canvas.
  64839. * @param {number} [cushion] - The cushion allows you to specify a distance within which the element must be within the viewport.
  64840. * @return {boolean} True if the element is within the viewport, or within `cushion` distance from it.
  64841. */
  64842. inLayoutViewport: function (element, cushion) {
  64843. var r = this.getBounds(element, cushion);
  64844. return !!r && r.bottom >= 0 && r.right >= 0 && r.top <= this.layoutBounds.width && r.left <= this.layoutBounds.height;
  64845. },
  64846. /**
  64847. * Returns the device screen orientation.
  64848. *
  64849. * Orientation values: 'portrait-primary', 'landscape-primary', 'portrait-secondary', 'landscape-secondary'.
  64850. *
  64851. * Order of resolving:
  64852. * - Screen Orientation API, or variation of - Future track. Most desktop and mobile browsers.
  64853. * - Screen size ratio check - If fallback is 'screen', suited for desktops.
  64854. * - Viewport size ratio check - If fallback is 'viewport', suited for mobile.
  64855. * - window.orientation - If fallback is 'window.orientation', works iOS and probably most Android; non-recommended track.
  64856. * - Media query
  64857. * - Viewport size ratio check (probably only IE9 and legacy mobile gets here..)
  64858. *
  64859. * See
  64860. * - https://w3c.github.io/screen-orientation/ (conflicts with mozOrientation/msOrientation)
  64861. * - https://developer.mozilla.org/en-US/docs/Web/API/Screen.orientation (mozOrientation)
  64862. * - http://msdn.microsoft.com/en-us/library/ie/dn342934(v=vs.85).aspx
  64863. * - https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Testing_media_queries
  64864. * - http://stackoverflow.com/questions/4917664/detect-viewport-orientation
  64865. * - http://www.matthewgifford.com/blog/2011/12/22/a-misconception-about-window-orientation
  64866. *
  64867. * @method Phaser.DOM.getScreenOrientation
  64868. * @protected
  64869. * @param {string} [primaryFallback=(none)] - Specify 'screen', 'viewport', or 'window.orientation'.
  64870. */
  64871. getScreenOrientation: function (primaryFallback) {
  64872. var screen = window.screen;
  64873. var orientation = screen.orientation || screen.mozOrientation || screen.msOrientation;
  64874. if (orientation && typeof orientation.type === 'string')
  64875. {
  64876. // Screen Orientation API specification
  64877. return orientation.type;
  64878. }
  64879. else if (typeof orientation === 'string')
  64880. {
  64881. // moz/ms-orientation are strings
  64882. return orientation;
  64883. }
  64884. var PORTRAIT = 'portrait-primary';
  64885. var LANDSCAPE = 'landscape-primary';
  64886. if (primaryFallback === 'screen')
  64887. {
  64888. return (screen.height > screen.width) ? PORTRAIT : LANDSCAPE;
  64889. }
  64890. else if (primaryFallback === 'viewport')
  64891. {
  64892. return (this.visualBounds.height > this.visualBounds.width) ? PORTRAIT : LANDSCAPE;
  64893. }
  64894. else if (primaryFallback === 'window.orientation' && typeof window.orientation === 'number')
  64895. {
  64896. // This may change by device based on "natural" orientation.
  64897. return (window.orientation === 0 || window.orientation === 180) ? PORTRAIT : LANDSCAPE;
  64898. }
  64899. else if (window.matchMedia)
  64900. {
  64901. if (window.matchMedia("(orientation: portrait)").matches)
  64902. {
  64903. return PORTRAIT;
  64904. }
  64905. else if (window.matchMedia("(orientation: landscape)").matches)
  64906. {
  64907. return LANDSCAPE;
  64908. }
  64909. }
  64910. return (this.visualBounds.height > this.visualBounds.width) ? PORTRAIT : LANDSCAPE;
  64911. },
  64912. /**
  64913. * The bounds of the Visual viewport, as discussed in
  64914. * {@link http://www.quirksmode.org/mobile/viewports.html A tale of two viewports — part one}
  64915. * with one difference: the viewport size _excludes_ scrollbars, as found on some desktop browsers.
  64916. *
  64917. * Supported mobile:
  64918. * iOS/Safari, Android 4, IE10, Firefox OS (maybe not Firefox Android), Opera Mobile 16
  64919. *
  64920. * The properties change dynamically.
  64921. *
  64922. * @type {Phaser.Rectangle}
  64923. * @property {number} x - Scroll, left offset - eg. "scrollX"
  64924. * @property {number} y - Scroll, top offset - eg. "scrollY"
  64925. * @property {number} width - Viewport width in pixels.
  64926. * @property {number} height - Viewport height in pixels.
  64927. * @readonly
  64928. */
  64929. visualBounds: new Phaser.Rectangle(),
  64930. /**
  64931. * The bounds of the Layout viewport, as discussed in
  64932. * {@link http://www.quirksmode.org/mobile/viewports2.html A tale of two viewports — part two};
  64933. * but honoring the constraints as specified applicable viewport meta-tag.
  64934. *
  64935. * The bounds returned are not guaranteed to be fully aligned with CSS media queries (see
  64936. * {@link http://www.matanich.com/2013/01/07/viewport-size/ What size is my viewport?}).
  64937. *
  64938. * This is _not_ representative of the Visual bounds: in particular the non-primary axis will
  64939. * generally be significantly larger than the screen height on mobile devices when running with a
  64940. * constrained viewport.
  64941. *
  64942. * The properties change dynamically.
  64943. *
  64944. * @type {Phaser.Rectangle}
  64945. * @property {number} width - Viewport width in pixels.
  64946. * @property {number} height - Viewport height in pixels.
  64947. * @readonly
  64948. */
  64949. layoutBounds: new Phaser.Rectangle(),
  64950. /**
  64951. * The size of the document / Layout viewport.
  64952. *
  64953. * This incorrectly reports the dimensions in IE.
  64954. *
  64955. * The properties change dynamically.
  64956. *
  64957. * @type {Phaser.Rectangle}
  64958. * @property {number} width - Document width in pixels.
  64959. * @property {number} height - Document height in pixels.
  64960. * @readonly
  64961. */
  64962. documentBounds: new Phaser.Rectangle()
  64963. };
  64964. Phaser.Device.whenReady(function (device) {
  64965. // All target browsers should support page[XY]Offset.
  64966. var scrollX = window && ('pageXOffset' in window) ?
  64967. function () { return window.pageXOffset; } :
  64968. function () { return document.documentElement.scrollLeft; };
  64969. var scrollY = window && ('pageYOffset' in window) ?
  64970. function () { return window.pageYOffset; } :
  64971. function () { return document.documentElement.scrollTop; };
  64972. /**
  64973. * A cross-browser window.scrollX.
  64974. *
  64975. * @name Phaser.DOM.scrollX
  64976. * @property {number} scrollX
  64977. * @readonly
  64978. * @protected
  64979. */
  64980. Object.defineProperty(Phaser.DOM, "scrollX", {
  64981. get: scrollX
  64982. });
  64983. /**
  64984. * A cross-browser window.scrollY.
  64985. *
  64986. * @name Phaser.DOM.scrollY
  64987. * @property {number} scrollY
  64988. * @readonly
  64989. * @protected
  64990. */
  64991. Object.defineProperty(Phaser.DOM, "scrollY", {
  64992. get: scrollY
  64993. });
  64994. Object.defineProperty(Phaser.DOM.visualBounds, "x", {
  64995. get: scrollX
  64996. });
  64997. Object.defineProperty(Phaser.DOM.visualBounds, "y", {
  64998. get: scrollY
  64999. });
  65000. Object.defineProperty(Phaser.DOM.layoutBounds, "x", {
  65001. value: 0
  65002. });
  65003. Object.defineProperty(Phaser.DOM.layoutBounds, "y", {
  65004. value: 0
  65005. });
  65006. var treatAsDesktop = device.desktop &&
  65007. (document.documentElement.clientWidth <= window.innerWidth) &&
  65008. (document.documentElement.clientHeight <= window.innerHeight);
  65009. // Desktop browsers align the layout viewport with the visual viewport.
  65010. // This differs from mobile browsers with their zooming design.
  65011. // Ref. http://quirksmode.org/mobile/tableViewport.html
  65012. if (treatAsDesktop)
  65013. {
  65014. // PST- When scrollbars are not included this causes upstream issues in ScaleManager.
  65015. // So reverted to the old "include scrollbars."
  65016. var clientWidth = function () {
  65017. return Math.max(window.innerWidth, document.documentElement.clientWidth);
  65018. };
  65019. var clientHeight = function () {
  65020. return Math.max(window.innerHeight, document.documentElement.clientHeight);
  65021. };
  65022. // Interested in area sans-scrollbar
  65023. Object.defineProperty(Phaser.DOM.visualBounds, "width", {
  65024. get: clientWidth
  65025. });
  65026. Object.defineProperty(Phaser.DOM.visualBounds, "height", {
  65027. get: clientHeight
  65028. });
  65029. Object.defineProperty(Phaser.DOM.layoutBounds, "width", {
  65030. get: clientWidth
  65031. });
  65032. Object.defineProperty(Phaser.DOM.layoutBounds, "height", {
  65033. get: clientHeight
  65034. });
  65035. } else {
  65036. Object.defineProperty(Phaser.DOM.visualBounds, "width", {
  65037. get: function () {
  65038. return window.innerWidth;
  65039. }
  65040. });
  65041. Object.defineProperty(Phaser.DOM.visualBounds, "height", {
  65042. get: function () {
  65043. return window.innerHeight;
  65044. }
  65045. });
  65046. Object.defineProperty(Phaser.DOM.layoutBounds, "width", {
  65047. get: function () {
  65048. var a = document.documentElement.clientWidth;
  65049. var b = window.innerWidth;
  65050. return a < b ? b : a; // max
  65051. }
  65052. });
  65053. Object.defineProperty(Phaser.DOM.layoutBounds, "height", {
  65054. get: function () {
  65055. var a = document.documentElement.clientHeight;
  65056. var b = window.innerHeight;
  65057. return a < b ? b : a; // max
  65058. }
  65059. });
  65060. }
  65061. // For Phaser.DOM.documentBounds
  65062. // Ref. http://www.quirksmode.org/mobile/tableViewport_desktop.html
  65063. Object.defineProperty(Phaser.DOM.documentBounds, "x", {
  65064. value: 0
  65065. });
  65066. Object.defineProperty(Phaser.DOM.documentBounds, "y", {
  65067. value: 0
  65068. });
  65069. Object.defineProperty(Phaser.DOM.documentBounds, "width", {
  65070. get: function () {
  65071. var d = document.documentElement;
  65072. return Math.max(d.clientWidth, d.offsetWidth, d.scrollWidth);
  65073. }
  65074. });
  65075. Object.defineProperty(Phaser.DOM.documentBounds, "height", {
  65076. get: function () {
  65077. var d = document.documentElement;
  65078. return Math.max(d.clientHeight, d.offsetHeight, d.scrollHeight);
  65079. }
  65080. });
  65081. }, null, true);
  65082. /**
  65083. * @author Richard Davey <rich@photonstorm.com>
  65084. * @copyright 2016 Photon Storm Ltd.
  65085. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  65086. */
  65087. /**
  65088. * ArraySet is a Set data structure (items must be unique within the set) that also maintains order.
  65089. * This allows specific items to be easily added or removed from the Set.
  65090. *
  65091. * Item equality (and uniqueness) is determined by the behavior of `Array.indexOf`.
  65092. *
  65093. * This used primarily by the Input subsystem.
  65094. *
  65095. * @class Phaser.ArraySet
  65096. * @constructor
  65097. * @param {any[]} [list=(new array)] - The backing array: if specified the items in the list _must_ be unique, per `Array.indexOf`, and the ownership of the array _should_ be relinquished to the ArraySet.
  65098. */
  65099. Phaser.ArraySet = function (list) {
  65100. /**
  65101. * Current cursor position as established by `first` and `next`.
  65102. * @property {integer} position
  65103. * @default
  65104. */
  65105. this.position = 0;
  65106. /**
  65107. * The backing array.
  65108. * @property {any[]} list
  65109. */
  65110. this.list = list || [];
  65111. };
  65112. Phaser.ArraySet.prototype = {
  65113. /**
  65114. * Adds a new element to the end of the list.
  65115. * If the item already exists in the list it is not moved.
  65116. *
  65117. * @method Phaser.ArraySet#add
  65118. * @param {any} item - The element to add to this list.
  65119. * @return {any} The item that was added.
  65120. */
  65121. add: function (item) {
  65122. if (!this.exists(item))
  65123. {
  65124. this.list.push(item);
  65125. }
  65126. return item;
  65127. },
  65128. /**
  65129. * Gets the index of the item in the list, or -1 if it isn't in the list.
  65130. *
  65131. * @method Phaser.ArraySet#getIndex
  65132. * @param {any} item - The element to get the list index for.
  65133. * @return {integer} The index of the item or -1 if not found.
  65134. */
  65135. getIndex: function (item) {
  65136. return this.list.indexOf(item);
  65137. },
  65138. /**
  65139. * Gets an item from the set based on the property strictly equaling the value given.
  65140. * Returns null if not found.
  65141. *
  65142. * @method Phaser.ArraySet#getByKey
  65143. * @param {string} property - The property to check against the value.
  65144. * @param {any} value - The value to check if the property strictly equals.
  65145. * @return {any} The item that was found, or null if nothing matched.
  65146. */
  65147. getByKey: function (property, value) {
  65148. var i = this.list.length;
  65149. while (i--)
  65150. {
  65151. if (this.list[i][property] === value)
  65152. {
  65153. return this.list[i];
  65154. }
  65155. }
  65156. return null;
  65157. },
  65158. /**
  65159. * Checks for the item within this list.
  65160. *
  65161. * @method Phaser.ArraySet#exists
  65162. * @param {any} item - The element to get the list index for.
  65163. * @return {boolean} True if the item is found in the list, otherwise false.
  65164. */
  65165. exists: function (item) {
  65166. return (this.list.indexOf(item) > -1);
  65167. },
  65168. /**
  65169. * Removes all the items.
  65170. *
  65171. * @method Phaser.ArraySet#reset
  65172. */
  65173. reset: function () {
  65174. this.list.length = 0;
  65175. },
  65176. /**
  65177. * Removes the given element from this list if it exists.
  65178. *
  65179. * @method Phaser.ArraySet#remove
  65180. * @param {any} item - The item to be removed from the list.
  65181. * @return {any} item - The item that was removed.
  65182. */
  65183. remove: function (item) {
  65184. var idx = this.list.indexOf(item);
  65185. if (idx > -1)
  65186. {
  65187. this.list.splice(idx, 1);
  65188. return item;
  65189. }
  65190. },
  65191. /**
  65192. * Sets the property `key` to the given value on all members of this list.
  65193. *
  65194. * @method Phaser.ArraySet#setAll
  65195. * @param {any} key - The property of the item to set.
  65196. * @param {any} value - The value to set the property to.
  65197. */
  65198. setAll: function (key, value) {
  65199. var i = this.list.length;
  65200. while (i--)
  65201. {
  65202. if (this.list[i])
  65203. {
  65204. this.list[i][key] = value;
  65205. }
  65206. }
  65207. },
  65208. /**
  65209. * Calls a function on all members of this list, using the member as the context for the callback.
  65210. *
  65211. * If the `key` property is present it must be a function.
  65212. * The function is invoked using the item as the context.
  65213. *
  65214. * @method Phaser.ArraySet#callAll
  65215. * @param {string} key - The name of the property with the function to call.
  65216. * @param {...*} parameter - Additional parameters that will be passed to the callback.
  65217. */
  65218. callAll: function (key) {
  65219. var args = Array.prototype.slice.call(arguments, 1);
  65220. var i = this.list.length;
  65221. while (i--)
  65222. {
  65223. if (this.list[i] && this.list[i][key])
  65224. {
  65225. this.list[i][key].apply(this.list[i], args);
  65226. }
  65227. }
  65228. },
  65229. /**
  65230. * Removes every member from this ArraySet and optionally destroys it.
  65231. *
  65232. * @method Phaser.ArraySet#removeAll
  65233. * @param {boolean} [destroy=false] - Call `destroy` on each member as it's removed from this set.
  65234. */
  65235. removeAll: function (destroy) {
  65236. if (destroy === undefined) { destroy = false; }
  65237. var i = this.list.length;
  65238. while (i--)
  65239. {
  65240. if (this.list[i])
  65241. {
  65242. var item = this.remove(this.list[i]);
  65243. if (destroy)
  65244. {
  65245. item.destroy();
  65246. }
  65247. }
  65248. }
  65249. this.position = 0;
  65250. this.list = [];
  65251. }
  65252. };
  65253. /**
  65254. * Number of items in the ArraySet. Same as `list.length`.
  65255. *
  65256. * @name Phaser.ArraySet#total
  65257. * @property {integer} total
  65258. */
  65259. Object.defineProperty(Phaser.ArraySet.prototype, "total", {
  65260. get: function () {
  65261. return this.list.length;
  65262. }
  65263. });
  65264. /**
  65265. * Returns the first item and resets the cursor to the start.
  65266. *
  65267. * @name Phaser.ArraySet#first
  65268. * @property {any} first
  65269. */
  65270. Object.defineProperty(Phaser.ArraySet.prototype, "first", {
  65271. get: function () {
  65272. this.position = 0;
  65273. if (this.list.length > 0)
  65274. {
  65275. return this.list[0];
  65276. }
  65277. else
  65278. {
  65279. return null;
  65280. }
  65281. }
  65282. });
  65283. /**
  65284. * Returns the the next item (based on the cursor) and advances the cursor.
  65285. *
  65286. * @name Phaser.ArraySet#next
  65287. * @property {any} next
  65288. */
  65289. Object.defineProperty(Phaser.ArraySet.prototype, "next", {
  65290. get: function () {
  65291. if (this.position < this.list.length)
  65292. {
  65293. this.position++;
  65294. return this.list[this.position];
  65295. }
  65296. else
  65297. {
  65298. return null;
  65299. }
  65300. }
  65301. });
  65302. Phaser.ArraySet.prototype.constructor = Phaser.ArraySet;
  65303. /**
  65304. * @author Richard Davey <rich@photonstorm.com>
  65305. * @copyright 2016 Photon Storm Ltd.
  65306. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  65307. */
  65308. /**
  65309. * Utility functions for dealing with Arrays.
  65310. *
  65311. * @class Phaser.ArrayUtils
  65312. * @static
  65313. */
  65314. Phaser.ArrayUtils = {
  65315. /**
  65316. * Fetch a random entry from the given array.
  65317. *
  65318. * Will return null if there are no array items that fall within the specified range
  65319. * or if there is no item for the randomly chosen index.
  65320. *
  65321. * @method
  65322. * @param {any[]} objects - An array of objects.
  65323. * @param {integer} startIndex - Optional offset off the front of the array. Default value is 0, or the beginning of the array.
  65324. * @param {integer} length - Optional restriction on the number of values you want to randomly select from.
  65325. * @return {object} The random object that was selected.
  65326. */
  65327. getRandomItem: function (objects, startIndex, length) {
  65328. if (objects === null) { return null; }
  65329. if (startIndex === undefined) { startIndex = 0; }
  65330. if (length === undefined) { length = objects.length; }
  65331. var randomIndex = startIndex + Math.floor(Math.random() * length);
  65332. return objects[randomIndex] === undefined ? null : objects[randomIndex];
  65333. },
  65334. /**
  65335. * Removes a random object from the given array and returns it.
  65336. *
  65337. * Will return null if there are no array items that fall within the specified range
  65338. * or if there is no item for the randomly chosen index.
  65339. *
  65340. * @method
  65341. * @param {any[]} objects - An array of objects.
  65342. * @param {integer} startIndex - Optional offset off the front of the array. Default value is 0, or the beginning of the array.
  65343. * @param {integer} length - Optional restriction on the number of values you want to randomly select from.
  65344. * @return {object} The random object that was removed.
  65345. */
  65346. removeRandomItem: function (objects, startIndex, length) {
  65347. if (objects == null) { // undefined or null
  65348. return null;
  65349. }
  65350. if (startIndex === undefined) { startIndex = 0; }
  65351. if (length === undefined) { length = objects.length; }
  65352. var randomIndex = startIndex + Math.floor(Math.random() * length);
  65353. if (randomIndex < objects.length)
  65354. {
  65355. var removed = objects.splice(randomIndex, 1);
  65356. return removed[0] === undefined ? null : removed[0];
  65357. }
  65358. else
  65359. {
  65360. return null;
  65361. }
  65362. },
  65363. /**
  65364. * A standard Fisher-Yates Array shuffle implementation which modifies the array in place.
  65365. *
  65366. * @method
  65367. * @param {any[]} array - The array to shuffle.
  65368. * @return {any[]} The original array, now shuffled.
  65369. */
  65370. shuffle: function (array) {
  65371. for (var i = array.length - 1; i > 0; i--)
  65372. {
  65373. var j = Math.floor(Math.random() * (i + 1));
  65374. var temp = array[i];
  65375. array[i] = array[j];
  65376. array[j] = temp;
  65377. }
  65378. return array;
  65379. },
  65380. /**
  65381. * Transposes the elements of the given matrix (array of arrays).
  65382. *
  65383. * @method
  65384. * @param {Array<any[]>} array - The matrix to transpose.
  65385. * @return {Array<any[]>} A new transposed matrix
  65386. */
  65387. transposeMatrix: function (array) {
  65388. var sourceRowCount = array.length;
  65389. var sourceColCount = array[0].length;
  65390. var result = new Array(sourceColCount);
  65391. for (var i = 0; i < sourceColCount; i++)
  65392. {
  65393. result[i] = new Array(sourceRowCount);
  65394. for (var j = sourceRowCount - 1; j > -1; j--)
  65395. {
  65396. result[i][j] = array[j][i];
  65397. }
  65398. }
  65399. return result;
  65400. },
  65401. /**
  65402. * Rotates the given matrix (array of arrays).
  65403. *
  65404. * Based on the routine from {@link http://jsfiddle.net/MrPolywhirl/NH42z/}.
  65405. *
  65406. * @method
  65407. * @param {Array<any[]>} matrix - The array to rotate; this matrix _may_ be altered.
  65408. * @param {number|string} direction - The amount to rotate: the rotation in degrees (90, -90, 270, -270, 180) or a string command ('rotateLeft', 'rotateRight' or 'rotate180').
  65409. * @return {Array<any[]>} The rotated matrix. The source matrix should be discarded for the returned matrix.
  65410. */
  65411. rotateMatrix: function (matrix, direction) {
  65412. if (typeof direction !== 'string')
  65413. {
  65414. direction = ((direction % 360) + 360) % 360;
  65415. }
  65416. if (direction === 90 || direction === -270 || direction === 'rotateLeft')
  65417. {
  65418. matrix = Phaser.ArrayUtils.transposeMatrix(matrix);
  65419. matrix = matrix.reverse();
  65420. }
  65421. else if (direction === -90 || direction === 270 || direction === 'rotateRight')
  65422. {
  65423. matrix = matrix.reverse();
  65424. matrix = Phaser.ArrayUtils.transposeMatrix(matrix);
  65425. }
  65426. else if (Math.abs(direction) === 180 || direction === 'rotate180')
  65427. {
  65428. for (var i = 0; i < matrix.length; i++)
  65429. {
  65430. matrix[i].reverse();
  65431. }
  65432. matrix = matrix.reverse();
  65433. }
  65434. return matrix;
  65435. },
  65436. /**
  65437. * Snaps a value to the nearest value in an array.
  65438. * The result will always be in the range `[first_value, last_value]`.
  65439. *
  65440. * @method
  65441. * @param {number} value - The search value
  65442. * @param {number[]} arr - The input array which _must_ be sorted.
  65443. * @return {number} The nearest value found.
  65444. */
  65445. findClosest: function (value, arr) {
  65446. if (!arr.length)
  65447. {
  65448. return NaN;
  65449. }
  65450. else if (arr.length === 1 || value < arr[0])
  65451. {
  65452. return arr[0];
  65453. }
  65454. var i = 1;
  65455. while (arr[i] < value) {
  65456. i++;
  65457. }
  65458. var low = arr[i - 1];
  65459. var high = (i < arr.length) ? arr[i] : Number.POSITIVE_INFINITY;
  65460. return ((high - value) <= (value - low)) ? high : low;
  65461. },
  65462. /**
  65463. * Moves the element from the start of the array to the end, shifting all items in the process.
  65464. * The "rotation" happens to the left.
  65465. *
  65466. * @method Phaser.ArrayUtils.rotate
  65467. * @param {any[]} array - The array to shift/rotate. The array is modified.
  65468. * @return {any} The shifted value.
  65469. */
  65470. rotate: function (array) {
  65471. var s = array.shift();
  65472. array.push(s);
  65473. return s;
  65474. },
  65475. /**
  65476. * Create an array representing the inclusive range of numbers (usually integers) in `[start, end]`.
  65477. * This is equivalent to `numberArrayStep(start, end, 1)`.
  65478. *
  65479. * @method Phaser.ArrayUtils#numberArray
  65480. * @param {number} start - The minimum value the array starts with.
  65481. * @param {number} end - The maximum value the array contains.
  65482. * @return {number[]} The array of number values.
  65483. */
  65484. numberArray: function (start, end) {
  65485. var result = [];
  65486. for (var i = start; i <= end; i++)
  65487. {
  65488. result.push(i);
  65489. }
  65490. return result;
  65491. },
  65492. /**
  65493. * Create an array of numbers (positive and/or negative) progressing from `start`
  65494. * up to but not including `end` by advancing by `step`.
  65495. *
  65496. * If `start` is less than `end` a zero-length range is created unless a negative `step` is specified.
  65497. *
  65498. * Certain values for `start` and `end` (eg. NaN/undefined/null) are currently coerced to 0;
  65499. * for forward compatibility make sure to pass in actual numbers.
  65500. *
  65501. * @method Phaser.ArrayUtils#numberArrayStep
  65502. * @param {number} start - The start of the range.
  65503. * @param {number} [end] - The end of the range.
  65504. * @param {number} [step=1] - The value to increment or decrement by.
  65505. * @returns {Array} Returns the new array of numbers.
  65506. * @example
  65507. * Phaser.ArrayUtils.numberArrayStep(4);
  65508. * // => [0, 1, 2, 3]
  65509. *
  65510. * Phaser.ArrayUtils.numberArrayStep(1, 5);
  65511. * // => [1, 2, 3, 4]
  65512. *
  65513. * Phaser.ArrayUtils.numberArrayStep(0, 20, 5);
  65514. * // => [0, 5, 10, 15]
  65515. *
  65516. * Phaser.ArrayUtils.numberArrayStep(0, -4, -1);
  65517. * // => [0, -1, -2, -3]
  65518. *
  65519. * Phaser.ArrayUtils.numberArrayStep(1, 4, 0);
  65520. * // => [1, 1, 1]
  65521. *
  65522. * Phaser.ArrayUtils.numberArrayStep(0);
  65523. * // => []
  65524. */
  65525. numberArrayStep: function (start, end, step) {
  65526. if (start === undefined || start === null) { start = 0; }
  65527. if (end === undefined || end === null)
  65528. {
  65529. end = start;
  65530. start = 0;
  65531. }
  65532. if (step === undefined) { step = 1; }
  65533. var result = [];
  65534. var total = Math.max(Phaser.Math.roundAwayFromZero((end - start) / (step || 1)), 0);
  65535. for (var i = 0; i < total; i++)
  65536. {
  65537. result.push(start);
  65538. start += step;
  65539. }
  65540. return result;
  65541. }
  65542. };
  65543. /**
  65544. * @author Richard Davey <rich@photonstorm.com>
  65545. * @copyright 2016 Photon Storm Ltd.
  65546. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  65547. */
  65548. /**
  65549. * A basic Linked List data structure.
  65550. *
  65551. * This implementation _modifies_ the `prev` and `next` properties of each item added:
  65552. * - The `prev` and `next` properties must be writable and should not be used for any other purpose.
  65553. * - Items _cannot_ be added to multiple LinkedLists at the same time.
  65554. * - Only objects can be added.
  65555. *
  65556. * @class Phaser.LinkedList
  65557. * @constructor
  65558. */
  65559. Phaser.LinkedList = function () {
  65560. /**
  65561. * Next element in the list.
  65562. * @property {object} next
  65563. * @default
  65564. */
  65565. this.next = null;
  65566. /**
  65567. * Previous element in the list.
  65568. * @property {object} prev
  65569. * @default
  65570. */
  65571. this.prev = null;
  65572. /**
  65573. * First element in the list.
  65574. * @property {object} first
  65575. * @default
  65576. */
  65577. this.first = null;
  65578. /**
  65579. * Last element in the list.
  65580. * @property {object} last
  65581. * @default
  65582. */
  65583. this.last = null;
  65584. /**
  65585. * Number of elements in the list.
  65586. * @property {integer} total
  65587. * @default
  65588. */
  65589. this.total = 0;
  65590. };
  65591. Phaser.LinkedList.prototype = {
  65592. /**
  65593. * Adds a new element to this linked list.
  65594. *
  65595. * @method Phaser.LinkedList#add
  65596. * @param {object} item - The element to add to this list. Can be a Phaser.Sprite or any other object you need to quickly iterate through.
  65597. * @return {object} The item that was added.
  65598. */
  65599. add: function (item) {
  65600. // If the list is empty
  65601. if (this.total === 0 && this.first === null && this.last === null)
  65602. {
  65603. this.first = item;
  65604. this.last = item;
  65605. this.next = item;
  65606. item.prev = this;
  65607. this.total++;
  65608. return item;
  65609. }
  65610. // Gets appended to the end of the list, regardless of anything, and it won't have any children of its own (non-nested list)
  65611. this.last.next = item;
  65612. item.prev = this.last;
  65613. this.last = item;
  65614. this.total++;
  65615. return item;
  65616. },
  65617. /**
  65618. * Resets the first, last, next and previous node pointers in this list.
  65619. *
  65620. * @method Phaser.LinkedList#reset
  65621. */
  65622. reset: function () {
  65623. this.first = null;
  65624. this.last = null;
  65625. this.next = null;
  65626. this.prev = null;
  65627. this.total = 0;
  65628. },
  65629. /**
  65630. * Removes the given element from this linked list if it exists.
  65631. *
  65632. * @method Phaser.LinkedList#remove
  65633. * @param {object} item - The item to be removed from the list.
  65634. */
  65635. remove: function (item) {
  65636. if (this.total === 1)
  65637. {
  65638. this.reset();
  65639. item.next = item.prev = null;
  65640. return;
  65641. }
  65642. if (item === this.first)
  65643. {
  65644. // It was 'first', make 'first' point to first.next
  65645. this.first = this.first.next;
  65646. }
  65647. else if (item === this.last)
  65648. {
  65649. // It was 'last', make 'last' point to last.prev
  65650. this.last = this.last.prev;
  65651. }
  65652. if (item.prev)
  65653. {
  65654. // make item.prev.next point to childs.next instead of item
  65655. item.prev.next = item.next;
  65656. }
  65657. if (item.next)
  65658. {
  65659. // make item.next.prev point to item.prev instead of item
  65660. item.next.prev = item.prev;
  65661. }
  65662. item.next = item.prev = null;
  65663. if (this.first === null )
  65664. {
  65665. this.last = null;
  65666. }
  65667. this.total--;
  65668. },
  65669. /**
  65670. * Calls a function on all members of this list, using the member as the context for the callback.
  65671. * The function must exist on the member.
  65672. *
  65673. * @method Phaser.LinkedList#callAll
  65674. * @param {function} callback - The function to call.
  65675. */
  65676. callAll: function (callback) {
  65677. if (!this.first || !this.last)
  65678. {
  65679. return;
  65680. }
  65681. var entity = this.first;
  65682. do
  65683. {
  65684. if (entity && entity[callback])
  65685. {
  65686. entity[callback].call(entity);
  65687. }
  65688. entity = entity.next;
  65689. }
  65690. while(entity != this.last.next);
  65691. }
  65692. };
  65693. Phaser.LinkedList.prototype.constructor = Phaser.LinkedList;
  65694. /**
  65695. * @author Richard Davey <rich@photonstorm.com>
  65696. * @copyright 2016 Photon Storm Ltd.
  65697. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  65698. */
  65699. /**
  65700. * The Phaser.Create class is a collection of smaller helper methods that allow you to generate game content
  65701. * quickly and easily, without the need for any external files. You can create textures for sprites and in
  65702. * coming releases we'll add dynamic sound effect generation support as well (like sfxr).
  65703. *
  65704. * Access this via `Game.create` (`this.game.create` from within a State object)
  65705. *
  65706. * @class Phaser.Create
  65707. * @constructor
  65708. * @param {Phaser.Game} game - Game reference to the currently running game.
  65709. */
  65710. Phaser.Create = function (game) {
  65711. /**
  65712. * @property {Phaser.Game} game - A reference to the currently running Game.
  65713. */
  65714. this.game = game;
  65715. /**
  65716. * @property {Phaser.BitmapData} bmd - The internal BitmapData Create uses to generate textures from.
  65717. */
  65718. this.bmd = null;
  65719. /**
  65720. * @property {HTMLCanvasElement} canvas - The canvas the BitmapData uses.
  65721. */
  65722. this.canvas = null;
  65723. /**
  65724. * @property {CanvasRenderingContext2D} context - The 2d context of the canvas.
  65725. */
  65726. this.ctx = null;
  65727. /**
  65728. * @property {array} palettes - A range of 16 color palettes for use with sprite generation.
  65729. */
  65730. this.palettes = [
  65731. { 0: '#000', 1: '#9D9D9D', 2: '#FFF', 3: '#BE2633', 4: '#E06F8B', 5: '#493C2B', 6: '#A46422', 7: '#EB8931', 8: '#F7E26B', 9: '#2F484E', A: '#44891A', B: '#A3CE27', C: '#1B2632', D: '#005784', E: '#31A2F2', F: '#B2DCEF' },
  65732. { 0: '#000', 1: '#191028', 2: '#46af45', 3: '#a1d685', 4: '#453e78', 5: '#7664fe', 6: '#833129', 7: '#9ec2e8', 8: '#dc534b', 9: '#e18d79', A: '#d6b97b', B: '#e9d8a1', C: '#216c4b', D: '#d365c8', E: '#afaab9', F: '#f5f4eb' },
  65733. { 0: '#000', 1: '#2234d1', 2: '#0c7e45', 3: '#44aacc', 4: '#8a3622', 5: '#5c2e78', 6: '#aa5c3d', 7: '#b5b5b5', 8: '#5e606e', 9: '#4c81fb', A: '#6cd947', B: '#7be2f9', C: '#eb8a60', D: '#e23d69', E: '#ffd93f', F: '#fff' },
  65734. { 0: '#000', 1: '#fff', 2: '#8b4131', 3: '#7bbdc5', 4: '#8b41ac', 5: '#6aac41', 6: '#3931a4', 7: '#d5de73', 8: '#945a20', 9: '#5a4100', A: '#bd736a', B: '#525252', C: '#838383', D: '#acee8b', E: '#7b73de', F: '#acacac' },
  65735. { 0: '#000', 1: '#191028', 2: '#46af45', 3: '#a1d685', 4: '#453e78', 5: '#7664fe', 6: '#833129', 7: '#9ec2e8', 8: '#dc534b', 9: '#e18d79', A: '#d6b97b', B: '#e9d8a1', C: '#216c4b', D: '#d365c8', E: '#afaab9', F: '#fff' }
  65736. ];
  65737. };
  65738. /**
  65739. * A 16 color palette by [Arne](http://androidarts.com/palette/16pal.htm)
  65740. * @constant
  65741. * @type {number}
  65742. */
  65743. Phaser.Create.PALETTE_ARNE = 0;
  65744. /**
  65745. * A 16 color JMP inspired palette.
  65746. * @constant
  65747. * @type {number}
  65748. */
  65749. Phaser.Create.PALETTE_JMP = 1;
  65750. /**
  65751. * A 16 color CGA inspired palette.
  65752. * @constant
  65753. * @type {number}
  65754. */
  65755. Phaser.Create.PALETTE_CGA = 2;
  65756. /**
  65757. * A 16 color C64 inspired palette.
  65758. * @constant
  65759. * @type {number}
  65760. */
  65761. Phaser.Create.PALETTE_C64 = 3;
  65762. /**
  65763. * A 16 color palette inspired by Japanese computers like the MSX.
  65764. * @constant
  65765. * @type {number}
  65766. */
  65767. Phaser.Create.PALETTE_JAPANESE_MACHINE = 4;
  65768. Phaser.Create.prototype = {
  65769. /**
  65770. * Generates a new PIXI.Texture from the given data, which can be applied to a Sprite.
  65771. *
  65772. * This allows you to create game graphics quickly and easily, with no external files but that use actual proper images
  65773. * rather than Phaser.Graphics objects, which are expensive to render and limited in scope.
  65774. *
  65775. * Each element of the array is a string holding the pixel color values, as mapped to one of the Phaser.Create PALETTE consts.
  65776. *
  65777. * For example:
  65778. *
  65779. * `var data = [
  65780. * ' 333 ',
  65781. * ' 777 ',
  65782. * 'E333E',
  65783. * ' 333 ',
  65784. * ' 3 3 '
  65785. * ];`
  65786. *
  65787. * `game.create.texture('bob', data);`
  65788. *
  65789. * The above will create a new texture called `bob`, which will look like a little man wearing a hat. You can then use it
  65790. * for sprites the same way you use any other texture: `game.add.sprite(0, 0, 'bob');`
  65791. *
  65792. * @method Phaser.Create#texture
  65793. * @param {string} key - The key used to store this texture in the Phaser Cache.
  65794. * @param {array} data - An array of pixel data.
  65795. * @param {integer} [pixelWidth=8] - The width of each pixel.
  65796. * @param {integer} [pixelHeight=8] - The height of each pixel.
  65797. * @param {integer} [palette=0] - The palette to use when rendering the texture. One of the Phaser.Create.PALETTE consts.
  65798. * @return {PIXI.Texture} The newly generated texture.
  65799. */
  65800. texture: function (key, data, pixelWidth, pixelHeight, palette) {
  65801. if (pixelWidth === undefined) { pixelWidth = 8; }
  65802. if (pixelHeight === undefined) { pixelHeight = pixelWidth; }
  65803. if (palette === undefined) { palette = 0; }
  65804. var w = data[0].length * pixelWidth;
  65805. var h = data.length * pixelHeight;
  65806. // No bmd? Let's make one
  65807. if (this.bmd === null)
  65808. {
  65809. this.bmd = this.game.make.bitmapData();
  65810. this.canvas = this.bmd.canvas;
  65811. this.ctx = this.bmd.context;
  65812. }
  65813. this.bmd.resize(w, h);
  65814. this.bmd.clear();
  65815. // Draw it
  65816. for (var y = 0; y < data.length; y++)
  65817. {
  65818. var row = data[y];
  65819. for (var x = 0; x < row.length; x++)
  65820. {
  65821. var d = row[x];
  65822. if (d !== '.' && d !== ' ')
  65823. {
  65824. this.ctx.fillStyle = this.palettes[palette][d];
  65825. this.ctx.fillRect(x * pixelWidth, y * pixelHeight, pixelWidth, pixelHeight);
  65826. }
  65827. }
  65828. }
  65829. return this.bmd.generateTexture(key);
  65830. },
  65831. /**
  65832. * Creates a grid texture based on the given dimensions.
  65833. *
  65834. * @method Phaser.Create#grid
  65835. * @param {string} key - The key used to store this texture in the Phaser Cache.
  65836. * @param {integer} width - The width of the grid in pixels.
  65837. * @param {integer} height - The height of the grid in pixels.
  65838. * @param {integer} cellWidth - The width of the grid cells in pixels.
  65839. * @param {integer} cellHeight - The height of the grid cells in pixels.
  65840. * @param {string} color - The color to draw the grid lines in. Should be a Canvas supported color string like `#ff5500` or `rgba(200,50,3,0.5)`.
  65841. * @return {PIXI.Texture} The newly generated texture.
  65842. */
  65843. grid: function (key, width, height, cellWidth, cellHeight, color) {
  65844. // No bmd? Let's make one
  65845. if (this.bmd === null)
  65846. {
  65847. this.bmd = this.game.make.bitmapData();
  65848. this.canvas = this.bmd.canvas;
  65849. this.ctx = this.bmd.context;
  65850. }
  65851. this.bmd.resize(width, height);
  65852. this.ctx.fillStyle = color;
  65853. for (var y = 0; y < height; y += cellHeight)
  65854. {
  65855. this.ctx.fillRect(0, y, width, 1);
  65856. }
  65857. for (var x = 0; x < width; x += cellWidth)
  65858. {
  65859. this.ctx.fillRect(x, 0, 1, height);
  65860. }
  65861. return this.bmd.generateTexture(key);
  65862. }
  65863. };
  65864. Phaser.Create.prototype.constructor = Phaser.Create;
  65865. /**
  65866. * @author Richard Davey <rich@photonstorm.com>
  65867. * @copyright 2016 Photon Storm Ltd.
  65868. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  65869. */
  65870. /**
  65871. * WARNING: This is an EXPERIMENTAL class. The API will change significantly in the coming versions and is incomplete.
  65872. * Please try to avoid using in production games with a long time to build.
  65873. * This is also why the documentation is incomplete.
  65874. *
  65875. * FlexGrid is a a responsive grid manager that works in conjunction with the ScaleManager RESIZE scaling mode and FlexLayers
  65876. * to provide for game object positioning in a responsive manner.
  65877. *
  65878. * @class Phaser.FlexGrid
  65879. * @constructor
  65880. * @param {Phaser.ScaleManager} manager - The ScaleManager.
  65881. * @param {number} width - The width of the game.
  65882. * @param {number} height - The height of the game.
  65883. */
  65884. Phaser.FlexGrid = function (manager, width, height) {
  65885. /**
  65886. * @property {Phaser.Game} game - A reference to the currently running Game.
  65887. */
  65888. this.game = manager.game;
  65889. /**
  65890. * @property {Phaser.ScaleManager} manager - A reference to the ScaleManager.
  65891. */
  65892. this.manager = manager;
  65893. // The perfect dimensions on which everything else is based
  65894. this.width = width;
  65895. this.height = height;
  65896. this.boundsCustom = new Phaser.Rectangle(0, 0, width, height);
  65897. this.boundsFluid = new Phaser.Rectangle(0, 0, width, height);
  65898. this.boundsFull = new Phaser.Rectangle(0, 0, width, height);
  65899. this.boundsNone = new Phaser.Rectangle(0, 0, width, height);
  65900. /**
  65901. * @property {Phaser.Point} position -
  65902. * @readonly
  65903. */
  65904. this.positionCustom = new Phaser.Point(0, 0);
  65905. this.positionFluid = new Phaser.Point(0, 0);
  65906. this.positionFull = new Phaser.Point(0, 0);
  65907. this.positionNone = new Phaser.Point(0, 0);
  65908. /**
  65909. * @property {Phaser.Point} scaleFactor - The scale factor based on the game dimensions vs. the scaled dimensions.
  65910. * @readonly
  65911. */
  65912. this.scaleCustom = new Phaser.Point(1, 1);
  65913. this.scaleFluid = new Phaser.Point(1, 1);
  65914. this.scaleFluidInversed = new Phaser.Point(1, 1);
  65915. this.scaleFull = new Phaser.Point(1, 1);
  65916. this.scaleNone = new Phaser.Point(1, 1);
  65917. this.customWidth = 0;
  65918. this.customHeight = 0;
  65919. this.customOffsetX = 0;
  65920. this.customOffsetY = 0;
  65921. this.ratioH = width / height;
  65922. this.ratioV = height / width;
  65923. this.multiplier = 0;
  65924. this.layers = [];
  65925. };
  65926. Phaser.FlexGrid.prototype = {
  65927. /**
  65928. * Sets the core game size. This resets the w/h parameters and bounds.
  65929. *
  65930. * @method Phaser.FlexGrid#setSize
  65931. * @param {number} width - The new dimensions.
  65932. * @param {number} height - The new dimensions.
  65933. */
  65934. setSize: function (width, height) {
  65935. // These are locked and don't change until setSize is called again
  65936. this.width = width;
  65937. this.height = height;
  65938. this.ratioH = width / height;
  65939. this.ratioV = height / width;
  65940. this.scaleNone = new Phaser.Point(1, 1);
  65941. this.boundsNone.width = this.width;
  65942. this.boundsNone.height = this.height;
  65943. this.refresh();
  65944. },
  65945. // Need ability to create your own layers with custom scaling, etc.
  65946. /**
  65947. * A custom layer is centered on the game and maintains its aspect ratio as it scales up and down.
  65948. *
  65949. * @method Phaser.FlexGrid#createCustomLayer
  65950. * @param {number} width - Width of this layer in pixels.
  65951. * @param {number} height - Height of this layer in pixels.
  65952. * @param {PIXI.DisplayObject[]} [children] - An array of children that are used to populate the FlexLayer.
  65953. * @return {Phaser.FlexLayer} The Layer object.
  65954. */
  65955. createCustomLayer: function (width, height, children, addToWorld) {
  65956. if (addToWorld === undefined) { addToWorld = true; }
  65957. this.customWidth = width;
  65958. this.customHeight = height;
  65959. this.boundsCustom.width = width;
  65960. this.boundsCustom.height = height;
  65961. var layer = new Phaser.FlexLayer(this, this.positionCustom, this.boundsCustom, this.scaleCustom);
  65962. if (addToWorld)
  65963. {
  65964. this.game.world.add(layer);
  65965. }
  65966. this.layers.push(layer);
  65967. if (typeof children !== 'undefined' && typeof children !== null)
  65968. {
  65969. layer.addMultiple(children);
  65970. }
  65971. return layer;
  65972. },
  65973. /**
  65974. * A fluid layer is centered on the game and maintains its aspect ratio as it scales up and down.
  65975. *
  65976. * @method Phaser.FlexGrid#createFluidLayer
  65977. * @param {array} [children] - An array of children that are used to populate the FlexLayer.
  65978. * @return {Phaser.FlexLayer} The Layer object.
  65979. */
  65980. createFluidLayer: function (children, addToWorld) {
  65981. if (addToWorld === undefined) { addToWorld = true; }
  65982. var layer = new Phaser.FlexLayer(this, this.positionFluid, this.boundsFluid, this.scaleFluid);
  65983. if (addToWorld)
  65984. {
  65985. this.game.world.add(layer);
  65986. }
  65987. this.layers.push(layer);
  65988. if (typeof children !== 'undefined' && typeof children !== null)
  65989. {
  65990. layer.addMultiple(children);
  65991. }
  65992. return layer;
  65993. },
  65994. /**
  65995. * A full layer is placed at 0,0 and extends to the full size of the game. Children are scaled according to the fluid ratios.
  65996. *
  65997. * @method Phaser.FlexGrid#createFullLayer
  65998. * @param {array} [children] - An array of children that are used to populate the FlexLayer.
  65999. * @return {Phaser.FlexLayer} The Layer object.
  66000. */
  66001. createFullLayer: function (children) {
  66002. var layer = new Phaser.FlexLayer(this, this.positionFull, this.boundsFull, this.scaleFluid);
  66003. this.game.world.add(layer);
  66004. this.layers.push(layer);
  66005. if (typeof children !== 'undefined')
  66006. {
  66007. layer.addMultiple(children);
  66008. }
  66009. return layer;
  66010. },
  66011. /**
  66012. * A fixed layer is centered on the game and is the size of the required dimensions and is never scaled.
  66013. *
  66014. * @method Phaser.FlexGrid#createFixedLayer
  66015. * @param {PIXI.DisplayObject[]} [children] - An array of children that are used to populate the FlexLayer.
  66016. * @return {Phaser.FlexLayer} The Layer object.
  66017. */
  66018. createFixedLayer: function (children) {
  66019. var layer = new Phaser.FlexLayer(this, this.positionNone, this.boundsNone, this.scaleNone);
  66020. this.game.world.add(layer);
  66021. this.layers.push(layer);
  66022. if (typeof children !== 'undefined')
  66023. {
  66024. layer.addMultiple(children);
  66025. }
  66026. return layer;
  66027. },
  66028. /**
  66029. * Resets the layer children references
  66030. *
  66031. * @method Phaser.FlexGrid#reset
  66032. */
  66033. reset: function () {
  66034. var i = this.layers.length;
  66035. while (i--)
  66036. {
  66037. if (!this.layers[i].persist)
  66038. {
  66039. // Remove references to this class
  66040. this.layers[i].position = null;
  66041. this.layers[i].scale = null;
  66042. this.layers.slice(i, 1);
  66043. }
  66044. }
  66045. },
  66046. /**
  66047. * Called when the game container changes dimensions.
  66048. *
  66049. * @method Phaser.FlexGrid#onResize
  66050. * @param {number} width - The new width of the game container.
  66051. * @param {number} height - The new height of the game container.
  66052. */
  66053. onResize: function (width, height) {
  66054. this.ratioH = width / height;
  66055. this.ratioV = height / width;
  66056. this.refresh(width, height);
  66057. },
  66058. /**
  66059. * Updates all internal vars such as the bounds and scale values.
  66060. *
  66061. * @method Phaser.FlexGrid#refresh
  66062. */
  66063. refresh: function () {
  66064. this.multiplier = Math.min((this.manager.height / this.height), (this.manager.width / this.width));
  66065. this.boundsFluid.width = Math.round(this.width * this.multiplier);
  66066. this.boundsFluid.height = Math.round(this.height * this.multiplier);
  66067. this.scaleFluid.set(this.boundsFluid.width / this.width, this.boundsFluid.height / this.height);
  66068. this.scaleFluidInversed.set(this.width / this.boundsFluid.width, this.height / this.boundsFluid.height);
  66069. this.scaleFull.set(this.boundsFull.width / this.width, this.boundsFull.height / this.height);
  66070. this.boundsFull.width = Math.round(this.manager.width * this.scaleFluidInversed.x);
  66071. this.boundsFull.height = Math.round(this.manager.height * this.scaleFluidInversed.y);
  66072. this.boundsFluid.centerOn(this.manager.bounds.centerX, this.manager.bounds.centerY);
  66073. this.boundsNone.centerOn(this.manager.bounds.centerX, this.manager.bounds.centerY);
  66074. this.positionFluid.set(this.boundsFluid.x, this.boundsFluid.y);
  66075. this.positionNone.set(this.boundsNone.x, this.boundsNone.y);
  66076. },
  66077. /**
  66078. * Fits a sprites width to the bounds.
  66079. *
  66080. * @method Phaser.FlexGrid#fitSprite
  66081. * @param {Phaser.Sprite} sprite - The Sprite to fit.
  66082. */
  66083. fitSprite: function (sprite) {
  66084. this.manager.scaleSprite(sprite);
  66085. sprite.x = this.manager.bounds.centerX;
  66086. sprite.y = this.manager.bounds.centerY;
  66087. },
  66088. /**
  66089. * Call in the render function to output the bounds rects.
  66090. *
  66091. * @method Phaser.FlexGrid#debug
  66092. */
  66093. debug: function () {
  66094. // for (var i = 0; i < this.layers.length; i++)
  66095. // {
  66096. // this.layers[i].debug();
  66097. // }
  66098. // this.game.debug.text(this.boundsFull.width + ' x ' + this.boundsFull.height, this.boundsFull.x + 4, this.boundsFull.y + 16);
  66099. // this.game.debug.geom(this.boundsFull, 'rgba(0,0,255,0.9', false);
  66100. this.game.debug.text(this.boundsFluid.width + ' x ' + this.boundsFluid.height, this.boundsFluid.x + 4, this.boundsFluid.y + 16);
  66101. this.game.debug.geom(this.boundsFluid, 'rgba(255,0,0,0.9', false);
  66102. // this.game.debug.text(this.boundsNone.width + ' x ' + this.boundsNone.height, this.boundsNone.x + 4, this.boundsNone.y + 16);
  66103. // this.game.debug.geom(this.boundsNone, 'rgba(0,255,0,0.9', false);
  66104. // this.game.debug.text(this.boundsCustom.width + ' x ' + this.boundsCustom.height, this.boundsCustom.x + 4, this.boundsCustom.y + 16);
  66105. // this.game.debug.geom(this.boundsCustom, 'rgba(255,255,0,0.9', false);
  66106. }
  66107. };
  66108. Phaser.FlexGrid.prototype.constructor = Phaser.FlexGrid;
  66109. /**
  66110. * @author Richard Davey <rich@photonstorm.com>
  66111. * @copyright 2016 Photon Storm Ltd.
  66112. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  66113. */
  66114. /**
  66115. * WARNING: This is an EXPERIMENTAL class. The API will change significantly in the coming versions and is incomplete.
  66116. * Please try to avoid using in production games with a long time to build.
  66117. * This is also why the documentation is incomplete.
  66118. *
  66119. * A responsive grid layer.
  66120. *
  66121. * @class Phaser.FlexLayer
  66122. * @extends Phaser.Group
  66123. * @constructor
  66124. * @param {Phaser.FlexGrid} manager - The FlexGrid that owns this FlexLayer.
  66125. * @param {Phaser.Point} position - A reference to the Point object used for positioning.
  66126. * @param {Phaser.Rectangle} bounds - A reference to the Rectangle used for the layer bounds.
  66127. * @param {Phaser.Point} scale - A reference to the Point object used for layer scaling.
  66128. */
  66129. Phaser.FlexLayer = function (manager, position, bounds, scale) {
  66130. Phaser.Group.call(this, manager.game, null, '__flexLayer' + manager.game.rnd.uuid(), false);
  66131. /**
  66132. * @property {Phaser.ScaleManager} scale - A reference to the ScaleManager.
  66133. */
  66134. this.manager = manager.manager;
  66135. /**
  66136. * @property {Phaser.FlexGrid} grid - A reference to the FlexGrid that owns this layer.
  66137. */
  66138. this.grid = manager;
  66139. /**
  66140. * Should the FlexLayer remain through a State swap?
  66141. *
  66142. * @type {boolean}
  66143. */
  66144. this.persist = false;
  66145. /**
  66146. * @property {Phaser.Point} position
  66147. */
  66148. this.position = position;
  66149. /**
  66150. * @property {Phaser.Rectangle} bounds
  66151. */
  66152. this.bounds = bounds;
  66153. /**
  66154. * @property {Phaser.Point} scale
  66155. */
  66156. this.scale = scale;
  66157. /**
  66158. * @property {Phaser.Point} topLeft
  66159. */
  66160. this.topLeft = bounds.topLeft;
  66161. /**
  66162. * @property {Phaser.Point} topMiddle
  66163. */
  66164. this.topMiddle = new Phaser.Point(bounds.halfWidth, 0);
  66165. /**
  66166. * @property {Phaser.Point} topRight
  66167. */
  66168. this.topRight = bounds.topRight;
  66169. /**
  66170. * @property {Phaser.Point} bottomLeft
  66171. */
  66172. this.bottomLeft = bounds.bottomLeft;
  66173. /**
  66174. * @property {Phaser.Point} bottomMiddle
  66175. */
  66176. this.bottomMiddle = new Phaser.Point(bounds.halfWidth, bounds.bottom);
  66177. /**
  66178. * @property {Phaser.Point} bottomRight
  66179. */
  66180. this.bottomRight = bounds.bottomRight;
  66181. };
  66182. Phaser.FlexLayer.prototype = Object.create(Phaser.Group.prototype);
  66183. Phaser.FlexLayer.prototype.constructor = Phaser.FlexLayer;
  66184. /**
  66185. * Resize.
  66186. *
  66187. * @method Phaser.FlexLayer#resize
  66188. */
  66189. Phaser.FlexLayer.prototype.resize = function () {
  66190. };
  66191. /**
  66192. * Debug.
  66193. *
  66194. * @method Phaser.FlexLayer#debug
  66195. */
  66196. Phaser.FlexLayer.prototype.debug = function () {
  66197. this.game.debug.text(this.bounds.width + ' x ' + this.bounds.height, this.bounds.x + 4, this.bounds.y + 16);
  66198. this.game.debug.geom(this.bounds, 'rgba(0,0,255,0.9', false);
  66199. this.game.debug.geom(this.topLeft, 'rgba(255,255,255,0.9');
  66200. this.game.debug.geom(this.topMiddle, 'rgba(255,255,255,0.9');
  66201. this.game.debug.geom(this.topRight, 'rgba(255,255,255,0.9');
  66202. };
  66203. /**
  66204. * @author Richard Davey <rich@photonstorm.com>
  66205. * @copyright 2016 Photon Storm Ltd.
  66206. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  66207. */
  66208. /**
  66209. * The Phaser.Color class is a set of static methods that assist in color manipulation and conversion.
  66210. *
  66211. * @class Phaser.Color
  66212. */
  66213. Phaser.Color = {
  66214. /**
  66215. * Packs the r, g, b, a components into a single integer, for use with Int32Array.
  66216. * If device is little endian then ABGR order is used. Otherwise RGBA order is used.
  66217. *
  66218. * @author Matt DesLauriers (@mattdesl)
  66219. * @method Phaser.Color.packPixel
  66220. * @static
  66221. * @param {number} r - The red color component, in the range 0 - 255.
  66222. * @param {number} g - The green color component, in the range 0 - 255.
  66223. * @param {number} b - The blue color component, in the range 0 - 255.
  66224. * @param {number} a - The alpha color component, in the range 0 - 255.
  66225. * @return {number} The packed color as uint32
  66226. */
  66227. packPixel: function (r, g, b, a) {
  66228. if (Phaser.Device.LITTLE_ENDIAN)
  66229. {
  66230. return ( (a << 24) | (b << 16) | (g << 8) | r ) >>> 0;
  66231. }
  66232. else
  66233. {
  66234. return ( (r << 24) | (g << 16) | (b << 8) | a ) >>> 0;
  66235. }
  66236. },
  66237. /**
  66238. * Unpacks the r, g, b, a components into the specified color object, or a new
  66239. * object, for use with Int32Array. If little endian, then ABGR order is used when
  66240. * unpacking, otherwise, RGBA order is used. The resulting color object has the
  66241. * `r, g, b, a` properties which are unrelated to endianness.
  66242. *
  66243. * Note that the integer is assumed to be packed in the correct endianness. On little-endian
  66244. * the format is 0xAABBGGRR and on big-endian the format is 0xRRGGBBAA. If you want a
  66245. * endian-independent method, use fromRGBA(rgba) and toRGBA(r, g, b, a).
  66246. *
  66247. * @author Matt DesLauriers (@mattdesl)
  66248. * @method Phaser.Color.unpackPixel
  66249. * @static
  66250. * @param {number} rgba - The integer, packed in endian order by packPixel.
  66251. * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created.
  66252. * @param {boolean} [hsl=false] - Also convert the rgb values into hsl?
  66253. * @param {boolean} [hsv=false] - Also convert the rgb values into hsv?
  66254. * @return {object} An object with the red, green and blue values set in the r, g and b properties.
  66255. */
  66256. unpackPixel: function (rgba, out, hsl, hsv) {
  66257. if (out === undefined || out === null) { out = Phaser.Color.createColor(); }
  66258. if (hsl === undefined || hsl === null) { hsl = false; }
  66259. if (hsv === undefined || hsv === null) { hsv = false; }
  66260. if (Phaser.Device.LITTLE_ENDIAN)
  66261. {
  66262. out.a = ((rgba & 0xff000000) >>> 24);
  66263. out.b = ((rgba & 0x00ff0000) >>> 16);
  66264. out.g = ((rgba & 0x0000ff00) >>> 8);
  66265. out.r = ((rgba & 0x000000ff));
  66266. }
  66267. else
  66268. {
  66269. out.r = ((rgba & 0xff000000) >>> 24);
  66270. out.g = ((rgba & 0x00ff0000) >>> 16);
  66271. out.b = ((rgba & 0x0000ff00) >>> 8);
  66272. out.a = ((rgba & 0x000000ff));
  66273. }
  66274. out.color = rgba;
  66275. out.rgba = 'rgba(' + out.r + ',' + out.g + ',' + out.b + ',' + (out.a / 255) + ')';
  66276. if (hsl)
  66277. {
  66278. Phaser.Color.RGBtoHSL(out.r, out.g, out.b, out);
  66279. }
  66280. if (hsv)
  66281. {
  66282. Phaser.Color.RGBtoHSV(out.r, out.g, out.b, out);
  66283. }
  66284. return out;
  66285. },
  66286. /**
  66287. * A utility to convert an integer in 0xRRGGBBAA format to a color object.
  66288. * This does not rely on endianness.
  66289. *
  66290. * @author Matt DesLauriers (@mattdesl)
  66291. * @method Phaser.Color.fromRGBA
  66292. * @static
  66293. * @param {number} rgba - An RGBA hex
  66294. * @param {object} [out] - The object to use, optional.
  66295. * @return {object} A color object.
  66296. */
  66297. fromRGBA: function (rgba, out) {
  66298. if (!out)
  66299. {
  66300. out = Phaser.Color.createColor();
  66301. }
  66302. out.r = ((rgba & 0xff000000) >>> 24);
  66303. out.g = ((rgba & 0x00ff0000) >>> 16);
  66304. out.b = ((rgba & 0x0000ff00) >>> 8);
  66305. out.a = ((rgba & 0x000000ff));
  66306. out.rgba = 'rgba(' + out.r + ',' + out.g + ',' + out.b + ',' + out.a + ')';
  66307. return out;
  66308. },
  66309. /**
  66310. * A utility to convert RGBA components to a 32 bit integer in RRGGBBAA format.
  66311. *
  66312. * @author Matt DesLauriers (@mattdesl)
  66313. * @method Phaser.Color.toRGBA
  66314. * @static
  66315. * @param {number} r - The red color component, in the range 0 - 255.
  66316. * @param {number} g - The green color component, in the range 0 - 255.
  66317. * @param {number} b - The blue color component, in the range 0 - 255.
  66318. * @param {number} a - The alpha color component, in the range 0 - 255.
  66319. * @return {number} A RGBA-packed 32 bit integer
  66320. */
  66321. toRGBA: function (r, g, b, a) {
  66322. return (r << 24) | (g << 16) | (b << 8) | a;
  66323. },
  66324. /**
  66325. * Converts an RGB color value to HSL (hue, saturation and lightness).
  66326. * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space.
  66327. * Assumes RGB values are contained in the set [0, 255] and returns h, s and l in the set [0, 1].
  66328. * Based on code by Michael Jackson (https://github.com/mjijackson)
  66329. *
  66330. * @method Phaser.Color.RGBtoHSL
  66331. * @static
  66332. * @param {number} r - The red color component, in the range 0 - 255.
  66333. * @param {number} g - The green color component, in the range 0 - 255.
  66334. * @param {number} b - The blue color component, in the range 0 - 255.
  66335. * @param {object} [out] - An object into which 3 properties will be created, h, s and l. If not provided a new object will be created.
  66336. * @return {object} An object with the hue, saturation and lightness values set in the h, s and l properties.
  66337. */
  66338. RGBtoHSL: function (r, g, b, out) {
  66339. if (!out)
  66340. {
  66341. out = Phaser.Color.createColor(r, g, b, 1);
  66342. }
  66343. r /= 255;
  66344. g /= 255;
  66345. b /= 255;
  66346. var min = Math.min(r, g, b);
  66347. var max = Math.max(r, g, b);
  66348. // achromatic by default
  66349. out.h = 0;
  66350. out.s = 0;
  66351. out.l = (max + min) / 2;
  66352. if (max !== min)
  66353. {
  66354. var d = max - min;
  66355. out.s = out.l > 0.5 ? d / (2 - max - min) : d / (max + min);
  66356. if (max === r)
  66357. {
  66358. out.h = (g - b) / d + (g < b ? 6 : 0);
  66359. }
  66360. else if (max === g)
  66361. {
  66362. out.h = (b - r) / d + 2;
  66363. }
  66364. else if (max === b)
  66365. {
  66366. out.h = (r - g) / d + 4;
  66367. }
  66368. out.h /= 6;
  66369. }
  66370. return out;
  66371. },
  66372. /**
  66373. * Converts an HSL (hue, saturation and lightness) color value to RGB.
  66374. * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space.
  66375. * Assumes HSL values are contained in the set [0, 1] and returns r, g and b values in the set [0, 255].
  66376. * Based on code by Michael Jackson (https://github.com/mjijackson)
  66377. *
  66378. * @method Phaser.Color.HSLtoRGB
  66379. * @static
  66380. * @param {number} h - The hue, in the range 0 - 1.
  66381. * @param {number} s - The saturation, in the range 0 - 1.
  66382. * @param {number} l - The lightness, in the range 0 - 1.
  66383. * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created.
  66384. * @return {object} An object with the red, green and blue values set in the r, g and b properties.
  66385. */
  66386. HSLtoRGB: function (h, s, l, out) {
  66387. if (!out)
  66388. {
  66389. out = Phaser.Color.createColor(l, l, l);
  66390. }
  66391. else
  66392. {
  66393. // achromatic by default
  66394. out.r = l;
  66395. out.g = l;
  66396. out.b = l;
  66397. }
  66398. if (s !== 0)
  66399. {
  66400. var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
  66401. var p = 2 * l - q;
  66402. out.r = Phaser.Color.hueToColor(p, q, h + 1 / 3);
  66403. out.g = Phaser.Color.hueToColor(p, q, h);
  66404. out.b = Phaser.Color.hueToColor(p, q, h - 1 / 3);
  66405. }
  66406. // out.r = (out.r * 255 | 0);
  66407. // out.g = (out.g * 255 | 0);
  66408. // out.b = (out.b * 255 | 0);
  66409. out.r = Math.floor((out.r * 255 | 0));
  66410. out.g = Math.floor((out.g * 255 | 0));
  66411. out.b = Math.floor((out.b * 255 | 0));
  66412. Phaser.Color.updateColor(out);
  66413. return out;
  66414. },
  66415. /**
  66416. * Converts an RGB color value to HSV (hue, saturation and value).
  66417. * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space.
  66418. * Assumes RGB values are contained in the set [0, 255] and returns h, s and v in the set [0, 1].
  66419. * Based on code by Michael Jackson (https://github.com/mjijackson)
  66420. *
  66421. * @method Phaser.Color.RGBtoHSV
  66422. * @static
  66423. * @param {number} r - The red color component, in the range 0 - 255.
  66424. * @param {number} g - The green color component, in the range 0 - 255.
  66425. * @param {number} b - The blue color component, in the range 0 - 255.
  66426. * @param {object} [out] - An object into which 3 properties will be created, h, s and v. If not provided a new object will be created.
  66427. * @return {object} An object with the hue, saturation and value set in the h, s and v properties.
  66428. */
  66429. RGBtoHSV: function (r, g, b, out) {
  66430. if (!out)
  66431. {
  66432. out = Phaser.Color.createColor(r, g, b, 255);
  66433. }
  66434. r /= 255;
  66435. g /= 255;
  66436. b /= 255;
  66437. var min = Math.min(r, g, b);
  66438. var max = Math.max(r, g, b);
  66439. var d = max - min;
  66440. // achromatic by default
  66441. out.h = 0;
  66442. out.s = max === 0 ? 0 : d / max;
  66443. out.v = max;
  66444. if (max !== min)
  66445. {
  66446. if (max === r)
  66447. {
  66448. out.h = (g - b) / d + (g < b ? 6 : 0);
  66449. }
  66450. else if (max === g)
  66451. {
  66452. out.h = (b - r) / d + 2;
  66453. }
  66454. else if (max === b)
  66455. {
  66456. out.h = (r - g) / d + 4;
  66457. }
  66458. out.h /= 6;
  66459. }
  66460. return out;
  66461. },
  66462. /**
  66463. * Converts an HSV (hue, saturation and value) color value to RGB.
  66464. * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space.
  66465. * Assumes HSV values are contained in the set [0, 1] and returns r, g and b values in the set [0, 255].
  66466. * Based on code by Michael Jackson (https://github.com/mjijackson)
  66467. *
  66468. * @method Phaser.Color.HSVtoRGB
  66469. * @static
  66470. * @param {number} h - The hue, in the range 0 - 1.
  66471. * @param {number} s - The saturation, in the range 0 - 1.
  66472. * @param {number} v - The value, in the range 0 - 1.
  66473. * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created.
  66474. * @return {object} An object with the red, green and blue values set in the r, g and b properties.
  66475. */
  66476. HSVtoRGB: function (h, s, v, out) {
  66477. if (out === undefined) { out = Phaser.Color.createColor(0, 0, 0, 1, h, s, 0, v); }
  66478. var r, g, b;
  66479. var i = Math.floor(h * 6);
  66480. var f = h * 6 - i;
  66481. var p = v * (1 - s);
  66482. var q = v * (1 - f * s);
  66483. var t = v * (1 - (1 - f) * s);
  66484. switch (i % 6)
  66485. {
  66486. case 0:
  66487. r = v;
  66488. g = t;
  66489. b = p;
  66490. break;
  66491. case 1:
  66492. r = q;
  66493. g = v;
  66494. b = p;
  66495. break;
  66496. case 2:
  66497. r = p;
  66498. g = v;
  66499. b = t;
  66500. break;
  66501. case 3:
  66502. r = p;
  66503. g = q;
  66504. b = v;
  66505. break;
  66506. case 4:
  66507. r = t;
  66508. g = p;
  66509. b = v;
  66510. break;
  66511. case 5:
  66512. r = v;
  66513. g = p;
  66514. b = q;
  66515. break;
  66516. }
  66517. out.r = Math.floor(r * 255);
  66518. out.g = Math.floor(g * 255);
  66519. out.b = Math.floor(b * 255);
  66520. Phaser.Color.updateColor(out);
  66521. return out;
  66522. },
  66523. /**
  66524. * Converts a hue to an RGB color.
  66525. * Based on code by Michael Jackson (https://github.com/mjijackson)
  66526. *
  66527. * @method Phaser.Color.hueToColor
  66528. * @static
  66529. * @param {number} p
  66530. * @param {number} q
  66531. * @param {number} t
  66532. * @return {number} The color component value.
  66533. */
  66534. hueToColor: function (p, q, t) {
  66535. if (t < 0)
  66536. {
  66537. t += 1;
  66538. }
  66539. if (t > 1)
  66540. {
  66541. t -= 1;
  66542. }
  66543. if (t < 1 / 6)
  66544. {
  66545. return p + (q - p) * 6 * t;
  66546. }
  66547. if (t < 1 / 2)
  66548. {
  66549. return q;
  66550. }
  66551. if (t < 2 / 3)
  66552. {
  66553. return p + (q - p) * (2 / 3 - t) * 6;
  66554. }
  66555. return p;
  66556. },
  66557. /**
  66558. * A utility function to create a lightweight 'color' object with the default components.
  66559. * Any components that are not specified will default to zero.
  66560. *
  66561. * This is useful when you want to use a shared color object for the getPixel and getPixelAt methods.
  66562. *
  66563. * @author Matt DesLauriers (@mattdesl)
  66564. * @method Phaser.Color.createColor
  66565. * @static
  66566. * @param {number} [r=0] - The red color component, in the range 0 - 255.
  66567. * @param {number} [g=0] - The green color component, in the range 0 - 255.
  66568. * @param {number} [b=0] - The blue color component, in the range 0 - 255.
  66569. * @param {number} [a=1] - The alpha color component, in the range 0 - 1.
  66570. * @param {number} [h=0] - The hue, in the range 0 - 1.
  66571. * @param {number} [s=0] - The saturation, in the range 0 - 1.
  66572. * @param {number} [l=0] - The lightness, in the range 0 - 1.
  66573. * @param {number} [v=0] - The value, in the range 0 - 1.
  66574. * @return {object} The resulting object with r, g, b, a properties and h, s, l and v.
  66575. */
  66576. createColor: function (r, g, b, a, h, s, l, v) {
  66577. var out = { r: r || 0, g: g || 0, b: b || 0, a: a || 1, h: h || 0, s: s || 0, l: l || 0, v: v || 0, color: 0, color32: 0, rgba: '' };
  66578. return Phaser.Color.updateColor(out);
  66579. },
  66580. /**
  66581. * Takes a color object and updates the rgba, color and color32 properties.
  66582. *
  66583. * @method Phaser.Color.updateColor
  66584. * @static
  66585. * @param {object} out - The color object to update.
  66586. * @returns {number} A native color value integer (format: 0xAARRGGBB).
  66587. */
  66588. updateColor: function (out) {
  66589. out.rgba = 'rgba(' + out.r.toString() + ',' + out.g.toString() + ',' + out.b.toString() + ',' + out.a.toString() + ')';
  66590. out.color = Phaser.Color.getColor(out.r, out.g, out.b);
  66591. out.color32 = Phaser.Color.getColor32(out.a * 255, out.r, out.g, out.b);
  66592. return out;
  66593. },
  66594. /**
  66595. * Given an alpha and 3 color values this will return an integer representation of it.
  66596. *
  66597. * @method Phaser.Color.getColor32
  66598. * @static
  66599. * @param {number} a - The alpha color component, in the range 0 - 255.
  66600. * @param {number} r - The red color component, in the range 0 - 255.
  66601. * @param {number} g - The green color component, in the range 0 - 255.
  66602. * @param {number} b - The blue color component, in the range 0 - 255.
  66603. * @returns {number} A native color value integer (format: 0xAARRGGBB).
  66604. */
  66605. getColor32: function (a, r, g, b) {
  66606. return a << 24 | r << 16 | g << 8 | b;
  66607. },
  66608. /**
  66609. * Given 3 color values this will return an integer representation of it.
  66610. *
  66611. * @method Phaser.Color.getColor
  66612. * @static
  66613. * @param {number} r - The red color component, in the range 0 - 255.
  66614. * @param {number} g - The green color component, in the range 0 - 255.
  66615. * @param {number} b - The blue color component, in the range 0 - 255.
  66616. * @returns {number} A native color value integer (format: 0xRRGGBB).
  66617. */
  66618. getColor: function (r, g, b) {
  66619. return r << 16 | g << 8 | b;
  66620. },
  66621. /**
  66622. * Converts the given color values into a string.
  66623. * If prefix was '#' it will be in the format `#RRGGBB` otherwise `0xAARRGGBB`.
  66624. *
  66625. * @method Phaser.Color.RGBtoString
  66626. * @static
  66627. * @param {number} r - The red color component, in the range 0 - 255.
  66628. * @param {number} g - The green color component, in the range 0 - 255.
  66629. * @param {number} b - The blue color component, in the range 0 - 255.
  66630. * @param {number} [a=255] - The alpha color component, in the range 0 - 255.
  66631. * @param {string} [prefix='#'] - The prefix used in the return string. If '#' it will return `#RRGGBB`, else `0xAARRGGBB`.
  66632. * @return {string} A string containing the color values. If prefix was '#' it will be in the format `#RRGGBB` otherwise `0xAARRGGBB`.
  66633. */
  66634. RGBtoString: function (r, g, b, a, prefix) {
  66635. if (a === undefined) { a = 255; }
  66636. if (prefix === undefined) { prefix = '#'; }
  66637. if (prefix === '#')
  66638. {
  66639. return '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
  66640. }
  66641. else
  66642. {
  66643. return '0x' + Phaser.Color.componentToHex(a) + Phaser.Color.componentToHex(r) + Phaser.Color.componentToHex(g) + Phaser.Color.componentToHex(b);
  66644. }
  66645. },
  66646. /**
  66647. * Converts a hex string into an integer color value.
  66648. *
  66649. * @method Phaser.Color.hexToRGB
  66650. * @static
  66651. * @param {string} hex - The hex string to convert. Can be in the short-hand format `#03f` or `#0033ff`.
  66652. * @return {number} The rgb color value in the format 0xAARRGGBB.
  66653. */
  66654. hexToRGB: function (hex) {
  66655. var rgb = Phaser.Color.hexToColor(hex);
  66656. if (rgb)
  66657. {
  66658. return Phaser.Color.getColor32(rgb.a, rgb.r, rgb.g, rgb.b);
  66659. }
  66660. },
  66661. /**
  66662. * Converts a hex string into a Phaser Color object.
  66663. *
  66664. * The hex string can supplied as `'#0033ff'` or the short-hand format of `'#03f'`; it can begin with an optional "#" or "0x", or be unprefixed.
  66665. *
  66666. * An alpha channel is _not_ supported.
  66667. *
  66668. * @method Phaser.Color.hexToColor
  66669. * @static
  66670. * @param {string} hex - The color string in a hex format.
  66671. * @param {object} [out] - An object into which 3 properties will be created or set: r, g and b. If not provided a new object will be created.
  66672. * @return {object} An object with the red, green and blue values set in the r, g and b properties.
  66673. */
  66674. hexToColor: function (hex, out) {
  66675. // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
  66676. hex = hex.replace(/^(?:#|0x)?([a-f\d])([a-f\d])([a-f\d])$/i, function(m, r, g, b) {
  66677. return r + r + g + g + b + b;
  66678. });
  66679. var result = /^(?:#|0x)?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  66680. if (result)
  66681. {
  66682. var r = parseInt(result[1], 16);
  66683. var g = parseInt(result[2], 16);
  66684. var b = parseInt(result[3], 16);
  66685. if (!out)
  66686. {
  66687. out = Phaser.Color.createColor(r, g, b);
  66688. }
  66689. else
  66690. {
  66691. out.r = r;
  66692. out.g = g;
  66693. out.b = b;
  66694. }
  66695. }
  66696. return out;
  66697. },
  66698. /**
  66699. * Converts a CSS 'web' string into a Phaser Color object.
  66700. *
  66701. * The web string can be in the format `'rgb(r,g,b)'` or `'rgba(r,g,b,a)'` where r/g/b are in the range [0..255] and a is in the range [0..1].
  66702. *
  66703. * @method Phaser.Color.webToColor
  66704. * @static
  66705. * @param {string} web - The color string in CSS 'web' format.
  66706. * @param {object} [out] - An object into which 4 properties will be created: r, g, b and a. If not provided a new object will be created.
  66707. * @return {object} An object with the red, green, blue and alpha values set in the r, g, b and a properties.
  66708. */
  66709. webToColor: function (web, out) {
  66710. if (!out)
  66711. {
  66712. out = Phaser.Color.createColor();
  66713. }
  66714. var result = /^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+(?:\.\d+)?))?\s*\)$/.exec(web);
  66715. if (result)
  66716. {
  66717. out.r = parseInt(result[1], 10);
  66718. out.g = parseInt(result[2], 10);
  66719. out.b = parseInt(result[3], 10);
  66720. out.a = result[4] !== undefined ? parseFloat(result[4]) : 1;
  66721. Phaser.Color.updateColor(out);
  66722. }
  66723. return out;
  66724. },
  66725. /**
  66726. * Converts a value - a "hex" string, a "CSS 'web' string", or a number - into red, green, blue, and alpha components.
  66727. *
  66728. * The value can be a string (see `hexToColor` and `webToColor` for the supported formats) or a packed integer (see `getRGB`).
  66729. *
  66730. * An alpha channel is _not_ supported when specifying a hex string.
  66731. *
  66732. * @method Phaser.Color.valueToColor
  66733. * @static
  66734. * @param {string|number} value - The color expressed as a recognized string format or a packed integer.
  66735. * @param {object} [out] - The object to use for the output. If not provided a new object will be created.
  66736. * @return {object} The (`out`) object with the red, green, blue, and alpha values set as the r/g/b/a properties.
  66737. */
  66738. valueToColor: function (value, out) {
  66739. // The behavior is not consistent between hexToColor/webToColor on invalid input.
  66740. // This unifies both by returning a new object, but returning null may be better.
  66741. if (!out)
  66742. {
  66743. out = Phaser.Color.createColor();
  66744. }
  66745. if (typeof value === 'string')
  66746. {
  66747. if (value.indexOf('rgb') === 0)
  66748. {
  66749. return Phaser.Color.webToColor(value, out);
  66750. }
  66751. else
  66752. {
  66753. // `hexToColor` does not support alpha; match `createColor`.
  66754. out.a = 1;
  66755. return Phaser.Color.hexToColor(value, out);
  66756. }
  66757. }
  66758. else if (typeof value === 'number')
  66759. {
  66760. // `getRGB` does not take optional object to modify;
  66761. // alpha is also adjusted to match `createColor`.
  66762. var tempColor = Phaser.Color.getRGB(value);
  66763. out.r = tempColor.r;
  66764. out.g = tempColor.g;
  66765. out.b = tempColor.b;
  66766. out.a = tempColor.a / 255;
  66767. return out;
  66768. }
  66769. else
  66770. {
  66771. return out;
  66772. }
  66773. },
  66774. /**
  66775. * Return a string containing a hex representation of the given color component.
  66776. *
  66777. * @method Phaser.Color.componentToHex
  66778. * @static
  66779. * @param {number} color - The color channel to get the hex value for, must be a value between 0 and 255.
  66780. * @returns {string} A string of length 2 characters, i.e. 255 = ff, 100 = 64.
  66781. */
  66782. componentToHex: function (color) {
  66783. var hex = color.toString(16);
  66784. return hex.length == 1 ? "0" + hex : hex;
  66785. },
  66786. /**
  66787. * Get HSV color wheel values in an array which will be 360 elements in size.
  66788. *
  66789. * @method Phaser.Color.HSVColorWheel
  66790. * @static
  66791. * @param {number} [s=1] - The saturation, in the range 0 - 1.
  66792. * @param {number} [v=1] - The value, in the range 0 - 1.
  66793. * @return {array} An array containing 360 elements corresponding to the HSV color wheel.
  66794. */
  66795. HSVColorWheel: function (s, v) {
  66796. if (s === undefined) { s = 1.0; }
  66797. if (v === undefined) { v = 1.0; }
  66798. var colors = [];
  66799. for (var c = 0; c <= 359; c++)
  66800. {
  66801. colors.push(Phaser.Color.HSVtoRGB(c / 359, s, v));
  66802. }
  66803. return colors;
  66804. },
  66805. /**
  66806. * Get HSL color wheel values in an array which will be 360 elements in size.
  66807. *
  66808. * @method Phaser.Color.HSLColorWheel
  66809. * @static
  66810. * @param {number} [s=0.5] - The saturation, in the range 0 - 1.
  66811. * @param {number} [l=0.5] - The lightness, in the range 0 - 1.
  66812. * @return {array} An array containing 360 elements corresponding to the HSL color wheel.
  66813. */
  66814. HSLColorWheel: function (s, l) {
  66815. if (s === undefined) { s = 0.5; }
  66816. if (l === undefined) { l = 0.5; }
  66817. var colors = [];
  66818. for (var c = 0; c <= 359; c++)
  66819. {
  66820. colors.push(Phaser.Color.HSLtoRGB(c / 359, s, l));
  66821. }
  66822. return colors;
  66823. },
  66824. /**
  66825. * Interpolates the two given colours based on the supplied step and currentStep properties.
  66826. *
  66827. * @method Phaser.Color.interpolateColor
  66828. * @static
  66829. * @param {number} color1 - The first color value.
  66830. * @param {number} color2 - The second color value.
  66831. * @param {number} steps - The number of steps to run the interpolation over.
  66832. * @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.
  66833. * @param {number} alpha - The alpha of the returned color.
  66834. * @returns {number} The interpolated color value.
  66835. */
  66836. interpolateColor: function (color1, color2, steps, currentStep, alpha) {
  66837. if (alpha === undefined) { alpha = 255; }
  66838. var src1 = Phaser.Color.getRGB(color1);
  66839. var src2 = Phaser.Color.getRGB(color2);
  66840. var r = (((src2.red - src1.red) * currentStep) / steps) + src1.red;
  66841. var g = (((src2.green - src1.green) * currentStep) / steps) + src1.green;
  66842. var b = (((src2.blue - src1.blue) * currentStep) / steps) + src1.blue;
  66843. return Phaser.Color.getColor32(alpha, r, g, b);
  66844. },
  66845. /**
  66846. * Interpolates the two given colours based on the supplied step and currentStep properties.
  66847. *
  66848. * @method Phaser.Color.interpolateColorWithRGB
  66849. * @static
  66850. * @param {number} color - The first color value.
  66851. * @param {number} r - The red color value, between 0 and 0xFF (255).
  66852. * @param {number} g - The green color value, between 0 and 0xFF (255).
  66853. * @param {number} b - The blue color value, between 0 and 0xFF (255).
  66854. * @param {number} steps - The number of steps to run the interpolation over.
  66855. * @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.
  66856. * @returns {number} The interpolated color value.
  66857. */
  66858. interpolateColorWithRGB: function (color, r, g, b, steps, currentStep) {
  66859. var src = Phaser.Color.getRGB(color);
  66860. var or = (((r - src.red) * currentStep) / steps) + src.red;
  66861. var og = (((g - src.green) * currentStep) / steps) + src.green;
  66862. var ob = (((b - src.blue) * currentStep) / steps) + src.blue;
  66863. return Phaser.Color.getColor(or, og, ob);
  66864. },
  66865. /**
  66866. * Interpolates the two given colours based on the supplied step and currentStep properties.
  66867. * @method Phaser.Color.interpolateRGB
  66868. * @static
  66869. * @param {number} r1 - The red color value, between 0 and 0xFF (255).
  66870. * @param {number} g1 - The green color value, between 0 and 0xFF (255).
  66871. * @param {number} b1 - The blue color value, between 0 and 0xFF (255).
  66872. * @param {number} r2 - The red color value, between 0 and 0xFF (255).
  66873. * @param {number} g2 - The green color value, between 0 and 0xFF (255).
  66874. * @param {number} b2 - The blue color value, between 0 and 0xFF (255).
  66875. * @param {number} steps - The number of steps to run the interpolation over.
  66876. * @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.
  66877. * @returns {number} The interpolated color value.
  66878. */
  66879. interpolateRGB: function (r1, g1, b1, r2, g2, b2, steps, currentStep) {
  66880. var r = (((r2 - r1) * currentStep) / steps) + r1;
  66881. var g = (((g2 - g1) * currentStep) / steps) + g1;
  66882. var b = (((b2 - b1) * currentStep) / steps) + b1;
  66883. return Phaser.Color.getColor(r, g, b);
  66884. },
  66885. /**
  66886. * Returns a random color value between black and white
  66887. * Set the min value to start each channel from the given offset.
  66888. * Set the max value to restrict the maximum color used per channel.
  66889. *
  66890. * @method Phaser.Color.getRandomColor
  66891. * @static
  66892. * @param {number} [min=0] - The lowest value to use for the color.
  66893. * @param {number} [max=255] - The highest value to use for the color.
  66894. * @param {number} [alpha=255] - The alpha value of the returning color (default 255 = fully opaque).
  66895. * @returns {number} 32-bit color value with alpha.
  66896. */
  66897. getRandomColor: function (min, max, alpha) {
  66898. if (min === undefined) { min = 0; }
  66899. if (max === undefined) { max = 255; }
  66900. if (alpha === undefined) { alpha = 255; }
  66901. // Sanity checks
  66902. if (max > 255 || min > max)
  66903. {
  66904. return Phaser.Color.getColor(255, 255, 255);
  66905. }
  66906. var red = min + Math.round(Math.random() * (max - min));
  66907. var green = min + Math.round(Math.random() * (max - min));
  66908. var blue = min + Math.round(Math.random() * (max - min));
  66909. return Phaser.Color.getColor32(alpha, red, green, blue);
  66910. },
  66911. /**
  66912. * Return the component parts of a color as an Object with the properties alpha, red, green, blue.
  66913. *
  66914. * Alpha will only be set if it exist in the given color (0xAARRGGBB)
  66915. *
  66916. * @method Phaser.Color.getRGB
  66917. * @static
  66918. * @param {number} color - Color in RGB (0xRRGGBB) or ARGB format (0xAARRGGBB).
  66919. * @returns {object} An Object with properties: alpha, red, green, blue (also r, g, b and a). Alpha will only be present if a color value > 16777215 was given.
  66920. */
  66921. getRGB: function (color) {
  66922. if (color > 16777215)
  66923. {
  66924. // The color value has an alpha component
  66925. return {
  66926. alpha: color >>> 24,
  66927. red: color >> 16 & 0xFF,
  66928. green: color >> 8 & 0xFF,
  66929. blue: color & 0xFF,
  66930. a: color >>> 24,
  66931. r: color >> 16 & 0xFF,
  66932. g: color >> 8 & 0xFF,
  66933. b: color & 0xFF
  66934. };
  66935. }
  66936. else
  66937. {
  66938. return {
  66939. alpha: 255,
  66940. red: color >> 16 & 0xFF,
  66941. green: color >> 8 & 0xFF,
  66942. blue: color & 0xFF,
  66943. a: 255,
  66944. r: color >> 16 & 0xFF,
  66945. g: color >> 8 & 0xFF,
  66946. b: color & 0xFF
  66947. };
  66948. }
  66949. },
  66950. /**
  66951. * Returns a CSS friendly string value from the given color.
  66952. *
  66953. * @method Phaser.Color.getWebRGB
  66954. * @static
  66955. * @param {number|Object} color - Color in RGB (0xRRGGBB), ARGB format (0xAARRGGBB) or an Object with r, g, b, a properties.
  66956. * @returns {string} A string in the format: 'rgba(r,g,b,a)'
  66957. */
  66958. getWebRGB: function (color) {
  66959. if (typeof color === 'object')
  66960. {
  66961. return 'rgba(' + color.r.toString() + ',' + color.g.toString() + ',' + color.b.toString() + ',' + (color.a / 255).toString() + ')';
  66962. }
  66963. else
  66964. {
  66965. var rgb = Phaser.Color.getRGB(color);
  66966. return 'rgba(' + rgb.r.toString() + ',' + rgb.g.toString() + ',' + rgb.b.toString() + ',' + (rgb.a / 255).toString() + ')';
  66967. }
  66968. },
  66969. /**
  66970. * Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component, as a value between 0 and 255.
  66971. *
  66972. * @method Phaser.Color.getAlpha
  66973. * @static
  66974. * @param {number} color - In the format 0xAARRGGBB.
  66975. * @returns {number} The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent)).
  66976. */
  66977. getAlpha: function (color) {
  66978. return color >>> 24;
  66979. },
  66980. /**
  66981. * Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component as a value between 0 and 1.
  66982. *
  66983. * @method Phaser.Color.getAlphaFloat
  66984. * @static
  66985. * @param {number} color - In the format 0xAARRGGBB.
  66986. * @returns {number} The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent)).
  66987. */
  66988. getAlphaFloat: function (color) {
  66989. return (color >>> 24) / 255;
  66990. },
  66991. /**
  66992. * Given a native color value (in the format 0xAARRGGBB) this will return the Red component, as a value between 0 and 255.
  66993. *
  66994. * @method Phaser.Color.getRed
  66995. * @static
  66996. * @param {number} color In the format 0xAARRGGBB.
  66997. * @returns {number} The Red component of the color, will be between 0 and 255 (0 being no color, 255 full Red).
  66998. */
  66999. getRed: function (color) {
  67000. return color >> 16 & 0xFF;
  67001. },
  67002. /**
  67003. * Given a native color value (in the format 0xAARRGGBB) this will return the Green component, as a value between 0 and 255.
  67004. *
  67005. * @method Phaser.Color.getGreen
  67006. * @static
  67007. * @param {number} color - In the format 0xAARRGGBB.
  67008. * @returns {number} The Green component of the color, will be between 0 and 255 (0 being no color, 255 full Green).
  67009. */
  67010. getGreen: function (color) {
  67011. return color >> 8 & 0xFF;
  67012. },
  67013. /**
  67014. * Given a native color value (in the format 0xAARRGGBB) this will return the Blue component, as a value between 0 and 255.
  67015. *
  67016. * @method Phaser.Color.getBlue
  67017. * @static
  67018. * @param {number} color - In the format 0xAARRGGBB.
  67019. * @returns {number} The Blue component of the color, will be between 0 and 255 (0 being no color, 255 full Blue).
  67020. */
  67021. getBlue: function (color) {
  67022. return color & 0xFF;
  67023. },
  67024. /**
  67025. * Blends the source color, ignoring the backdrop.
  67026. *
  67027. * @method Phaser.Color.blendNormal
  67028. * @static
  67029. * @param {integer} a - The source color to blend, in the range 1 to 255.
  67030. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  67031. * @returns {integer} The blended color value, in the range 1 to 255.
  67032. */
  67033. blendNormal: function (a) {
  67034. return a;
  67035. },
  67036. /**
  67037. * Selects the lighter of the backdrop and source colors.
  67038. *
  67039. * @method Phaser.Color.blendLighten
  67040. * @static
  67041. * @param {integer} a - The source color to blend, in the range 1 to 255.
  67042. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  67043. * @returns {integer} The blended color value, in the range 1 to 255.
  67044. */
  67045. blendLighten: function (a, b) {
  67046. return (b > a) ? b : a;
  67047. },
  67048. /**
  67049. * Selects the darker of the backdrop and source colors.
  67050. *
  67051. * @method Phaser.Color.blendDarken
  67052. * @static
  67053. * @param {integer} a - The source color to blend, in the range 1 to 255.
  67054. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  67055. * @returns {integer} The blended color value, in the range 1 to 255.
  67056. */
  67057. blendDarken: function (a, b) {
  67058. return (b > a) ? a : b;
  67059. },
  67060. /**
  67061. * Multiplies the backdrop and source color values.
  67062. * The result color is always at least as dark as either of the two constituent
  67063. * colors. Multiplying any color with black produces black;
  67064. * multiplying with white leaves the original color unchanged.
  67065. *
  67066. * @method Phaser.Color.blendMultiply
  67067. * @static
  67068. * @param {integer} a - The source color to blend, in the range 1 to 255.
  67069. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  67070. * @returns {integer} The blended color value, in the range 1 to 255.
  67071. */
  67072. blendMultiply: function (a, b) {
  67073. return (a * b) / 255;
  67074. },
  67075. /**
  67076. * Takes the average of the source and backdrop colors.
  67077. *
  67078. * @method Phaser.Color.blendAverage
  67079. * @static
  67080. * @param {integer} a - The source color to blend, in the range 1 to 255.
  67081. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  67082. * @returns {integer} The blended color value, in the range 1 to 255.
  67083. */
  67084. blendAverage: function (a, b) {
  67085. return (a + b) / 2;
  67086. },
  67087. /**
  67088. * Adds the source and backdrop colors together and returns the value, up to a maximum of 255.
  67089. *
  67090. * @method Phaser.Color.blendAdd
  67091. * @static
  67092. * @param {integer} a - The source color to blend, in the range 1 to 255.
  67093. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  67094. * @returns {integer} The blended color value, in the range 1 to 255.
  67095. */
  67096. blendAdd: function (a, b) {
  67097. return Math.min(255, a + b);
  67098. },
  67099. /**
  67100. * Combines the source and backdrop colors and returns their value minus 255.
  67101. *
  67102. * @method Phaser.Color.blendSubtract
  67103. * @static
  67104. * @param {integer} a - The source color to blend, in the range 1 to 255.
  67105. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  67106. * @returns {integer} The blended color value, in the range 1 to 255.
  67107. */
  67108. blendSubtract: function (a, b) {
  67109. return Math.max(0, a + b - 255);
  67110. },
  67111. /**
  67112. * Subtracts the darker of the two constituent colors from the lighter.
  67113. *
  67114. * Painting with white inverts the backdrop color; painting with black produces no change.
  67115. *
  67116. * @method Phaser.Color.blendDifference
  67117. * @static
  67118. * @param {integer} a - The source color to blend, in the range 1 to 255.
  67119. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  67120. * @returns {integer} The blended color value, in the range 1 to 255.
  67121. */
  67122. blendDifference: function (a, b) {
  67123. return Math.abs(a - b);
  67124. },
  67125. /**
  67126. * Negation blend mode.
  67127. *
  67128. * @method Phaser.Color.blendNegation
  67129. * @static
  67130. * @param {integer} a - The source color to blend, in the range 1 to 255.
  67131. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  67132. * @returns {integer} The blended color value, in the range 1 to 255.
  67133. */
  67134. blendNegation: function (a, b) {
  67135. return 255 - Math.abs(255 - a - b);
  67136. },
  67137. /**
  67138. * Multiplies the complements of the backdrop and source color values, then complements the result.
  67139. * The result color is always at least as light as either of the two constituent colors.
  67140. * Screening any color with white produces white; screening with black leaves the original color unchanged.
  67141. *
  67142. * @method Phaser.Color.blendScreen
  67143. * @static
  67144. * @param {integer} a - The source color to blend, in the range 1 to 255.
  67145. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  67146. * @returns {integer} The blended color value, in the range 1 to 255.
  67147. */
  67148. blendScreen: function (a, b) {
  67149. return 255 - (((255 - a) * (255 - b)) >> 8);
  67150. },
  67151. /**
  67152. * Produces an effect similar to that of the Difference mode, but lower in contrast.
  67153. * Painting with white inverts the backdrop color; painting with black produces no change.
  67154. *
  67155. * @method Phaser.Color.blendExclusion
  67156. * @static
  67157. * @param {integer} a - The source color to blend, in the range 1 to 255.
  67158. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  67159. * @returns {integer} The blended color value, in the range 1 to 255.
  67160. */
  67161. blendExclusion: function (a, b) {
  67162. return a + b - 2 * a * b / 255;
  67163. },
  67164. /**
  67165. * Multiplies or screens the colors, depending on the backdrop color.
  67166. * Source colors overlay the backdrop while preserving its highlights and shadows.
  67167. * The backdrop color is not replaced, but is mixed with the source color to reflect the lightness or darkness of the backdrop.
  67168. *
  67169. * @method Phaser.Color.blendOverlay
  67170. * @static
  67171. * @param {integer} a - The source color to blend, in the range 1 to 255.
  67172. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  67173. * @returns {integer} The blended color value, in the range 1 to 255.
  67174. */
  67175. blendOverlay: function (a, b) {
  67176. return b < 128 ? (2 * a * b / 255) : (255 - 2 * (255 - a) * (255 - b) / 255);
  67177. },
  67178. /**
  67179. * Darkens or lightens the colors, depending on the source color value.
  67180. *
  67181. * If the source color is lighter than 0.5, the backdrop is lightened, as if it were dodged;
  67182. * this is useful for adding highlights to a scene.
  67183. *
  67184. * If the source color is darker than 0.5, the backdrop is darkened, as if it were burned in.
  67185. * The degree of lightening or darkening is proportional to the difference between the source color and 0.5;
  67186. * if it is equal to 0.5, the backdrop is unchanged.
  67187. *
  67188. * Painting with pure black or white produces a distinctly darker or lighter area, but does not result in pure black or white.
  67189. * The effect is similar to shining a diffused spotlight on the backdrop.
  67190. *
  67191. * @method Phaser.Color.blendSoftLight
  67192. * @static
  67193. * @param {integer} a - The source color to blend, in the range 1 to 255.
  67194. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  67195. * @returns {integer} The blended color value, in the range 1 to 255.
  67196. */
  67197. blendSoftLight: function (a, b) {
  67198. return b < 128 ? (2 * ((a >> 1) + 64)) * (b / 255) : 255 - (2 * (255 - ((a >> 1) + 64)) * (255 - b) / 255);
  67199. },
  67200. /**
  67201. * Multiplies or screens the colors, depending on the source color value.
  67202. *
  67203. * If the source color is lighter than 0.5, the backdrop is lightened, as if it were screened;
  67204. * this is useful for adding highlights to a scene.
  67205. *
  67206. * If the source color is darker than 0.5, the backdrop is darkened, as if it were multiplied;
  67207. * this is useful for adding shadows to a scene.
  67208. *
  67209. * The degree of lightening or darkening is proportional to the difference between the source color and 0.5;
  67210. * if it is equal to 0.5, the backdrop is unchanged.
  67211. *
  67212. * Painting with pure black or white produces pure black or white. The effect is similar to shining a harsh spotlight on the backdrop.
  67213. *
  67214. * @method Phaser.Color.blendHardLight
  67215. * @static
  67216. * @param {integer} a - The source color to blend, in the range 1 to 255.
  67217. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  67218. * @returns {integer} The blended color value, in the range 1 to 255.
  67219. */
  67220. blendHardLight: function (a, b) {
  67221. return Phaser.Color.blendOverlay(b, a);
  67222. },
  67223. /**
  67224. * Brightens the backdrop color to reflect the source color.
  67225. * Painting with black produces no change.
  67226. *
  67227. * @method Phaser.Color.blendColorDodge
  67228. * @static
  67229. * @param {integer} a - The source color to blend, in the range 1 to 255.
  67230. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  67231. * @returns {integer} The blended color value, in the range 1 to 255.
  67232. */
  67233. blendColorDodge: function (a, b) {
  67234. return b === 255 ? b : Math.min(255, ((a << 8) / (255 - b)));
  67235. },
  67236. /**
  67237. * Darkens the backdrop color to reflect the source color.
  67238. * Painting with white produces no change.
  67239. *
  67240. * @method Phaser.Color.blendColorBurn
  67241. * @static
  67242. * @param {integer} a - The source color to blend, in the range 1 to 255.
  67243. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  67244. * @returns {integer} The blended color value, in the range 1 to 255.
  67245. */
  67246. blendColorBurn: function (a, b) {
  67247. return b === 0 ? b : Math.max(0, (255 - ((255 - a) << 8) / b));
  67248. },
  67249. /**
  67250. * An alias for blendAdd, it simply sums the values of the two colors.
  67251. *
  67252. * @method Phaser.Color.blendLinearDodge
  67253. * @static
  67254. * @param {integer} a - The source color to blend, in the range 1 to 255.
  67255. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  67256. * @returns {integer} The blended color value, in the range 1 to 255.
  67257. */
  67258. blendLinearDodge: function (a, b) {
  67259. return Phaser.Color.blendAdd(a, b);
  67260. },
  67261. /**
  67262. * An alias for blendSubtract, it simply sums the values of the two colors and subtracts 255.
  67263. *
  67264. * @method Phaser.Color.blendLinearBurn
  67265. * @static
  67266. * @param {integer} a - The source color to blend, in the range 1 to 255.
  67267. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  67268. * @returns {integer} The blended color value, in the range 1 to 255.
  67269. */
  67270. blendLinearBurn: function (a, b) {
  67271. return Phaser.Color.blendSubtract(a, b);
  67272. },
  67273. /**
  67274. * This blend mode combines Linear Dodge and Linear Burn (rescaled so that neutral colors become middle gray).
  67275. * Dodge applies to values of top layer lighter than middle gray, and burn to darker values.
  67276. * The calculation simplifies to the sum of bottom layer and twice the top layer, subtract 128. The contrast decreases.
  67277. *
  67278. * @method Phaser.Color.blendLinearLight
  67279. * @static
  67280. * @param {integer} a - The source color to blend, in the range 1 to 255.
  67281. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  67282. * @returns {integer} The blended color value, in the range 1 to 255.
  67283. */
  67284. blendLinearLight: function (a, b) {
  67285. return b < 128 ? Phaser.Color.blendLinearBurn(a, 2 * b) : Phaser.Color.blendLinearDodge(a, (2 * (b - 128)));
  67286. },
  67287. /**
  67288. * This blend mode combines Color Dodge and Color Burn (rescaled so that neutral colors become middle gray).
  67289. * Dodge applies when values in the top layer are lighter than middle gray, and burn to darker values.
  67290. * The middle gray is the neutral color. When color is lighter than this, this effectively moves the white point of the bottom
  67291. * layer down by twice the difference; when it is darker, the black point is moved up by twice the difference. The perceived contrast increases.
  67292. *
  67293. * @method Phaser.Color.blendVividLight
  67294. * @static
  67295. * @param {integer} a - The source color to blend, in the range 1 to 255.
  67296. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  67297. * @returns {integer} The blended color value, in the range 1 to 255.
  67298. */
  67299. blendVividLight: function (a, b) {
  67300. return b < 128 ? Phaser.Color.blendColorBurn(a, 2 * b) : Phaser.Color.blendColorDodge(a, (2 * (b - 128)));
  67301. },
  67302. /**
  67303. * If the backdrop color (light source) is lighter than 50%, the blendDarken mode is used, and colors lighter than the backdrop color do not change.
  67304. * If the backdrop color is darker than 50% gray, colors lighter than the blend color are replaced, and colors darker than the blend color do not change.
  67305. *
  67306. * @method Phaser.Color.blendPinLight
  67307. * @static
  67308. * @param {integer} a - The source color to blend, in the range 1 to 255.
  67309. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  67310. * @returns {integer} The blended color value, in the range 1 to 255.
  67311. */
  67312. blendPinLight: function (a, b) {
  67313. return b < 128 ? Phaser.Color.blendDarken(a, 2 * b) : Phaser.Color.blendLighten(a, (2 * (b - 128)));
  67314. },
  67315. /**
  67316. * Runs blendVividLight on the source and backdrop colors.
  67317. * If the resulting color is 128 or more, it receives a value of 255; if less than 128, a value of 0.
  67318. * Therefore, all blended pixels have red, green, and blue channel values of either 0 or 255.
  67319. * This changes all pixels to primary additive colors (red, green, or blue), white, or black.
  67320. *
  67321. * @method Phaser.Color.blendHardMix
  67322. * @static
  67323. * @param {integer} a - The source color to blend, in the range 1 to 255.
  67324. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  67325. * @returns {integer} The blended color value, in the range 1 to 255.
  67326. */
  67327. blendHardMix: function (a, b) {
  67328. return Phaser.Color.blendVividLight(a, b) < 128 ? 0 : 255;
  67329. },
  67330. /**
  67331. * Reflect blend mode. This mode is useful when adding shining objects or light zones to images.
  67332. *
  67333. * @method Phaser.Color.blendReflect
  67334. * @static
  67335. * @param {integer} a - The source color to blend, in the range 1 to 255.
  67336. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  67337. * @returns {integer} The blended color value, in the range 1 to 255.
  67338. */
  67339. blendReflect: function (a, b) {
  67340. return b === 255 ? b : Math.min(255, (a * a / (255 - b)));
  67341. },
  67342. /**
  67343. * Glow blend mode. This mode is a variation of reflect mode with the source and backdrop colors swapped.
  67344. *
  67345. * @method Phaser.Color.blendGlow
  67346. * @static
  67347. * @param {integer} a - The source color to blend, in the range 1 to 255.
  67348. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  67349. * @returns {integer} The blended color value, in the range 1 to 255.
  67350. */
  67351. blendGlow: function (a, b) {
  67352. return Phaser.Color.blendReflect(b, a);
  67353. },
  67354. /**
  67355. * Phoenix blend mode. This subtracts the lighter color from the darker color, and adds 255, giving a bright result.
  67356. *
  67357. * @method Phaser.Color.blendPhoenix
  67358. * @static
  67359. * @param {integer} a - The source color to blend, in the range 1 to 255.
  67360. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  67361. * @returns {integer} The blended color value, in the range 1 to 255.
  67362. */
  67363. blendPhoenix: function (a, b) {
  67364. return Math.min(a, b) - Math.max(a, b) + 255;
  67365. }
  67366. };
  67367. /**
  67368. * @author Richard Davey <rich@photonstorm.com>
  67369. * @copyright 2016 Photon Storm Ltd.
  67370. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  67371. */
  67372. /**
  67373. * The Physics Manager is responsible for looking after all of the running physics systems.
  67374. * Phaser supports 4 physics systems: Arcade Physics, P2, Ninja Physics and Box2D via a commercial plugin.
  67375. *
  67376. * Game Objects (such as Sprites) can only belong to 1 physics system, but you can have multiple systems active in a single game.
  67377. *
  67378. * For example you could have P2 managing a polygon-built terrain landscape that an vehicle drives over, while it could be firing bullets that use the
  67379. * faster (due to being much simpler) Arcade Physics system.
  67380. *
  67381. * @class Phaser.Physics
  67382. * @constructor
  67383. * @param {Phaser.Game} game - A reference to the currently running game.
  67384. * @param {object} [physicsConfig=null] - A physics configuration object to pass to the Physics world on creation.
  67385. */
  67386. Phaser.Physics = function (game, config) {
  67387. config = config || {};
  67388. /**
  67389. * @property {Phaser.Game} game - Local reference to game.
  67390. */
  67391. this.game = game;
  67392. /**
  67393. * @property {object} config - The physics configuration object as passed to the game on creation.
  67394. */
  67395. this.config = config;
  67396. /**
  67397. * @property {Phaser.Physics.Arcade} arcade - The Arcade Physics system.
  67398. */
  67399. this.arcade = null;
  67400. /**
  67401. * @property {Phaser.Physics.P2} p2 - The P2.JS Physics system.
  67402. */
  67403. this.p2 = null;
  67404. /**
  67405. * @property {Phaser.Physics.Ninja} ninja - The N+ Ninja Physics system.
  67406. */
  67407. this.ninja = null;
  67408. /**
  67409. * @property {Phaser.Physics.Box2D} box2d - The Box2D Physics system.
  67410. */
  67411. this.box2d = null;
  67412. /**
  67413. * @property {Phaser.Physics.Chipmunk} chipmunk - The Chipmunk Physics system (to be done).
  67414. */
  67415. this.chipmunk = null;
  67416. /**
  67417. * @property {Phaser.Physics.Matter} matter - The MatterJS Physics system (coming soon).
  67418. */
  67419. this.matter = null;
  67420. this.parseConfig();
  67421. };
  67422. /**
  67423. * @const
  67424. * @type {number}
  67425. */
  67426. Phaser.Physics.ARCADE = 0;
  67427. /**
  67428. * @const
  67429. * @type {number}
  67430. */
  67431. Phaser.Physics.P2JS = 1;
  67432. /**
  67433. * @const
  67434. * @type {number}
  67435. */
  67436. Phaser.Physics.NINJA = 2;
  67437. /**
  67438. * @const
  67439. * @type {number}
  67440. */
  67441. Phaser.Physics.BOX2D = 3;
  67442. /**
  67443. * @const
  67444. * @type {number}
  67445. */
  67446. Phaser.Physics.CHIPMUNK = 4;
  67447. /**
  67448. * @const
  67449. * @type {number}
  67450. */
  67451. Phaser.Physics.MATTERJS = 5;
  67452. Phaser.Physics.prototype = {
  67453. /**
  67454. * Parses the Physics Configuration object passed to the Game constructor and starts any physics systems specified within.
  67455. *
  67456. * @method Phaser.Physics#parseConfig
  67457. */
  67458. parseConfig: function () {
  67459. if ((!this.config.hasOwnProperty('arcade') || this.config['arcade'] === true) && Phaser.Physics.hasOwnProperty('Arcade'))
  67460. {
  67461. // If Arcade isn't specified, we create it automatically if we can
  67462. this.arcade = new Phaser.Physics.Arcade(this.game);
  67463. }
  67464. if (this.config.hasOwnProperty('ninja') && this.config['ninja'] === true && Phaser.Physics.hasOwnProperty('Ninja'))
  67465. {
  67466. this.ninja = new Phaser.Physics.Ninja(this.game);
  67467. }
  67468. if (this.config.hasOwnProperty('p2') && this.config['p2'] === true && Phaser.Physics.hasOwnProperty('P2'))
  67469. {
  67470. this.p2 = new Phaser.Physics.P2(this.game, this.config);
  67471. }
  67472. if (this.config.hasOwnProperty('box2d') && this.config['box2d'] === true && Phaser.Physics.hasOwnProperty('BOX2D'))
  67473. {
  67474. this.box2d = new Phaser.Physics.BOX2D(this.game, this.config);
  67475. }
  67476. if (this.config.hasOwnProperty('matter') && this.config['matter'] === true && Phaser.Physics.hasOwnProperty('Matter'))
  67477. {
  67478. this.matter = new Phaser.Physics.Matter(this.game, this.config);
  67479. }
  67480. },
  67481. /**
  67482. * This will create an instance of the requested physics simulation.
  67483. * Phaser.Physics.Arcade is running by default, but all others need activating directly.
  67484. *
  67485. * You can start the following physics systems:
  67486. *
  67487. * Phaser.Physics.P2JS - A full-body advanced physics system by Stefan Hedman.
  67488. * Phaser.Physics.NINJA - A port of Metanet Softwares N+ physics system.
  67489. * Phaser.Physics.BOX2D - A commercial Phaser Plugin (see http://phaser.io)
  67490. *
  67491. * Both Ninja Physics and Box2D require their respective plugins to be loaded before you can start them.
  67492. * They are not bundled into the core Phaser library.
  67493. *
  67494. * If the physics world has already been created (i.e. in another state in your game) then
  67495. * calling startSystem will reset the physics world, not re-create it. If you need to start them again from their constructors
  67496. * then set Phaser.Physics.p2 (or whichever system you want to recreate) to `null` before calling `startSystem`.
  67497. *
  67498. * @method Phaser.Physics#startSystem
  67499. * @param {number} system - The physics system to start: Phaser.Physics.ARCADE, Phaser.Physics.P2JS, Phaser.Physics.NINJA or Phaser.Physics.BOX2D.
  67500. */
  67501. startSystem: function (system) {
  67502. if (system === Phaser.Physics.ARCADE)
  67503. {
  67504. this.arcade = new Phaser.Physics.Arcade(this.game);
  67505. }
  67506. else if (system === Phaser.Physics.P2JS)
  67507. {
  67508. if (this.p2 === null)
  67509. {
  67510. this.p2 = new Phaser.Physics.P2(this.game, this.config);
  67511. }
  67512. else
  67513. {
  67514. this.p2.reset();
  67515. }
  67516. }
  67517. else if (system === Phaser.Physics.NINJA)
  67518. {
  67519. this.ninja = new Phaser.Physics.Ninja(this.game);
  67520. }
  67521. else if (system === Phaser.Physics.BOX2D)
  67522. {
  67523. if (this.box2d === null)
  67524. {
  67525. this.box2d = new Phaser.Physics.Box2D(this.game, this.config);
  67526. }
  67527. else
  67528. {
  67529. this.box2d.reset();
  67530. }
  67531. }
  67532. else if (system === Phaser.Physics.MATTERJS)
  67533. {
  67534. if (this.matter === null)
  67535. {
  67536. this.matter = new Phaser.Physics.Matter(this.game, this.config);
  67537. }
  67538. else
  67539. {
  67540. this.matter.reset();
  67541. }
  67542. }
  67543. },
  67544. /**
  67545. * This will create a default physics body on the given game object or array of objects.
  67546. * A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed.
  67547. * It can be for any of the physics systems that have been started:
  67548. *
  67549. * Phaser.Physics.Arcade - A light weight AABB based collision system with basic separation.
  67550. * Phaser.Physics.P2JS - A full-body advanced physics system supporting multiple object shapes, polygon loading, contact materials, springs and constraints.
  67551. * Phaser.Physics.NINJA - A port of Metanet Softwares N+ physics system. Advanced AABB and Circle vs. Tile collision.
  67552. * Phaser.Physics.BOX2D - A port of https://code.google.com/p/box2d-html5
  67553. * Phaser.Physics.MATTER - A full-body and light-weight advanced physics system (still in development)
  67554. * Phaser.Physics.CHIPMUNK is still in development.
  67555. *
  67556. * If you require more control over what type of body is created, for example to create a Ninja Physics Circle instead of the default AABB, then see the
  67557. * individual physics systems `enable` methods instead of using this generic one.
  67558. *
  67559. * @method Phaser.Physics#enable
  67560. * @param {object|array} object - The game object to create the physics body on. Can also be an array of objects, a body will be created on every object in the array.
  67561. * @param {number} [system=Phaser.Physics.ARCADE] - The physics system that will be used to create the body. Defaults to Arcade Physics.
  67562. * @param {boolean} [debug=false] - Enable the debug drawing for this body. Defaults to false.
  67563. */
  67564. enable: function (object, system, debug) {
  67565. if (system === undefined) { system = Phaser.Physics.ARCADE; }
  67566. if (debug === undefined) { debug = false; }
  67567. if (system === Phaser.Physics.ARCADE)
  67568. {
  67569. this.arcade.enable(object);
  67570. }
  67571. else if (system === Phaser.Physics.P2JS && this.p2)
  67572. {
  67573. this.p2.enable(object, debug);
  67574. }
  67575. else if (system === Phaser.Physics.NINJA && this.ninja)
  67576. {
  67577. this.ninja.enableAABB(object);
  67578. }
  67579. else if (system === Phaser.Physics.BOX2D && this.box2d)
  67580. {
  67581. this.box2d.enable(object);
  67582. }
  67583. else if (system === Phaser.Physics.MATTERJS && this.matter)
  67584. {
  67585. this.matter.enable(object);
  67586. }
  67587. else
  67588. {
  67589. console.warn(object.key + ' is attempting to enable a physics body using an unknown physics system.');
  67590. }
  67591. },
  67592. /**
  67593. * preUpdate checks.
  67594. *
  67595. * @method Phaser.Physics#preUpdate
  67596. * @protected
  67597. */
  67598. preUpdate: function () {
  67599. // ArcadePhysics / Ninja don't have a core to preUpdate
  67600. if (this.p2)
  67601. {
  67602. this.p2.preUpdate();
  67603. }
  67604. if (this.box2d)
  67605. {
  67606. this.box2d.preUpdate();
  67607. }
  67608. if (this.matter)
  67609. {
  67610. this.matter.preUpdate();
  67611. }
  67612. },
  67613. /**
  67614. * Updates all running physics systems.
  67615. *
  67616. * @method Phaser.Physics#update
  67617. * @protected
  67618. */
  67619. update: function () {
  67620. // ArcadePhysics / Ninja don't have a core to update
  67621. if (this.p2)
  67622. {
  67623. this.p2.update();
  67624. }
  67625. if (this.box2d)
  67626. {
  67627. this.box2d.update();
  67628. }
  67629. if (this.matter)
  67630. {
  67631. this.matter.update();
  67632. }
  67633. },
  67634. /**
  67635. * Updates the physics bounds to match the world dimensions.
  67636. *
  67637. * @method Phaser.Physics#setBoundsToWorld
  67638. * @protected
  67639. */
  67640. setBoundsToWorld: function () {
  67641. if (this.arcade)
  67642. {
  67643. this.arcade.setBoundsToWorld();
  67644. }
  67645. if (this.ninja)
  67646. {
  67647. this.ninja.setBoundsToWorld();
  67648. }
  67649. if (this.p2)
  67650. {
  67651. this.p2.setBoundsToWorld();
  67652. }
  67653. if (this.box2d)
  67654. {
  67655. this.box2d.setBoundsToWorld();
  67656. }
  67657. if (this.matter)
  67658. {
  67659. this.matter.setBoundsToWorld();
  67660. }
  67661. },
  67662. /**
  67663. * Clears down all active physics systems. This doesn't destroy them, it just clears them of objects and is called when the State changes.
  67664. *
  67665. * @method Phaser.Physics#clear
  67666. * @protected
  67667. */
  67668. clear: function () {
  67669. if (this.p2)
  67670. {
  67671. this.p2.clear();
  67672. }
  67673. if (this.box2d)
  67674. {
  67675. this.box2d.clear();
  67676. }
  67677. if (this.matter)
  67678. {
  67679. this.matter.clear();
  67680. }
  67681. },
  67682. /**
  67683. * Resets the active physics system. Called automatically on a Phaser.State swap.
  67684. *
  67685. * @method Phaser.Physics#reset
  67686. * @protected
  67687. */
  67688. reset: function () {
  67689. if (this.p2)
  67690. {
  67691. this.p2.reset();
  67692. }
  67693. if (this.box2d)
  67694. {
  67695. this.box2d.reset();
  67696. }
  67697. if (this.matter)
  67698. {
  67699. this.matter.reset();
  67700. }
  67701. },
  67702. /**
  67703. * Destroys all active physics systems. Usually only called on a Game Shutdown, not on a State swap.
  67704. *
  67705. * @method Phaser.Physics#destroy
  67706. */
  67707. destroy: function () {
  67708. if (this.p2)
  67709. {
  67710. this.p2.destroy();
  67711. }
  67712. if (this.box2d)
  67713. {
  67714. this.box2d.destroy();
  67715. }
  67716. if (this.matter)
  67717. {
  67718. this.matter.destroy();
  67719. }
  67720. this.arcade = null;
  67721. this.ninja = null;
  67722. this.p2 = null;
  67723. this.box2d = null;
  67724. this.matter = null;
  67725. }
  67726. };
  67727. Phaser.Physics.prototype.constructor = Phaser.Physics;
  67728. /**
  67729. * @author Richard Davey <rich@photonstorm.com>
  67730. * @copyright 2016 Photon Storm Ltd.
  67731. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  67732. */
  67733. /**
  67734. * The Arcade Physics world. Contains Arcade Physics related collision, overlap and motion methods.
  67735. *
  67736. * @class Phaser.Physics.Arcade
  67737. * @constructor
  67738. * @param {Phaser.Game} game - reference to the current game instance.
  67739. */
  67740. Phaser.Physics.Arcade = function (game) {
  67741. /**
  67742. * @property {Phaser.Game} game - Local reference to game.
  67743. */
  67744. this.game = game;
  67745. /**
  67746. * @property {Phaser.Point} gravity - The World gravity setting. Defaults to x: 0, y: 0, or no gravity.
  67747. */
  67748. this.gravity = new Phaser.Point();
  67749. /**
  67750. * @property {Phaser.Rectangle} bounds - The bounds inside of which the physics world exists. Defaults to match the world bounds.
  67751. */
  67752. this.bounds = new Phaser.Rectangle(0, 0, game.world.width, game.world.height);
  67753. /**
  67754. * Set the checkCollision properties to control for which bounds collision is processed.
  67755. * For example checkCollision.down = false means Bodies cannot collide with the World.bounds.bottom.
  67756. * @property {object} checkCollision - An object containing allowed collision flags.
  67757. */
  67758. this.checkCollision = { up: true, down: true, left: true, right: true };
  67759. /**
  67760. * @property {number} maxObjects - Used by the QuadTree to set the maximum number of objects per quad.
  67761. */
  67762. this.maxObjects = 10;
  67763. /**
  67764. * @property {number} maxLevels - Used by the QuadTree to set the maximum number of iteration levels.
  67765. */
  67766. this.maxLevels = 4;
  67767. /**
  67768. * @property {number} OVERLAP_BIAS - A value added to the delta values during collision checks.
  67769. */
  67770. this.OVERLAP_BIAS = 4;
  67771. /**
  67772. * @property {boolean} forceX - If true World.separate will always separate on the X axis before Y. Otherwise it will check gravity totals first.
  67773. */
  67774. this.forceX = false;
  67775. /**
  67776. * @property {number} sortDirection - Used when colliding a Sprite vs. a Group, or a Group vs. a Group, this defines the direction the sort is based on. Default is Phaser.Physics.Arcade.LEFT_RIGHT.
  67777. * @default
  67778. */
  67779. this.sortDirection = Phaser.Physics.Arcade.LEFT_RIGHT;
  67780. /**
  67781. * @property {boolean} skipQuadTree - If true the QuadTree will not be used for any collision. QuadTrees are great if objects are well spread out in your game, otherwise they are a performance hit. If you enable this you can disable on a per body basis via `Body.skipQuadTree`.
  67782. */
  67783. this.skipQuadTree = true;
  67784. /**
  67785. * @property {boolean} isPaused - If `true` the `Body.preUpdate` method will be skipped, halting all motion for all bodies. Note that other methods such as `collide` will still work, so be careful not to call them on paused bodies.
  67786. */
  67787. this.isPaused = false;
  67788. /**
  67789. * @property {Phaser.QuadTree} quadTree - The world QuadTree.
  67790. */
  67791. this.quadTree = new Phaser.QuadTree(this.game.world.bounds.x, this.game.world.bounds.y, this.game.world.bounds.width, this.game.world.bounds.height, this.maxObjects, this.maxLevels);
  67792. /**
  67793. * @property {number} _total - Internal cache var.
  67794. * @private
  67795. */
  67796. this._total = 0;
  67797. // By default we want the bounds the same size as the world bounds
  67798. this.setBoundsToWorld();
  67799. };
  67800. Phaser.Physics.Arcade.prototype.constructor = Phaser.Physics.Arcade;
  67801. /**
  67802. * A constant used for the sortDirection value.
  67803. * Use this if you don't wish to perform any pre-collision sorting at all, or will manually sort your Groups.
  67804. * @constant
  67805. * @type {number}
  67806. */
  67807. Phaser.Physics.Arcade.SORT_NONE = 0;
  67808. /**
  67809. * A constant used for the sortDirection value.
  67810. * Use this if your game world is wide but short and scrolls from the left to the right (i.e. Mario)
  67811. * @constant
  67812. * @type {number}
  67813. */
  67814. Phaser.Physics.Arcade.LEFT_RIGHT = 1;
  67815. /**
  67816. * A constant used for the sortDirection value.
  67817. * Use this if your game world is wide but short and scrolls from the right to the left (i.e. Mario backwards)
  67818. * @constant
  67819. * @type {number}
  67820. */
  67821. Phaser.Physics.Arcade.RIGHT_LEFT = 2;
  67822. /**
  67823. * A constant used for the sortDirection value.
  67824. * Use this if your game world is narrow but tall and scrolls from the top to the bottom (i.e. Dig Dug)
  67825. * @constant
  67826. * @type {number}
  67827. */
  67828. Phaser.Physics.Arcade.TOP_BOTTOM = 3;
  67829. /**
  67830. * A constant used for the sortDirection value.
  67831. * Use this if your game world is narrow but tall and scrolls from the bottom to the top (i.e. Commando or a vertically scrolling shoot-em-up)
  67832. * @constant
  67833. * @type {number}
  67834. */
  67835. Phaser.Physics.Arcade.BOTTOM_TOP = 4;
  67836. Phaser.Physics.Arcade.prototype = {
  67837. /**
  67838. * Updates the size of this physics world.
  67839. *
  67840. * @method Phaser.Physics.Arcade#setBounds
  67841. * @param {number} x - Top left most corner of the world.
  67842. * @param {number} y - Top left most corner of the world.
  67843. * @param {number} width - New width of the world. Can never be smaller than the Game.width.
  67844. * @param {number} height - New height of the world. Can never be smaller than the Game.height.
  67845. */
  67846. setBounds: function (x, y, width, height) {
  67847. this.bounds.setTo(x, y, width, height);
  67848. },
  67849. /**
  67850. * Updates the size of this physics world to match the size of the game world.
  67851. *
  67852. * @method Phaser.Physics.Arcade#setBoundsToWorld
  67853. */
  67854. setBoundsToWorld: function () {
  67855. this.bounds.copyFrom(this.game.world.bounds);
  67856. },
  67857. /**
  67858. * This will create an Arcade Physics body on the given game object or array of game objects.
  67859. * A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed.
  67860. *
  67861. * @method Phaser.Physics.Arcade#enable
  67862. * @param {object|array|Phaser.Group} object - The game object to create the physics body on. Can also be an array or Group of objects, a body will be created on every child that has a `body` property.
  67863. * @param {boolean} [children=true] - Should a body be created on all children of this object? If true it will recurse down the display list as far as it can go.
  67864. */
  67865. enable: function (object, children) {
  67866. if (children === undefined) { children = true; }
  67867. var i = 1;
  67868. if (Array.isArray(object))
  67869. {
  67870. i = object.length;
  67871. while (i--)
  67872. {
  67873. if (object[i] instanceof Phaser.Group)
  67874. {
  67875. // If it's a Group then we do it on the children regardless
  67876. this.enable(object[i].children, children);
  67877. }
  67878. else
  67879. {
  67880. this.enableBody(object[i]);
  67881. if (children && object[i].hasOwnProperty('children') && object[i].children.length > 0)
  67882. {
  67883. this.enable(object[i], true);
  67884. }
  67885. }
  67886. }
  67887. }
  67888. else
  67889. {
  67890. if (object instanceof Phaser.Group)
  67891. {
  67892. // If it's a Group then we do it on the children regardless
  67893. this.enable(object.children, children);
  67894. }
  67895. else
  67896. {
  67897. this.enableBody(object);
  67898. if (children && object.hasOwnProperty('children') && object.children.length > 0)
  67899. {
  67900. this.enable(object.children, true);
  67901. }
  67902. }
  67903. }
  67904. },
  67905. /**
  67906. * Creates an Arcade Physics body on the given game object.
  67907. *
  67908. * A game object can only have 1 physics body active at any one time, and it can't be changed until the body is nulled.
  67909. *
  67910. * When you add an Arcade Physics body to an object it will automatically add the object into its parent Groups hash array.
  67911. *
  67912. * @method Phaser.Physics.Arcade#enableBody
  67913. * @param {object} object - The game object to create the physics body on. A body will only be created if this object has a null `body` property.
  67914. */
  67915. enableBody: function (object) {
  67916. if (object.hasOwnProperty('body') && object.body === null)
  67917. {
  67918. object.body = new Phaser.Physics.Arcade.Body(object);
  67919. if (object.parent && object.parent instanceof Phaser.Group)
  67920. {
  67921. object.parent.addToHash(object);
  67922. }
  67923. }
  67924. },
  67925. /**
  67926. * Called automatically by a Physics body, it updates all motion related values on the Body unless `World.isPaused` is `true`.
  67927. *
  67928. * @method Phaser.Physics.Arcade#updateMotion
  67929. * @param {Phaser.Physics.Arcade.Body} The Body object to be updated.
  67930. */
  67931. updateMotion: function (body) {
  67932. var velocityDelta = this.computeVelocity(0, body, body.angularVelocity, body.angularAcceleration, body.angularDrag, body.maxAngular) - body.angularVelocity;
  67933. body.angularVelocity += velocityDelta;
  67934. body.rotation += (body.angularVelocity * this.game.time.physicsElapsed);
  67935. body.velocity.x = this.computeVelocity(1, body, body.velocity.x, body.acceleration.x, body.drag.x, body.maxVelocity.x);
  67936. body.velocity.y = this.computeVelocity(2, body, body.velocity.y, body.acceleration.y, body.drag.y, body.maxVelocity.y);
  67937. },
  67938. /**
  67939. * A tween-like function that takes a starting velocity and some other factors and returns an altered velocity.
  67940. * Based on a function in Flixel by @ADAMATOMIC
  67941. *
  67942. * @method Phaser.Physics.Arcade#computeVelocity
  67943. * @param {number} axis - 0 for nothing, 1 for horizontal, 2 for vertical.
  67944. * @param {Phaser.Physics.Arcade.Body} body - The Body object to be updated.
  67945. * @param {number} velocity - Any component of velocity (e.g. 20).
  67946. * @param {number} acceleration - Rate at which the velocity is changing.
  67947. * @param {number} drag - Really kind of a deceleration, this is how much the velocity changes if Acceleration is not set.
  67948. * @param {number} [max=10000] - An absolute value cap for the velocity.
  67949. * @return {number} The altered Velocity value.
  67950. */
  67951. computeVelocity: function (axis, body, velocity, acceleration, drag, max) {
  67952. if (max === undefined) { max = 10000; }
  67953. if (axis === 1 && body.allowGravity)
  67954. {
  67955. velocity += (this.gravity.x + body.gravity.x) * this.game.time.physicsElapsed;
  67956. }
  67957. else if (axis === 2 && body.allowGravity)
  67958. {
  67959. velocity += (this.gravity.y + body.gravity.y) * this.game.time.physicsElapsed;
  67960. }
  67961. if (acceleration)
  67962. {
  67963. velocity += acceleration * this.game.time.physicsElapsed;
  67964. }
  67965. else if (drag)
  67966. {
  67967. drag *= this.game.time.physicsElapsed;
  67968. if (velocity - drag > 0)
  67969. {
  67970. velocity -= drag;
  67971. }
  67972. else if (velocity + drag < 0)
  67973. {
  67974. velocity += drag;
  67975. }
  67976. else
  67977. {
  67978. velocity = 0;
  67979. }
  67980. }
  67981. if (velocity > max)
  67982. {
  67983. velocity = max;
  67984. }
  67985. else if (velocity < -max)
  67986. {
  67987. velocity = -max;
  67988. }
  67989. return velocity;
  67990. },
  67991. /**
  67992. * Checks for overlaps between two game objects. The objects can be Sprites, Groups or Emitters.
  67993. * You can perform Sprite vs. Sprite, Sprite vs. Group and Group vs. Group overlap checks.
  67994. * Unlike collide the objects are NOT automatically separated or have any physics applied, they merely test for overlap results.
  67995. * Both the first and second parameter can be arrays of objects, of differing types.
  67996. * If two arrays are passed, the contents of the first parameter will be tested against all contents of the 2nd parameter.
  67997. * NOTE: This function is not recursive, and will not test against children of objects passed (i.e. Groups within Groups).
  67998. *
  67999. * @method Phaser.Physics.Arcade#overlap
  68000. * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|array} object1 - The first object or array of objects to check. Can be Phaser.Sprite, Phaser.Group or Phaser.Particles.Emitter.
  68001. * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|array} object2 - The second object or array of objects to check. Can be Phaser.Sprite, Phaser.Group or Phaser.Particles.Emitter.
  68002. * @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, unless you are checking Group vs. Sprite, in which case Sprite will always be the first parameter.
  68003. * @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 this callback returns `true`.
  68004. * @param {object} [callbackContext] - The context in which to run the callbacks.
  68005. * @return {boolean} True if an overlap occurred otherwise false.
  68006. */
  68007. overlap: function (object1, object2, overlapCallback, processCallback, callbackContext) {
  68008. overlapCallback = overlapCallback || null;
  68009. processCallback = processCallback || null;
  68010. callbackContext = callbackContext || overlapCallback;
  68011. this._total = 0;
  68012. if (!Array.isArray(object1) && Array.isArray(object2))
  68013. {
  68014. for (var i = 0; i < object2.length; i++)
  68015. {
  68016. this.collideHandler(object1, object2[i], overlapCallback, processCallback, callbackContext, true);
  68017. }
  68018. }
  68019. else if (Array.isArray(object1) && !Array.isArray(object2))
  68020. {
  68021. for (var i = 0; i < object1.length; i++)
  68022. {
  68023. this.collideHandler(object1[i], object2, overlapCallback, processCallback, callbackContext, true);
  68024. }
  68025. }
  68026. else if (Array.isArray(object1) && Array.isArray(object2))
  68027. {
  68028. for (var i = 0; i < object1.length; i++)
  68029. {
  68030. for (var j = 0; j < object2.length; j++)
  68031. {
  68032. this.collideHandler(object1[i], object2[j], overlapCallback, processCallback, callbackContext, true);
  68033. }
  68034. }
  68035. }
  68036. else
  68037. {
  68038. this.collideHandler(object1, object2, overlapCallback, processCallback, callbackContext, true);
  68039. }
  68040. return (this._total > 0);
  68041. },
  68042. /**
  68043. * Checks for collision between two game objects. You can perform Sprite vs. Sprite, Sprite vs. Group, Group vs. Group, Sprite vs. Tilemap Layer or Group vs. Tilemap Layer collisions.
  68044. * Both the first and second parameter can be arrays of objects, of differing types.
  68045. * If two arrays are passed, the contents of the first parameter will be tested against all contents of the 2nd parameter.
  68046. * The objects are also automatically separated. If you don't require separation then use ArcadePhysics.overlap instead.
  68047. * An optional processCallback can be provided. If given this function will be called when two sprites are found to be colliding. It is called before any separation takes place,
  68048. * giving you the chance to perform additional checks. If the function returns true then the collision and separation is carried out. If it returns false it is skipped.
  68049. * The collideCallback is an optional function that is only called if two sprites collide. If a processCallback has been set then it needs to return true for collideCallback to be called.
  68050. * NOTE: This function is not recursive, and will not test against children of objects passed (i.e. Groups or Tilemaps within other Groups).
  68051. *
  68052. * @method Phaser.Physics.Arcade#collide
  68053. * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer|array} object1 - The first object or array of objects to check. Can be Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter, or Phaser.TilemapLayer.
  68054. * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer|array} object2 - The second object or array of objects to check. Can be Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter or Phaser.TilemapLayer.
  68055. * @param {function} [collideCallback=null] - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them, unless you are colliding Group vs. Sprite, in which case Sprite will always be the first parameter.
  68056. * @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 collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them, unless you are colliding Group vs. Sprite, in which case Sprite will always be the first parameter.
  68057. * @param {object} [callbackContext] - The context in which to run the callbacks.
  68058. * @return {boolean} True if a collision occurred otherwise false.
  68059. */
  68060. collide: function (object1, object2, collideCallback, processCallback, callbackContext) {
  68061. collideCallback = collideCallback || null;
  68062. processCallback = processCallback || null;
  68063. callbackContext = callbackContext || collideCallback;
  68064. this._total = 0;
  68065. if (!Array.isArray(object1) && Array.isArray(object2))
  68066. {
  68067. for (var i = 0; i < object2.length; i++)
  68068. {
  68069. this.collideHandler(object1, object2[i], collideCallback, processCallback, callbackContext, false);
  68070. }
  68071. }
  68072. else if (Array.isArray(object1) && !Array.isArray(object2))
  68073. {
  68074. for (var i = 0; i < object1.length; i++)
  68075. {
  68076. this.collideHandler(object1[i], object2, collideCallback, processCallback, callbackContext, false);
  68077. }
  68078. }
  68079. else if (Array.isArray(object1) && Array.isArray(object2))
  68080. {
  68081. for (var i = 0; i < object1.length; i++)
  68082. {
  68083. for (var j = 0; j < object2.length; j++)
  68084. {
  68085. this.collideHandler(object1[i], object2[j], collideCallback, processCallback, callbackContext, false);
  68086. }
  68087. }
  68088. }
  68089. else
  68090. {
  68091. this.collideHandler(object1, object2, collideCallback, processCallback, callbackContext, false);
  68092. }
  68093. return (this._total > 0);
  68094. },
  68095. /**
  68096. * A Sort function for sorting two bodies based on a LEFT to RIGHT sort direction.
  68097. *
  68098. * This is called automatically by World.sort
  68099. *
  68100. * @method Phaser.Physics.Arcade#sortLeftRight
  68101. * @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body.
  68102. * @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body.
  68103. * @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid.
  68104. */
  68105. sortLeftRight: function (a, b) {
  68106. if (!a.body || !b.body)
  68107. {
  68108. return 0;
  68109. }
  68110. return a.body.x - b.body.x;
  68111. },
  68112. /**
  68113. * A Sort function for sorting two bodies based on a RIGHT to LEFT sort direction.
  68114. *
  68115. * This is called automatically by World.sort
  68116. *
  68117. * @method Phaser.Physics.Arcade#sortRightLeft
  68118. * @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body.
  68119. * @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body.
  68120. * @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid.
  68121. */
  68122. sortRightLeft: function (a, b) {
  68123. if (!a.body || !b.body)
  68124. {
  68125. return 0;
  68126. }
  68127. return b.body.x - a.body.x;
  68128. },
  68129. /**
  68130. * A Sort function for sorting two bodies based on a TOP to BOTTOM sort direction.
  68131. *
  68132. * This is called automatically by World.sort
  68133. *
  68134. * @method Phaser.Physics.Arcade#sortTopBottom
  68135. * @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body.
  68136. * @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body.
  68137. * @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid.
  68138. */
  68139. sortTopBottom: function (a, b) {
  68140. if (!a.body || !b.body)
  68141. {
  68142. return 0;
  68143. }
  68144. return a.body.y - b.body.y;
  68145. },
  68146. /**
  68147. * A Sort function for sorting two bodies based on a BOTTOM to TOP sort direction.
  68148. *
  68149. * This is called automatically by World.sort
  68150. *
  68151. * @method Phaser.Physics.Arcade#sortBottomTop
  68152. * @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body.
  68153. * @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body.
  68154. * @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid.
  68155. */
  68156. sortBottomTop: function (a, b) {
  68157. if (!a.body || !b.body)
  68158. {
  68159. return 0;
  68160. }
  68161. return b.body.y - a.body.y;
  68162. },
  68163. /**
  68164. * This method will sort a Groups hash array.
  68165. *
  68166. * If the Group has `physicsSortDirection` set it will use the sort direction defined.
  68167. *
  68168. * Otherwise if the sortDirection parameter is undefined, or Group.physicsSortDirection is null, it will use Phaser.Physics.Arcade.sortDirection.
  68169. *
  68170. * By changing Group.physicsSortDirection you can customise each Group to sort in a different order.
  68171. *
  68172. * @method Phaser.Physics.Arcade#sort
  68173. * @param {Phaser.Group} group - The Group to sort.
  68174. * @param {integer} [sortDirection] - The sort direction used to sort this Group.
  68175. */
  68176. sort: function (group, sortDirection) {
  68177. if (group.physicsSortDirection !== null)
  68178. {
  68179. sortDirection = group.physicsSortDirection;
  68180. }
  68181. else
  68182. {
  68183. if (sortDirection === undefined) { sortDirection = this.sortDirection; }
  68184. }
  68185. if (sortDirection === Phaser.Physics.Arcade.LEFT_RIGHT)
  68186. {
  68187. // Game world is say 2000x600 and you start at 0
  68188. group.hash.sort(this.sortLeftRight);
  68189. }
  68190. else if (sortDirection === Phaser.Physics.Arcade.RIGHT_LEFT)
  68191. {
  68192. // Game world is say 2000x600 and you start at 2000
  68193. group.hash.sort(this.sortRightLeft);
  68194. }
  68195. else if (sortDirection === Phaser.Physics.Arcade.TOP_BOTTOM)
  68196. {
  68197. // Game world is say 800x2000 and you start at 0
  68198. group.hash.sort(this.sortTopBottom);
  68199. }
  68200. else if (sortDirection === Phaser.Physics.Arcade.BOTTOM_TOP)
  68201. {
  68202. // Game world is say 800x2000 and you start at 2000
  68203. group.hash.sort(this.sortBottomTop);
  68204. }
  68205. },
  68206. /**
  68207. * Internal collision handler.
  68208. *
  68209. * @method Phaser.Physics.Arcade#collideHandler
  68210. * @private
  68211. * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer} object1 - The first object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter, or Phaser.TilemapLayer.
  68212. * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer} object2 - The second object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter or Phaser.TilemapLayer. Can also be an array of objects to check.
  68213. * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them.
  68214. * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them.
  68215. * @param {object} callbackContext - The context in which to run the callbacks.
  68216. * @param {boolean} overlapOnly - Just run an overlap or a full collision.
  68217. */
  68218. collideHandler: function (object1, object2, collideCallback, processCallback, callbackContext, overlapOnly) {
  68219. // Only collide valid objects
  68220. if (object2 === undefined && object1.physicsType === Phaser.GROUP)
  68221. {
  68222. this.sort(object1);
  68223. this.collideGroupVsSelf(object1, collideCallback, processCallback, callbackContext, overlapOnly);
  68224. return;
  68225. }
  68226. // If neither of the objects are set or exist then bail out
  68227. if (!object1 || !object2 || !object1.exists || !object2.exists)
  68228. {
  68229. return;
  68230. }
  68231. // Groups? Sort them
  68232. if (this.sortDirection !== Phaser.Physics.Arcade.SORT_NONE)
  68233. {
  68234. if (object1.physicsType === Phaser.GROUP)
  68235. {
  68236. this.sort(object1);
  68237. }
  68238. if (object2.physicsType === Phaser.GROUP)
  68239. {
  68240. this.sort(object2);
  68241. }
  68242. }
  68243. // SPRITES
  68244. if (object1.physicsType === Phaser.SPRITE)
  68245. {
  68246. if (object2.physicsType === Phaser.SPRITE)
  68247. {
  68248. this.collideSpriteVsSprite(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly);
  68249. }
  68250. else if (object2.physicsType === Phaser.GROUP)
  68251. {
  68252. this.collideSpriteVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly);
  68253. }
  68254. else if (object2.physicsType === Phaser.TILEMAPLAYER)
  68255. {
  68256. this.collideSpriteVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly);
  68257. }
  68258. }
  68259. // GROUPS
  68260. else if (object1.physicsType === Phaser.GROUP)
  68261. {
  68262. if (object2.physicsType === Phaser.SPRITE)
  68263. {
  68264. this.collideSpriteVsGroup(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly);
  68265. }
  68266. else if (object2.physicsType === Phaser.GROUP)
  68267. {
  68268. this.collideGroupVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly);
  68269. }
  68270. else if (object2.physicsType === Phaser.TILEMAPLAYER)
  68271. {
  68272. this.collideGroupVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly);
  68273. }
  68274. }
  68275. // TILEMAP LAYERS
  68276. else if (object1.physicsType === Phaser.TILEMAPLAYER)
  68277. {
  68278. if (object2.physicsType === Phaser.SPRITE)
  68279. {
  68280. this.collideSpriteVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly);
  68281. }
  68282. else if (object2.physicsType === Phaser.GROUP)
  68283. {
  68284. this.collideGroupVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly);
  68285. }
  68286. }
  68287. },
  68288. /**
  68289. * An internal function. Use Phaser.Physics.Arcade.collide instead.
  68290. *
  68291. * @method Phaser.Physics.Arcade#collideSpriteVsSprite
  68292. * @private
  68293. * @param {Phaser.Sprite} sprite1 - The first sprite to check.
  68294. * @param {Phaser.Sprite} sprite2 - The second sprite to check.
  68295. * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them.
  68296. * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them.
  68297. * @param {object} callbackContext - The context in which to run the callbacks.
  68298. * @param {boolean} overlapOnly - Just run an overlap or a full collision.
  68299. * @return {boolean} True if there was a collision, otherwise false.
  68300. */
  68301. collideSpriteVsSprite: function (sprite1, sprite2, collideCallback, processCallback, callbackContext, overlapOnly) {
  68302. if (!sprite1.body || !sprite2.body)
  68303. {
  68304. return false;
  68305. }
  68306. if (this.separate(sprite1.body, sprite2.body, processCallback, callbackContext, overlapOnly))
  68307. {
  68308. if (collideCallback)
  68309. {
  68310. collideCallback.call(callbackContext, sprite1, sprite2);
  68311. }
  68312. this._total++;
  68313. }
  68314. return true;
  68315. },
  68316. /**
  68317. * An internal function. Use Phaser.Physics.Arcade.collide instead.
  68318. *
  68319. * @method Phaser.Physics.Arcade#collideSpriteVsGroup
  68320. * @private
  68321. * @param {Phaser.Sprite} sprite - The sprite to check.
  68322. * @param {Phaser.Group} group - The Group to check.
  68323. * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them.
  68324. * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them.
  68325. * @param {object} callbackContext - The context in which to run the callbacks.
  68326. * @param {boolean} overlapOnly - Just run an overlap or a full collision.
  68327. */
  68328. collideSpriteVsGroup: function (sprite, group, collideCallback, processCallback, callbackContext, overlapOnly) {
  68329. if (group.length === 0 || !sprite.body)
  68330. {
  68331. return;
  68332. }
  68333. var body;
  68334. if (this.skipQuadTree || sprite.body.skipQuadTree)
  68335. {
  68336. for (var i = 0; i < group.hash.length; i++)
  68337. {
  68338. // Skip duff entries - we can't check a non-existent sprite or one with no body
  68339. if (!group.hash[i] || !group.hash[i].exists || !group.hash[i].body)
  68340. {
  68341. continue;
  68342. }
  68343. body = group.hash[i].body;
  68344. // Skip items either side of the sprite
  68345. if (this.sortDirection === Phaser.Physics.Arcade.LEFT_RIGHT)
  68346. {
  68347. if (sprite.body.right < body.x)
  68348. {
  68349. break;
  68350. }
  68351. else if (body.right < sprite.body.x)
  68352. {
  68353. continue;
  68354. }
  68355. }
  68356. else if (this.sortDirection === Phaser.Physics.Arcade.RIGHT_LEFT)
  68357. {
  68358. if (sprite.body.x > body.right)
  68359. {
  68360. break;
  68361. }
  68362. else if (body.x > sprite.body.right)
  68363. {
  68364. continue;
  68365. }
  68366. }
  68367. else if (this.sortDirection === Phaser.Physics.Arcade.TOP_BOTTOM)
  68368. {
  68369. if (sprite.body.bottom < body.y)
  68370. {
  68371. break;
  68372. }
  68373. else if (body.bottom < sprite.body.y)
  68374. {
  68375. continue;
  68376. }
  68377. }
  68378. else if (this.sortDirection === Phaser.Physics.Arcade.BOTTOM_TOP)
  68379. {
  68380. if (sprite.body.y > body.bottom)
  68381. {
  68382. break;
  68383. }
  68384. else if (body.y > sprite.body.bottom)
  68385. {
  68386. continue;
  68387. }
  68388. }
  68389. this.collideSpriteVsSprite(sprite, group.hash[i], collideCallback, processCallback, callbackContext, overlapOnly);
  68390. }
  68391. }
  68392. else
  68393. {
  68394. // What is the sprite colliding with in the quadtree?
  68395. this.quadTree.clear();
  68396. this.quadTree.reset(this.game.world.bounds.x, this.game.world.bounds.y, this.game.world.bounds.width, this.game.world.bounds.height, this.maxObjects, this.maxLevels);
  68397. this.quadTree.populate(group);
  68398. var items = this.quadTree.retrieve(sprite);
  68399. for (var i = 0; i < items.length; i++)
  68400. {
  68401. // We have our potential suspects, are they in this group?
  68402. if (this.separate(sprite.body, items[i], processCallback, callbackContext, overlapOnly))
  68403. {
  68404. if (collideCallback)
  68405. {
  68406. collideCallback.call(callbackContext, sprite, items[i].sprite);
  68407. }
  68408. this._total++;
  68409. }
  68410. }
  68411. }
  68412. },
  68413. /**
  68414. * An internal function. Use Phaser.Physics.Arcade.collide instead.
  68415. *
  68416. * @method Phaser.Physics.Arcade#collideGroupVsSelf
  68417. * @private
  68418. * @param {Phaser.Group} group - The Group to check.
  68419. * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them.
  68420. * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them.
  68421. * @param {object} callbackContext - The context in which to run the callbacks.
  68422. * @param {boolean} overlapOnly - Just run an overlap or a full collision.
  68423. * @return {boolean} True if there was a collision, otherwise false.
  68424. */
  68425. collideGroupVsSelf: function (group, collideCallback, processCallback, callbackContext, overlapOnly) {
  68426. if (group.length === 0)
  68427. {
  68428. return;
  68429. }
  68430. for (var i = 0; i < group.hash.length; i++)
  68431. {
  68432. // Skip duff entries - we can't check a non-existent sprite or one with no body
  68433. if (!group.hash[i] || !group.hash[i].exists || !group.hash[i].body)
  68434. {
  68435. continue;
  68436. }
  68437. var object1 = group.hash[i];
  68438. for (var j = i + 1; j < group.hash.length; j++)
  68439. {
  68440. // Skip duff entries - we can't check a non-existent sprite or one with no body
  68441. if (!group.hash[j] || !group.hash[j].exists || !group.hash[j].body)
  68442. {
  68443. continue;
  68444. }
  68445. var object2 = group.hash[j];
  68446. // Skip items either side of the sprite
  68447. if (this.sortDirection === Phaser.Physics.Arcade.LEFT_RIGHT)
  68448. {
  68449. if (object1.body.right < object2.body.x)
  68450. {
  68451. break;
  68452. }
  68453. else if (object2.body.right < object1.body.x)
  68454. {
  68455. continue;
  68456. }
  68457. }
  68458. else if (this.sortDirection === Phaser.Physics.Arcade.RIGHT_LEFT)
  68459. {
  68460. if (object1.body.x > object2.body.right)
  68461. {
  68462. continue;
  68463. }
  68464. else if (object2.body.x > object1.body.right)
  68465. {
  68466. break;
  68467. }
  68468. }
  68469. else if (this.sortDirection === Phaser.Physics.Arcade.TOP_BOTTOM)
  68470. {
  68471. if (object1.body.bottom < object2.body.y)
  68472. {
  68473. continue;
  68474. }
  68475. else if (object2.body.bottom < object1.body.y)
  68476. {
  68477. break;
  68478. }
  68479. }
  68480. else if (this.sortDirection === Phaser.Physics.Arcade.BOTTOM_TOP)
  68481. {
  68482. if (object1.body.y > object2.body.bottom)
  68483. {
  68484. continue;
  68485. }
  68486. else if (object2.body.y > object1.body.bottom)
  68487. {
  68488. break;
  68489. }
  68490. }
  68491. this.collideSpriteVsSprite(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly);
  68492. }
  68493. }
  68494. },
  68495. /**
  68496. * An internal function. Use Phaser.Physics.Arcade.collide instead.
  68497. *
  68498. * @method Phaser.Physics.Arcade#collideGroupVsGroup
  68499. * @private
  68500. * @param {Phaser.Group} group1 - The first Group to check.
  68501. * @param {Phaser.Group} group2 - The second Group to check.
  68502. * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them.
  68503. * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them.
  68504. * @param {object} callbackContext - The context in which to run the callbacks.
  68505. * @param {boolean} overlapOnly - Just run an overlap or a full collision.
  68506. */
  68507. collideGroupVsGroup: function (group1, group2, collideCallback, processCallback, callbackContext, overlapOnly) {
  68508. if (group1.length === 0 || group2.length === 0)
  68509. {
  68510. return;
  68511. }
  68512. for (var i = 0; i < group1.children.length; i++)
  68513. {
  68514. if (group1.children[i].exists)
  68515. {
  68516. if (group1.children[i].physicsType === Phaser.GROUP)
  68517. {
  68518. this.collideGroupVsGroup(group1.children[i], group2, collideCallback, processCallback, callbackContext, overlapOnly);
  68519. }
  68520. else
  68521. {
  68522. this.collideSpriteVsGroup(group1.children[i], group2, collideCallback, processCallback, callbackContext, overlapOnly);
  68523. }
  68524. }
  68525. }
  68526. },
  68527. /**
  68528. * The core separation function to separate two physics bodies.
  68529. *
  68530. * @private
  68531. * @method Phaser.Physics.Arcade#separate
  68532. * @param {Phaser.Physics.Arcade.Body} body1 - The first Body object to separate.
  68533. * @param {Phaser.Physics.Arcade.Body} body2 - The second Body object to separate.
  68534. * @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this function is set then the sprites will only be collided if it returns true.
  68535. * @param {object} [callbackContext] - The context in which to run the process callback.
  68536. * @param {boolean} overlapOnly - Just run an overlap or a full collision.
  68537. * @return {boolean} Returns true if the bodies collided, otherwise false.
  68538. */
  68539. separate: function (body1, body2, processCallback, callbackContext, overlapOnly) {
  68540. if (!body1.enable || !body2.enable || !this.intersects(body1, body2))
  68541. {
  68542. return false;
  68543. }
  68544. // They overlap. Is there a custom process callback? If it returns true then we can carry on, otherwise we should abort.
  68545. if (processCallback && processCallback.call(callbackContext, body1.sprite, body2.sprite) === false)
  68546. {
  68547. return false;
  68548. }
  68549. var resultX = false;
  68550. var resultY = false;
  68551. // Do we separate on x or y first?
  68552. if (this.forceX || Math.abs(this.gravity.y + body1.gravity.y) < Math.abs(this.gravity.x + body1.gravity.x))
  68553. {
  68554. resultX = this.separateX(body1, body2, overlapOnly);
  68555. // Are they still intersecting? Let's do the other axis then
  68556. if (this.intersects(body1, body2))
  68557. {
  68558. resultY = this.separateY(body1, body2, overlapOnly);
  68559. }
  68560. }
  68561. else
  68562. {
  68563. resultY = this.separateY(body1, body2, overlapOnly);
  68564. // Are they still intersecting? Let's do the other axis then
  68565. if (this.intersects(body1, body2))
  68566. {
  68567. resultX = this.separateX(body1, body2, overlapOnly);
  68568. }
  68569. }
  68570. return (resultX || resultY);
  68571. },
  68572. /**
  68573. * Check for intersection against two bodies.
  68574. *
  68575. * @method Phaser.Physics.Arcade#intersects
  68576. * @param {Phaser.Physics.Arcade.Body} body1 - The first Body object to check.
  68577. * @param {Phaser.Physics.Arcade.Body} body2 - The second Body object to check.
  68578. * @return {boolean} True if they intersect, otherwise false.
  68579. */
  68580. intersects: function (body1, body2) {
  68581. // Rect vs. Rect
  68582. if (body1.right <= body2.position.x)
  68583. {
  68584. return false;
  68585. }
  68586. if (body1.bottom <= body2.position.y)
  68587. {
  68588. return false;
  68589. }
  68590. if (body1.position.x >= body2.right)
  68591. {
  68592. return false;
  68593. }
  68594. if (body1.position.y >= body2.bottom)
  68595. {
  68596. return false;
  68597. }
  68598. return true;
  68599. },
  68600. /**
  68601. * Calculates the horizontal overlap between two Bodies and sets their properties accordingly, including:
  68602. * `touching.left`, `touching.right` and `overlapX`.
  68603. *
  68604. * @method Phaser.Physics.Arcade#getOverlapX
  68605. * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate.
  68606. * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate.
  68607. * @return {float} Returns the amount of horizontal overlap between the two bodies.
  68608. */
  68609. getOverlapX: function (body1, body2) {
  68610. var overlap = 0;
  68611. var maxOverlap = body1.deltaAbsX() + body2.deltaAbsX() + this.OVERLAP_BIAS;
  68612. if (body1.deltaX() === 0 && body2.deltaX() === 0)
  68613. {
  68614. // They overlap but neither of them are moving
  68615. body1.embedded = true;
  68616. body2.embedded = true;
  68617. }
  68618. else if (body1.deltaX() > body2.deltaX())
  68619. {
  68620. // Body1 is moving right and / or Body2 is moving left
  68621. overlap = body1.right - body2.x;
  68622. if ((overlap > maxOverlap) || body1.checkCollision.right === false || body2.checkCollision.left === false)
  68623. {
  68624. overlap = 0;
  68625. }
  68626. else
  68627. {
  68628. body1.touching.none = false;
  68629. body1.touching.right = true;
  68630. body2.touching.none = false;
  68631. body2.touching.left = true;
  68632. }
  68633. }
  68634. else if (body1.deltaX() < body2.deltaX())
  68635. {
  68636. // Body1 is moving left and/or Body2 is moving right
  68637. overlap = body1.x - body2.width - body2.x;
  68638. if ((-overlap > maxOverlap) || body1.checkCollision.left === false || body2.checkCollision.right === false)
  68639. {
  68640. overlap = 0;
  68641. }
  68642. else
  68643. {
  68644. body1.touching.none = false;
  68645. body1.touching.left = true;
  68646. body2.touching.none = false;
  68647. body2.touching.right = true;
  68648. }
  68649. }
  68650. // Resets the overlapX to zero if there is no overlap, or to the actual pixel value if there is
  68651. body1.overlapX = overlap;
  68652. body2.overlapX = overlap;
  68653. return overlap;
  68654. },
  68655. /**
  68656. * Calculates the vertical overlap between two Bodies and sets their properties accordingly, including:
  68657. * `touching.up`, `touching.down` and `overlapY`.
  68658. *
  68659. * @method Phaser.Physics.Arcade#getOverlapY
  68660. * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate.
  68661. * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate.
  68662. * @return {float} Returns the amount of vertical overlap between the two bodies.
  68663. */
  68664. getOverlapY: function (body1, body2) {
  68665. var overlap = 0;
  68666. var maxOverlap = body1.deltaAbsY() + body2.deltaAbsY() + this.OVERLAP_BIAS;
  68667. if (body1.deltaY() === 0 && body2.deltaY() === 0)
  68668. {
  68669. // They overlap but neither of them are moving
  68670. body1.embedded = true;
  68671. body2.embedded = true;
  68672. }
  68673. else if (body1.deltaY() > body2.deltaY())
  68674. {
  68675. // Body1 is moving down and/or Body2 is moving up
  68676. overlap = body1.bottom - body2.y;
  68677. if ((overlap > maxOverlap) || body1.checkCollision.down === false || body2.checkCollision.up === false)
  68678. {
  68679. overlap = 0;
  68680. }
  68681. else
  68682. {
  68683. body1.touching.none = false;
  68684. body1.touching.down = true;
  68685. body2.touching.none = false;
  68686. body2.touching.up = true;
  68687. }
  68688. }
  68689. else if (body1.deltaY() < body2.deltaY())
  68690. {
  68691. // Body1 is moving up and/or Body2 is moving down
  68692. overlap = body1.y - body2.bottom;
  68693. if ((-overlap > maxOverlap) || body1.checkCollision.up === false || body2.checkCollision.down === false)
  68694. {
  68695. overlap = 0;
  68696. }
  68697. else
  68698. {
  68699. body1.touching.none = false;
  68700. body1.touching.up = true;
  68701. body2.touching.none = false;
  68702. body2.touching.down = true;
  68703. }
  68704. }
  68705. // Resets the overlapY to zero if there is no overlap, or to the actual pixel value if there is
  68706. body1.overlapY = overlap;
  68707. body2.overlapY = overlap;
  68708. return overlap;
  68709. },
  68710. /**
  68711. * The core separation function to separate two physics bodies on the x axis.
  68712. *
  68713. * @method Phaser.Physics.Arcade#separateX
  68714. * @private
  68715. * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate.
  68716. * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate.
  68717. * @param {boolean} overlapOnly - If true the bodies will only have their overlap data set, no separation or exchange of velocity will take place.
  68718. * @return {boolean} Returns true if the bodies were separated or overlap, otherwise false.
  68719. */
  68720. separateX: function (body1, body2, overlapOnly) {
  68721. var overlap = this.getOverlapX(body1, body2);
  68722. // Can't separate two immovable bodies, or a body with its own custom separation logic
  68723. if (overlapOnly || overlap === 0 || (body1.immovable && body2.immovable) || body1.customSeparateX || body2.customSeparateX)
  68724. {
  68725. // return true if there was some overlap, otherwise false
  68726. return (overlap !== 0);
  68727. }
  68728. // Adjust their positions and velocities accordingly (if there was any overlap)
  68729. var v1 = body1.velocity.x;
  68730. var v2 = body2.velocity.x;
  68731. if (!body1.immovable && !body2.immovable)
  68732. {
  68733. overlap *= 0.5;
  68734. body1.x -= overlap;
  68735. body2.x += overlap;
  68736. var nv1 = Math.sqrt((v2 * v2 * body2.mass) / body1.mass) * ((v2 > 0) ? 1 : -1);
  68737. var nv2 = Math.sqrt((v1 * v1 * body1.mass) / body2.mass) * ((v1 > 0) ? 1 : -1);
  68738. var avg = (nv1 + nv2) * 0.5;
  68739. nv1 -= avg;
  68740. nv2 -= avg;
  68741. body1.velocity.x = avg + nv1 * body1.bounce.x;
  68742. body2.velocity.x = avg + nv2 * body2.bounce.x;
  68743. }
  68744. else if (!body1.immovable)
  68745. {
  68746. body1.x -= overlap;
  68747. body1.velocity.x = v2 - v1 * body1.bounce.x;
  68748. // This is special case code that handles things like vertically moving platforms you can ride
  68749. if (body2.moves)
  68750. {
  68751. body1.y += (body2.y - body2.prev.y) * body2.friction.y;
  68752. }
  68753. }
  68754. else
  68755. {
  68756. body2.x += overlap;
  68757. body2.velocity.x = v1 - v2 * body2.bounce.x;
  68758. // This is special case code that handles things like vertically moving platforms you can ride
  68759. if (body1.moves)
  68760. {
  68761. body2.y += (body1.y - body1.prev.y) * body1.friction.y;
  68762. }
  68763. }
  68764. // If we got this far then there WAS overlap, and separation is complete, so return true
  68765. return true;
  68766. },
  68767. /**
  68768. * The core separation function to separate two physics bodies on the y axis.
  68769. *
  68770. * @private
  68771. * @method Phaser.Physics.Arcade#separateY
  68772. * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate.
  68773. * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate.
  68774. * @param {boolean} overlapOnly - If true the bodies will only have their overlap data set, no separation or exchange of velocity will take place.
  68775. * @return {boolean} Returns true if the bodies were separated or overlap, otherwise false.
  68776. */
  68777. separateY: function (body1, body2, overlapOnly) {
  68778. var overlap = this.getOverlapY(body1, body2);
  68779. // Can't separate two immovable bodies, or a body with its own custom separation logic
  68780. if (overlapOnly || overlap === 0 || (body1.immovable && body2.immovable) || body1.customSeparateY || body2.customSeparateY)
  68781. {
  68782. // return true if there was some overlap, otherwise false
  68783. return (overlap !== 0);
  68784. }
  68785. // Adjust their positions and velocities accordingly (if there was any overlap)
  68786. var v1 = body1.velocity.y;
  68787. var v2 = body2.velocity.y;
  68788. if (!body1.immovable && !body2.immovable)
  68789. {
  68790. overlap *= 0.5;
  68791. body1.y -= overlap;
  68792. body2.y += overlap;
  68793. var nv1 = Math.sqrt((v2 * v2 * body2.mass) / body1.mass) * ((v2 > 0) ? 1 : -1);
  68794. var nv2 = Math.sqrt((v1 * v1 * body1.mass) / body2.mass) * ((v1 > 0) ? 1 : -1);
  68795. var avg = (nv1 + nv2) * 0.5;
  68796. nv1 -= avg;
  68797. nv2 -= avg;
  68798. body1.velocity.y = avg + nv1 * body1.bounce.y;
  68799. body2.velocity.y = avg + nv2 * body2.bounce.y;
  68800. }
  68801. else if (!body1.immovable)
  68802. {
  68803. body1.y -= overlap;
  68804. body1.velocity.y = v2 - v1 * body1.bounce.y;
  68805. // This is special case code that handles things like horizontal moving platforms you can ride
  68806. if (body2.moves)
  68807. {
  68808. body1.x += (body2.x - body2.prev.x) * body2.friction.x;
  68809. }
  68810. }
  68811. else
  68812. {
  68813. body2.y += overlap;
  68814. body2.velocity.y = v1 - v2 * body2.bounce.y;
  68815. // This is special case code that handles things like horizontal moving platforms you can ride
  68816. if (body1.moves)
  68817. {
  68818. body2.x += (body1.x - body1.prev.x) * body1.friction.x;
  68819. }
  68820. }
  68821. // If we got this far then there WAS overlap, and separation is complete, so return true
  68822. return true;
  68823. },
  68824. /**
  68825. * Given a Group and a Pointer this will check to see which Group children overlap with the Pointer coordinates.
  68826. * Each child will be sent to the given callback for further processing.
  68827. * Note that the children are not checked for depth order, but simply if they overlap the Pointer or not.
  68828. *
  68829. * @method Phaser.Physics.Arcade#getObjectsUnderPointer
  68830. * @param {Phaser.Pointer} pointer - The Pointer to check.
  68831. * @param {Phaser.Group} group - The Group to check.
  68832. * @param {function} [callback] - A callback function that is called if the object overlaps with the Pointer. The callback will be sent two parameters: the Pointer and the Object that overlapped with it.
  68833. * @param {object} [callbackContext] - The context in which to run the callback.
  68834. * @return {PIXI.DisplayObject[]} An array of the Sprites from the Group that overlapped the Pointer coordinates.
  68835. */
  68836. getObjectsUnderPointer: function (pointer, group, callback, callbackContext) {
  68837. if (group.length === 0 || !pointer.exists)
  68838. {
  68839. return;
  68840. }
  68841. return this.getObjectsAtLocation(pointer.x, pointer.y, group, callback, callbackContext, pointer);
  68842. },
  68843. /**
  68844. * Given a Group and a location this will check to see which Group children overlap with the coordinates.
  68845. * Each child will be sent to the given callback for further processing.
  68846. * Note that the children are not checked for depth order, but simply if they overlap the coordinate or not.
  68847. *
  68848. * @method Phaser.Physics.Arcade#getObjectsAtLocation
  68849. * @param {number} x - The x coordinate to check.
  68850. * @param {number} y - The y coordinate to check.
  68851. * @param {Phaser.Group} group - The Group to check.
  68852. * @param {function} [callback] - A callback function that is called if the object overlaps the coordinates. The callback will be sent two parameters: the callbackArg and the Object that overlapped the location.
  68853. * @param {object} [callbackContext] - The context in which to run the callback.
  68854. * @param {object} [callbackArg] - An argument to pass to the callback.
  68855. * @return {PIXI.DisplayObject[]} An array of the Sprites from the Group that overlapped the coordinates.
  68856. */
  68857. getObjectsAtLocation: function (x, y, group, callback, callbackContext, callbackArg) {
  68858. this.quadTree.clear();
  68859. this.quadTree.reset(this.game.world.bounds.x, this.game.world.bounds.y, this.game.world.bounds.width, this.game.world.bounds.height, this.maxObjects, this.maxLevels);
  68860. this.quadTree.populate(group);
  68861. var rect = new Phaser.Rectangle(x, y, 1, 1);
  68862. var output = [];
  68863. var items = this.quadTree.retrieve(rect);
  68864. for (var i = 0; i < items.length; i++)
  68865. {
  68866. if (items[i].hitTest(x, y))
  68867. {
  68868. if (callback)
  68869. {
  68870. callback.call(callbackContext, callbackArg, items[i].sprite);
  68871. }
  68872. output.push(items[i].sprite);
  68873. }
  68874. }
  68875. return output;
  68876. },
  68877. /**
  68878. * Move the given display object towards the destination object at a steady velocity.
  68879. * If you specify a maxTime then it will adjust the speed (overwriting what you set) so it arrives at the destination in that number of seconds.
  68880. * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms.
  68881. * 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.
  68882. * Note: The display object doesn't stop moving once it reaches the destination coordinates.
  68883. * 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)
  68884. *
  68885. * @method Phaser.Physics.Arcade#moveToObject
  68886. * @param {any} displayObject - The display object to move.
  68887. * @param {any} destination - The display object to move towards. Can be any object but must have visible x/y properties.
  68888. * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec)
  68889. * @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.
  68890. * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity.
  68891. */
  68892. moveToObject: function (displayObject, destination, speed, maxTime) {
  68893. if (speed === undefined) { speed = 60; }
  68894. if (maxTime === undefined) { maxTime = 0; }
  68895. var angle = Math.atan2(destination.y - displayObject.y, destination.x - displayObject.x);
  68896. if (maxTime > 0)
  68897. {
  68898. // We know how many pixels we need to move, but how fast?
  68899. speed = this.distanceBetween(displayObject, destination) / (maxTime / 1000);
  68900. }
  68901. displayObject.body.velocity.x = Math.cos(angle) * speed;
  68902. displayObject.body.velocity.y = Math.sin(angle) * speed;
  68903. return angle;
  68904. },
  68905. /**
  68906. * Move the given display object towards the pointer at a steady velocity. If no pointer is given it will use Phaser.Input.activePointer.
  68907. * 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.
  68908. * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms.
  68909. * 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.
  68910. * Note: The display object doesn't stop moving once it reaches the destination coordinates.
  68911. *
  68912. * @method Phaser.Physics.Arcade#moveToPointer
  68913. * @param {any} displayObject - The display object to move.
  68914. * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec)
  68915. * @param {Phaser.Pointer} [pointer] - The pointer to move towards. Defaults to Phaser.Input.activePointer.
  68916. * @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.
  68917. * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity.
  68918. */
  68919. moveToPointer: function (displayObject, speed, pointer, maxTime) {
  68920. if (speed === undefined) { speed = 60; }
  68921. pointer = pointer || this.game.input.activePointer;
  68922. if (maxTime === undefined) { maxTime = 0; }
  68923. var angle = this.angleToPointer(displayObject, pointer);
  68924. if (maxTime > 0)
  68925. {
  68926. // We know how many pixels we need to move, but how fast?
  68927. speed = this.distanceToPointer(displayObject, pointer) / (maxTime / 1000);
  68928. }
  68929. displayObject.body.velocity.x = Math.cos(angle) * speed;
  68930. displayObject.body.velocity.y = Math.sin(angle) * speed;
  68931. return angle;
  68932. },
  68933. /**
  68934. * Move the given display object towards the x/y coordinates at a steady velocity.
  68935. * 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.
  68936. * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms.
  68937. * 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.
  68938. * Note: The display object doesn't stop moving once it reaches the destination coordinates.
  68939. * 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)
  68940. *
  68941. * @method Phaser.Physics.Arcade#moveToXY
  68942. * @param {any} displayObject - The display object to move.
  68943. * @param {number} x - The x coordinate to move towards.
  68944. * @param {number} y - The y coordinate to move towards.
  68945. * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec)
  68946. * @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.
  68947. * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity.
  68948. */
  68949. moveToXY: function (displayObject, x, y, speed, maxTime) {
  68950. if (speed === undefined) { speed = 60; }
  68951. if (maxTime === undefined) { maxTime = 0; }
  68952. var angle = Math.atan2(y - displayObject.y, x - displayObject.x);
  68953. if (maxTime > 0)
  68954. {
  68955. // We know how many pixels we need to move, but how fast?
  68956. speed = this.distanceToXY(displayObject, x, y) / (maxTime / 1000);
  68957. }
  68958. displayObject.body.velocity.x = Math.cos(angle) * speed;
  68959. displayObject.body.velocity.y = Math.sin(angle) * speed;
  68960. return angle;
  68961. },
  68962. /**
  68963. * 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.
  68964. * 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.
  68965. *
  68966. * @method Phaser.Physics.Arcade#velocityFromAngle
  68967. * @param {number} angle - The angle in degrees calculated in clockwise positive direction (down = 90 degrees positive, right = 0 degrees positive, up = 90 degrees negative)
  68968. * @param {number} [speed=60] - The speed it will move, in pixels per second sq.
  68969. * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated velocity.
  68970. * @return {Phaser.Point} - A Point where point.x contains the velocity x value and point.y contains the velocity y value.
  68971. */
  68972. velocityFromAngle: function (angle, speed, point) {
  68973. if (speed === undefined) { speed = 60; }
  68974. point = point || new Phaser.Point();
  68975. return point.setTo((Math.cos(this.game.math.degToRad(angle)) * speed), (Math.sin(this.game.math.degToRad(angle)) * speed));
  68976. },
  68977. /**
  68978. * 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.
  68979. * 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.
  68980. *
  68981. * @method Phaser.Physics.Arcade#velocityFromRotation
  68982. * @param {number} rotation - The angle in radians.
  68983. * @param {number} [speed=60] - The speed it will move, in pixels per second sq.
  68984. * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated velocity.
  68985. * @return {Phaser.Point} - A Point where point.x contains the velocity x value and point.y contains the velocity y value.
  68986. */
  68987. velocityFromRotation: function (rotation, speed, point) {
  68988. if (speed === undefined) { speed = 60; }
  68989. point = point || new Phaser.Point();
  68990. return point.setTo((Math.cos(rotation) * speed), (Math.sin(rotation) * speed));
  68991. },
  68992. /**
  68993. * 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.
  68994. * One way to use this is: accelerationFromRotation(rotation, 200, sprite.acceleration) which will set the values directly to the sprites acceleration and not create a new Point object.
  68995. *
  68996. * @method Phaser.Physics.Arcade#accelerationFromRotation
  68997. * @param {number} rotation - The angle in radians.
  68998. * @param {number} [speed=60] - The speed it will move, in pixels per second sq.
  68999. * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated acceleration.
  69000. * @return {Phaser.Point} - A Point where point.x contains the acceleration x value and point.y contains the acceleration y value.
  69001. */
  69002. accelerationFromRotation: function (rotation, speed, point) {
  69003. if (speed === undefined) { speed = 60; }
  69004. point = point || new Phaser.Point();
  69005. return point.setTo((Math.cos(rotation) * speed), (Math.sin(rotation) * speed));
  69006. },
  69007. /**
  69008. * 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.)
  69009. * You must give a maximum speed value, beyond which the display object won't go any faster.
  69010. * 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.
  69011. * Note: The display object doesn't stop moving once it reaches the destination coordinates.
  69012. *
  69013. * @method Phaser.Physics.Arcade#accelerateToObject
  69014. * @param {any} displayObject - The display object to move.
  69015. * @param {any} destination - The display object to move towards. Can be any object but must have visible x/y properties.
  69016. * @param {number} [speed=60] - The speed it will accelerate in pixels per second.
  69017. * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach.
  69018. * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach.
  69019. * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory.
  69020. */
  69021. accelerateToObject: function (displayObject, destination, speed, xSpeedMax, ySpeedMax) {
  69022. if (speed === undefined) { speed = 60; }
  69023. if (xSpeedMax === undefined) { xSpeedMax = 1000; }
  69024. if (ySpeedMax === undefined) { ySpeedMax = 1000; }
  69025. var angle = this.angleBetween(displayObject, destination);
  69026. displayObject.body.acceleration.setTo(Math.cos(angle) * speed, Math.sin(angle) * speed);
  69027. displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax);
  69028. return angle;
  69029. },
  69030. /**
  69031. * 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.)
  69032. * You must give a maximum speed value, beyond which the display object won't go any faster.
  69033. * 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.
  69034. * Note: The display object doesn't stop moving once it reaches the destination coordinates.
  69035. *
  69036. * @method Phaser.Physics.Arcade#accelerateToPointer
  69037. * @param {any} displayObject - The display object to move.
  69038. * @param {Phaser.Pointer} [pointer] - The pointer to move towards. Defaults to Phaser.Input.activePointer.
  69039. * @param {number} [speed=60] - The speed it will accelerate in pixels per second.
  69040. * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach.
  69041. * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach.
  69042. * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory.
  69043. */
  69044. accelerateToPointer: function (displayObject, pointer, speed, xSpeedMax, ySpeedMax) {
  69045. if (speed === undefined) { speed = 60; }
  69046. if (pointer === undefined) { pointer = this.game.input.activePointer; }
  69047. if (xSpeedMax === undefined) { xSpeedMax = 1000; }
  69048. if (ySpeedMax === undefined) { ySpeedMax = 1000; }
  69049. var angle = this.angleToPointer(displayObject, pointer);
  69050. displayObject.body.acceleration.setTo(Math.cos(angle) * speed, Math.sin(angle) * speed);
  69051. displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax);
  69052. return angle;
  69053. },
  69054. /**
  69055. * 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.)
  69056. * You must give a maximum speed value, beyond which the display object won't go any faster.
  69057. * 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.
  69058. * Note: The display object doesn't stop moving once it reaches the destination coordinates.
  69059. *
  69060. * @method Phaser.Physics.Arcade#accelerateToXY
  69061. * @param {any} displayObject - The display object to move.
  69062. * @param {number} x - The x coordinate to accelerate towards.
  69063. * @param {number} y - The y coordinate to accelerate towards.
  69064. * @param {number} [speed=60] - The speed it will accelerate in pixels per second.
  69065. * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach.
  69066. * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach.
  69067. * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory.
  69068. */
  69069. accelerateToXY: function (displayObject, x, y, speed, xSpeedMax, ySpeedMax) {
  69070. if (speed === undefined) { speed = 60; }
  69071. if (xSpeedMax === undefined) { xSpeedMax = 1000; }
  69072. if (ySpeedMax === undefined) { ySpeedMax = 1000; }
  69073. var angle = this.angleToXY(displayObject, x, y);
  69074. displayObject.body.acceleration.setTo(Math.cos(angle) * speed, Math.sin(angle) * speed);
  69075. displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax);
  69076. return angle;
  69077. },
  69078. /**
  69079. * Find the distance between two display objects (like Sprites).
  69080. *
  69081. * @method Phaser.Physics.Arcade#distanceBetween
  69082. * @param {any} source - The Display Object to test from.
  69083. * @param {any} target - The Display Object to test to.
  69084. * @return {number} The distance between the source and target objects.
  69085. */
  69086. distanceBetween: function (source, target) {
  69087. var dx = source.x - target.x;
  69088. var dy = source.y - target.y;
  69089. return Math.sqrt(dx * dx + dy * dy);
  69090. },
  69091. /**
  69092. * Find the distance between a display object (like a Sprite) and the given x/y coordinates.
  69093. * The calculation is made from the display objects x/y coordinate. This may be the top-left if its anchor hasn't been changed.
  69094. * If you need to calculate from the center of a display object instead use the method distanceBetweenCenters()
  69095. *
  69096. * @method Phaser.Physics.Arcade#distanceToXY
  69097. * @param {any} displayObject - The Display Object to test from.
  69098. * @param {number} x - The x coordinate to move towards.
  69099. * @param {number} y - The y coordinate to move towards.
  69100. * @return {number} The distance between the object and the x/y coordinates.
  69101. */
  69102. distanceToXY: function (displayObject, x, y) {
  69103. var dx = displayObject.x - x;
  69104. var dy = displayObject.y - y;
  69105. return Math.sqrt(dx * dx + dy * dy);
  69106. },
  69107. /**
  69108. * Find the distance between a display object (like a Sprite) and a Pointer. If no Pointer is given the Input.activePointer is used.
  69109. * The calculation is made from the display objects x/y coordinate. This may be the top-left if its anchor hasn't been changed.
  69110. * If you need to calculate from the center of a display object instead use the method distanceBetweenCenters()
  69111. * The distance to the Pointer is returned in screen space, not world space.
  69112. *
  69113. * @method Phaser.Physics.Arcade#distanceToPointer
  69114. * @param {any} displayObject - The Display Object to test from.
  69115. * @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used.
  69116. * @return {number} The distance between the object and the Pointer.
  69117. */
  69118. distanceToPointer: function (displayObject, pointer) {
  69119. pointer = pointer || this.game.input.activePointer;
  69120. var dx = displayObject.x - pointer.worldX;
  69121. var dy = displayObject.y - pointer.worldY;
  69122. return Math.sqrt(dx * dx + dy * dy);
  69123. },
  69124. /**
  69125. * Find the angle in radians between two display objects (like Sprites).
  69126. *
  69127. * @method Phaser.Physics.Arcade#angleBetween
  69128. * @param {any} source - The Display Object to test from.
  69129. * @param {any} target - The Display Object to test to.
  69130. * @return {number} The angle in radians between the source and target display objects.
  69131. */
  69132. angleBetween: function (source, target) {
  69133. var dx = target.x - source.x;
  69134. var dy = target.y - source.y;
  69135. return Math.atan2(dy, dx);
  69136. },
  69137. /**
  69138. * Find the angle in radians between a display object (like a Sprite) and the given x/y coordinate.
  69139. *
  69140. * @method Phaser.Physics.Arcade#angleToXY
  69141. * @param {any} displayObject - The Display Object to test from.
  69142. * @param {number} x - The x coordinate to get the angle to.
  69143. * @param {number} y - The y coordinate to get the angle to.
  69144. * @return {number} The angle in radians between displayObject.x/y to Pointer.x/y
  69145. */
  69146. angleToXY: function (displayObject, x, y) {
  69147. var dx = x - displayObject.x;
  69148. var dy = y - displayObject.y;
  69149. return Math.atan2(dy, dx);
  69150. },
  69151. /**
  69152. * Find the angle in radians between a display object (like a Sprite) and a Pointer, taking their x/y and center into account.
  69153. *
  69154. * @method Phaser.Physics.Arcade#angleToPointer
  69155. * @param {any} displayObject - The Display Object to test from.
  69156. * @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used.
  69157. * @return {number} The angle in radians between displayObject.x/y to Pointer.x/y
  69158. */
  69159. angleToPointer: function (displayObject, pointer) {
  69160. pointer = pointer || this.game.input.activePointer;
  69161. var dx = pointer.worldX - displayObject.x;
  69162. var dy = pointer.worldY - displayObject.y;
  69163. return Math.atan2(dy, dx);
  69164. },
  69165. /**
  69166. * Find the angle in radians between a display object (like a Sprite) and a Pointer,
  69167. * taking their x/y and center into account relative to the world.
  69168. *
  69169. * @method Phaser.Physics.Arcade#worldAngleToPointer
  69170. * @param {any} displayObject - The DisplayObjerct to test from.
  69171. * @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used.
  69172. * @return {number} The angle in radians between displayObject.world.x/y to Pointer.worldX / worldY
  69173. */
  69174. worldAngleToPointer: function (displayObject, pointer) {
  69175. pointer = pointer || this.game.input.activePointer;
  69176. var dx = pointer.worldX - displayObject.world.x;
  69177. var dy = pointer.worldY - displayObject.world.y;
  69178. return Math.atan2(dy, dx);
  69179. }
  69180. };
  69181. /**
  69182. * @author Richard Davey <rich@photonstorm.com>
  69183. * @copyright 2016 Photon Storm Ltd.
  69184. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  69185. */
  69186. /**
  69187. * The Physics Body is linked to a single Sprite. All physics operations should be performed against the body rather than
  69188. * the Sprite itself. For example you can set the velocity, acceleration, bounce values etc all on the Body.
  69189. *
  69190. * @class Phaser.Physics.Arcade.Body
  69191. * @constructor
  69192. * @param {Phaser.Sprite} sprite - The Sprite object this physics body belongs to.
  69193. */
  69194. Phaser.Physics.Arcade.Body = function (sprite) {
  69195. /**
  69196. * @property {Phaser.Sprite} sprite - Reference to the parent Sprite.
  69197. */
  69198. this.sprite = sprite;
  69199. /**
  69200. * @property {Phaser.Game} game - Local reference to game.
  69201. */
  69202. this.game = sprite.game;
  69203. /**
  69204. * @property {number} type - The type of physics system this body belongs to.
  69205. */
  69206. this.type = Phaser.Physics.ARCADE;
  69207. /**
  69208. * @property {boolean} enable - A disabled body won't be checked for any form of collision or overlap or have its pre/post updates run.
  69209. * @default
  69210. */
  69211. this.enable = true;
  69212. /**
  69213. * @property {Phaser.Point} offset - The offset of the Physics Body from the Sprite x/y position.
  69214. */
  69215. this.offset = new Phaser.Point();
  69216. /**
  69217. * @property {Phaser.Point} position - The position of the physics body.
  69218. * @readonly
  69219. */
  69220. this.position = new Phaser.Point(sprite.x, sprite.y);
  69221. /**
  69222. * @property {Phaser.Point} prev - The previous position of the physics body.
  69223. * @readonly
  69224. */
  69225. this.prev = new Phaser.Point(this.position.x, this.position.y);
  69226. /**
  69227. * @property {boolean} allowRotation - Allow this Body to be rotated? (via angularVelocity, etc)
  69228. * @default
  69229. */
  69230. this.allowRotation = true;
  69231. /**
  69232. * An Arcade Physics Body can have angularVelocity and angularAcceleration. Please understand that the collision Body
  69233. * itself never rotates, it is always axis-aligned. However these values are passed up to the parent Sprite and updates its rotation.
  69234. * @property {number} rotation
  69235. */
  69236. this.rotation = sprite.rotation;
  69237. /**
  69238. * @property {number} preRotation - The previous rotation of the physics body.
  69239. * @readonly
  69240. */
  69241. this.preRotation = sprite.rotation;
  69242. /**
  69243. * @property {number} width - The calculated width of the physics body.
  69244. * @readonly
  69245. */
  69246. this.width = sprite.width;
  69247. /**
  69248. * @property {number} height - The calculated height of the physics body.
  69249. * @readonly
  69250. */
  69251. this.height = sprite.height;
  69252. /**
  69253. * @property {number} sourceWidth - The un-scaled original size.
  69254. * @readonly
  69255. */
  69256. this.sourceWidth = sprite.width;
  69257. /**
  69258. * @property {number} sourceHeight - The un-scaled original size.
  69259. * @readonly
  69260. */
  69261. this.sourceHeight = sprite.height;
  69262. if (sprite.texture)
  69263. {
  69264. this.sourceWidth = sprite.texture.frame.width;
  69265. this.sourceHeight = sprite.texture.frame.height;
  69266. }
  69267. /**
  69268. * @property {number} halfWidth - The calculated width / 2 of the physics body.
  69269. * @readonly
  69270. */
  69271. this.halfWidth = Math.abs(sprite.width / 2);
  69272. /**
  69273. * @property {number} halfHeight - The calculated height / 2 of the physics body.
  69274. * @readonly
  69275. */
  69276. this.halfHeight = Math.abs(sprite.height / 2);
  69277. /**
  69278. * @property {Phaser.Point} center - The center coordinate of the Physics Body.
  69279. * @readonly
  69280. */
  69281. this.center = new Phaser.Point(sprite.x + this.halfWidth, sprite.y + this.halfHeight);
  69282. /**
  69283. * @property {Phaser.Point} velocity - The velocity, or rate of change in speed of the Body. Measured in pixels per second.
  69284. */
  69285. this.velocity = new Phaser.Point();
  69286. /**
  69287. * @property {Phaser.Point} newVelocity - The new velocity. Calculated during the Body.preUpdate and applied to its position.
  69288. * @readonly
  69289. */
  69290. this.newVelocity = new Phaser.Point(0, 0);
  69291. /**
  69292. * @property {Phaser.Point} deltaMax - The Sprite position is updated based on the delta x/y values. You can set a cap on those (both +-) using deltaMax.
  69293. */
  69294. this.deltaMax = new Phaser.Point(0, 0);
  69295. /**
  69296. * @property {Phaser.Point} acceleration - The acceleration is the rate of change of the velocity. Measured in pixels per second squared.
  69297. */
  69298. this.acceleration = new Phaser.Point();
  69299. /**
  69300. * @property {Phaser.Point} drag - The drag applied to the motion of the Body.
  69301. */
  69302. this.drag = new Phaser.Point();
  69303. /**
  69304. * @property {boolean} allowGravity - Allow this Body to be influenced by gravity? Either world or local.
  69305. * @default
  69306. */
  69307. this.allowGravity = true;
  69308. /**
  69309. * @property {Phaser.Point} gravity - A local gravity applied to this Body. If non-zero this over rides any world gravity, unless Body.allowGravity is set to false.
  69310. */
  69311. this.gravity = new Phaser.Point(0, 0);
  69312. /**
  69313. * @property {Phaser.Point} bounce - The elasticity of the Body when colliding. bounce.x/y = 1 means full rebound, bounce.x/y = 0.5 means 50% rebound velocity.
  69314. */
  69315. this.bounce = new Phaser.Point();
  69316. /**
  69317. * @property {Phaser.Point} maxVelocity - The maximum velocity in pixels per second sq. that the Body can reach.
  69318. * @default
  69319. */
  69320. this.maxVelocity = new Phaser.Point(10000, 10000);
  69321. /**
  69322. * @property {Phaser.Point} friction - The amount of movement that will occur if another object 'rides' this one.
  69323. */
  69324. this.friction = new Phaser.Point(1, 0);
  69325. /**
  69326. * @property {number} angularVelocity - The angular velocity controls the rotation speed of the Body. It is measured in radians per second.
  69327. * @default
  69328. */
  69329. this.angularVelocity = 0;
  69330. /**
  69331. * @property {number} angularAcceleration - The angular acceleration is the rate of change of the angular velocity. Measured in radians per second squared.
  69332. * @default
  69333. */
  69334. this.angularAcceleration = 0;
  69335. /**
  69336. * @property {number} angularDrag - The drag applied during the rotation of the Body.
  69337. * @default
  69338. */
  69339. this.angularDrag = 0;
  69340. /**
  69341. * @property {number} maxAngular - The maximum angular velocity in radians per second that the Body can reach.
  69342. * @default
  69343. */
  69344. this.maxAngular = 1000;
  69345. /**
  69346. * @property {number} mass - The mass of the Body. When two bodies collide their mass is used in the calculation to determine the exchange of velocity.
  69347. * @default
  69348. */
  69349. this.mass = 1;
  69350. /**
  69351. * @property {number} angle - The angle of the Body in radians, as calculated by its angularVelocity.
  69352. * @readonly
  69353. */
  69354. this.angle = 0;
  69355. /**
  69356. * @property {number} speed - The speed of the Body as calculated by its velocity.
  69357. * @readonly
  69358. */
  69359. this.speed = 0;
  69360. /**
  69361. * @property {number} facing - A const reference to the direction the Body is traveling or facing.
  69362. * @default
  69363. */
  69364. this.facing = Phaser.NONE;
  69365. /**
  69366. * @property {boolean} immovable - An immovable Body will not receive any impacts from other bodies.
  69367. * @default
  69368. */
  69369. this.immovable = false;
  69370. /**
  69371. * If you have a Body that is being moved around the world via a tween or a Group motion, but its local x/y position never
  69372. * actually changes, then you should set Body.moves = false. Otherwise it will most likely fly off the screen.
  69373. * If you want the physics system to move the body around, then set moves to true.
  69374. * @property {boolean} moves - Set to true to allow the Physics system to move this Body, otherwise false to move it manually.
  69375. * @default
  69376. */
  69377. this.moves = true;
  69378. /**
  69379. * This flag allows you to disable the custom x separation that takes place by Physics.Arcade.separate.
  69380. * Used in combination with your own collision processHandler you can create whatever type of collision response you need.
  69381. * @property {boolean} customSeparateX - Use a custom separation system or the built-in one?
  69382. * @default
  69383. */
  69384. this.customSeparateX = false;
  69385. /**
  69386. * This flag allows you to disable the custom y separation that takes place by Physics.Arcade.separate.
  69387. * Used in combination with your own collision processHandler you can create whatever type of collision response you need.
  69388. * @property {boolean} customSeparateY - Use a custom separation system or the built-in one?
  69389. * @default
  69390. */
  69391. this.customSeparateY = false;
  69392. /**
  69393. * When this body collides with another, the amount of overlap is stored here.
  69394. * @property {number} overlapX - The amount of horizontal overlap during the collision.
  69395. */
  69396. this.overlapX = 0;
  69397. /**
  69398. * When this body collides with another, the amount of overlap is stored here.
  69399. * @property {number} overlapY - The amount of vertical overlap during the collision.
  69400. */
  69401. this.overlapY = 0;
  69402. /**
  69403. * 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.
  69404. * @property {boolean} embedded - Body embed value.
  69405. */
  69406. this.embedded = false;
  69407. /**
  69408. * 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.
  69409. * @property {boolean} collideWorldBounds - Should the Body collide with the World bounds?
  69410. */
  69411. this.collideWorldBounds = false;
  69412. /**
  69413. * Set the checkCollision properties to control which directions collision is processed for this Body.
  69414. * For example checkCollision.up = false means it won't collide when the collision happened while moving up.
  69415. * @property {object} checkCollision - An object containing allowed collision.
  69416. */
  69417. this.checkCollision = { none: false, any: true, up: true, down: true, left: true, right: true };
  69418. /**
  69419. * This object is populated with boolean values when the Body collides with another.
  69420. * touching.up = true means the collision happened to the top of this Body for example.
  69421. * @property {object} touching - An object containing touching results.
  69422. */
  69423. this.touching = { none: true, up: false, down: false, left: false, right: false };
  69424. /**
  69425. * This object is populated with previous touching values from the bodies previous collision.
  69426. * @property {object} wasTouching - An object containing previous touching results.
  69427. */
  69428. this.wasTouching = { none: true, up: false, down: false, left: false, right: false };
  69429. /**
  69430. * This object is populated with boolean values when the Body collides with the World bounds or a Tile.
  69431. * For example if blocked.up is true then the Body cannot move up.
  69432. * @property {object} blocked - An object containing on which faces this Body is blocked from moving, if any.
  69433. */
  69434. this.blocked = { up: false, down: false, left: false, right: false };
  69435. /**
  69436. * If this is an especially small or fast moving object then it can sometimes skip over tilemap collisions if it moves through a tile in a step.
  69437. * Set this padding value to add extra padding to its bounds. tilePadding.x applied to its width, y to its height.
  69438. * @property {Phaser.Point} tilePadding - Extra padding to be added to this sprite's dimensions when checking for tile collision.
  69439. */
  69440. this.tilePadding = new Phaser.Point();
  69441. /**
  69442. * @property {boolean} dirty - If this Body in a preUpdate (true) or postUpdate (false) state?
  69443. */
  69444. this.dirty = false;
  69445. /**
  69446. * @property {boolean} skipQuadTree - If true and you collide this Sprite against a Group, it will disable the collision check from using a QuadTree.
  69447. */
  69448. this.skipQuadTree = false;
  69449. /**
  69450. * If true the Body will check itself against the Sprite.getBounds() dimensions and adjust its width and height accordingly.
  69451. * If false it will compare its dimensions against the Sprite scale instead, and adjust its width height if the scale has changed.
  69452. * Typically you would need to enable syncBounds if your sprite is the child of a responsive display object such as a FlexLayer,
  69453. * or in any situation where the Sprite scale doesn't change, but its parents scale is effecting the dimensions regardless.
  69454. * @property {boolean} syncBounds
  69455. * @default
  69456. */
  69457. this.syncBounds = false;
  69458. /**
  69459. * @property {boolean} _reset - Internal cache var.
  69460. * @private
  69461. */
  69462. this._reset = true;
  69463. /**
  69464. * @property {number} _sx - Internal cache var.
  69465. * @private
  69466. */
  69467. this._sx = sprite.scale.x;
  69468. /**
  69469. * @property {number} _sy - Internal cache var.
  69470. * @private
  69471. */
  69472. this._sy = sprite.scale.y;
  69473. /**
  69474. * @property {number} _dx - Internal cache var.
  69475. * @private
  69476. */
  69477. this._dx = 0;
  69478. /**
  69479. * @property {number} _dy - Internal cache var.
  69480. * @private
  69481. */
  69482. this._dy = 0;
  69483. };
  69484. Phaser.Physics.Arcade.Body.prototype = {
  69485. /**
  69486. * Internal method.
  69487. *
  69488. * @method Phaser.Physics.Arcade.Body#updateBounds
  69489. * @protected
  69490. */
  69491. updateBounds: function () {
  69492. if (this.syncBounds)
  69493. {
  69494. var b = this.sprite.getBounds();
  69495. b.ceilAll();
  69496. if (b.width !== this.width || b.height !== this.height)
  69497. {
  69498. this.width = b.width;
  69499. this.height = b.height;
  69500. this._reset = true;
  69501. }
  69502. }
  69503. else
  69504. {
  69505. var asx = Math.abs(this.sprite.scale.x);
  69506. var asy = Math.abs(this.sprite.scale.y);
  69507. if (asx !== this._sx || asy !== this._sy)
  69508. {
  69509. this.width = this.sourceWidth * asx;
  69510. this.height = this.sourceHeight * asy;
  69511. this._sx = asx;
  69512. this._sy = asy;
  69513. this._reset = true;
  69514. }
  69515. }
  69516. if (this._reset)
  69517. {
  69518. this.halfWidth = Math.floor(this.width / 2);
  69519. this.halfHeight = Math.floor(this.height / 2);
  69520. this.center.setTo(this.position.x + this.halfWidth, this.position.y + this.halfHeight);
  69521. }
  69522. },
  69523. /**
  69524. * Internal method.
  69525. *
  69526. * @method Phaser.Physics.Arcade.Body#preUpdate
  69527. * @protected
  69528. */
  69529. preUpdate: function () {
  69530. if (!this.enable || this.game.physics.arcade.isPaused)
  69531. {
  69532. return;
  69533. }
  69534. this.dirty = true;
  69535. // Store and reset collision flags
  69536. this.wasTouching.none = this.touching.none;
  69537. this.wasTouching.up = this.touching.up;
  69538. this.wasTouching.down = this.touching.down;
  69539. this.wasTouching.left = this.touching.left;
  69540. this.wasTouching.right = this.touching.right;
  69541. this.touching.none = true;
  69542. this.touching.up = false;
  69543. this.touching.down = false;
  69544. this.touching.left = false;
  69545. this.touching.right = false;
  69546. this.blocked.up = false;
  69547. this.blocked.down = false;
  69548. this.blocked.left = false;
  69549. this.blocked.right = false;
  69550. this.embedded = false;
  69551. this.updateBounds();
  69552. this.position.x = (this.sprite.world.x - (this.sprite.anchor.x * this.width)) + this.offset.x;
  69553. this.position.y = (this.sprite.world.y - (this.sprite.anchor.y * this.height)) + this.offset.y;
  69554. this.rotation = this.sprite.angle;
  69555. this.preRotation = this.rotation;
  69556. if (this._reset || this.sprite.fresh)
  69557. {
  69558. this.prev.x = this.position.x;
  69559. this.prev.y = this.position.y;
  69560. }
  69561. if (this.moves)
  69562. {
  69563. this.game.physics.arcade.updateMotion(this);
  69564. this.newVelocity.set(this.velocity.x * this.game.time.physicsElapsed, this.velocity.y * this.game.time.physicsElapsed);
  69565. this.position.x += this.newVelocity.x;
  69566. this.position.y += this.newVelocity.y;
  69567. if (this.position.x !== this.prev.x || this.position.y !== this.prev.y)
  69568. {
  69569. this.angle = Math.atan2(this.velocity.y, this.velocity.x);
  69570. }
  69571. this.speed = Math.sqrt(this.velocity.x * this.velocity.x + this.velocity.y * this.velocity.y);
  69572. // Now the State update will throw collision checks at the Body
  69573. // And finally we'll integrate the new position back to the Sprite in postUpdate
  69574. if (this.collideWorldBounds)
  69575. {
  69576. this.checkWorldBounds();
  69577. }
  69578. }
  69579. this._dx = this.deltaX();
  69580. this._dy = this.deltaY();
  69581. this._reset = false;
  69582. },
  69583. /**
  69584. * Internal method.
  69585. *
  69586. * @method Phaser.Physics.Arcade.Body#postUpdate
  69587. * @protected
  69588. */
  69589. postUpdate: function () {
  69590. // Only allow postUpdate to be called once per frame
  69591. if (!this.enable || !this.dirty)
  69592. {
  69593. return;
  69594. }
  69595. this.dirty = false;
  69596. if (this.deltaX() < 0)
  69597. {
  69598. this.facing = Phaser.LEFT;
  69599. }
  69600. else if (this.deltaX() > 0)
  69601. {
  69602. this.facing = Phaser.RIGHT;
  69603. }
  69604. if (this.deltaY() < 0)
  69605. {
  69606. this.facing = Phaser.UP;
  69607. }
  69608. else if (this.deltaY() > 0)
  69609. {
  69610. this.facing = Phaser.DOWN;
  69611. }
  69612. if (this.moves)
  69613. {
  69614. this._dx = this.deltaX();
  69615. this._dy = this.deltaY();
  69616. if (this.deltaMax.x !== 0 && this._dx !== 0)
  69617. {
  69618. if (this._dx < 0 && this._dx < -this.deltaMax.x)
  69619. {
  69620. this._dx = -this.deltaMax.x;
  69621. }
  69622. else if (this._dx > 0 && this._dx > this.deltaMax.x)
  69623. {
  69624. this._dx = this.deltaMax.x;
  69625. }
  69626. }
  69627. if (this.deltaMax.y !== 0 && this._dy !== 0)
  69628. {
  69629. if (this._dy < 0 && this._dy < -this.deltaMax.y)
  69630. {
  69631. this._dy = -this.deltaMax.y;
  69632. }
  69633. else if (this._dy > 0 && this._dy > this.deltaMax.y)
  69634. {
  69635. this._dy = this.deltaMax.y;
  69636. }
  69637. }
  69638. this.sprite.position.x += this._dx;
  69639. this.sprite.position.y += this._dy;
  69640. this._reset = true;
  69641. }
  69642. this.center.setTo(this.position.x + this.halfWidth, this.position.y + this.halfHeight);
  69643. if (this.allowRotation)
  69644. {
  69645. this.sprite.angle += this.deltaZ();
  69646. }
  69647. this.prev.x = this.position.x;
  69648. this.prev.y = this.position.y;
  69649. },
  69650. /**
  69651. * Internal method.
  69652. *
  69653. * @method Phaser.Physics.Arcade.Body#checkWorldBounds
  69654. * @protected
  69655. */
  69656. checkWorldBounds: function () {
  69657. var pos = this.position;
  69658. var bounds = this.game.physics.arcade.bounds;
  69659. var check = this.game.physics.arcade.checkCollision;
  69660. if (pos.x < bounds.x && check.left)
  69661. {
  69662. pos.x = bounds.x;
  69663. this.velocity.x *= -this.bounce.x;
  69664. this.blocked.left = true;
  69665. }
  69666. else if (this.right > bounds.right && check.right)
  69667. {
  69668. pos.x = bounds.right - this.width;
  69669. this.velocity.x *= -this.bounce.x;
  69670. this.blocked.right = true;
  69671. }
  69672. if (pos.y < bounds.y && check.up)
  69673. {
  69674. pos.y = bounds.y;
  69675. this.velocity.y *= -this.bounce.y;
  69676. this.blocked.up = true;
  69677. }
  69678. else if (this.bottom > bounds.bottom && check.down)
  69679. {
  69680. pos.y = bounds.bottom - this.height;
  69681. this.velocity.y *= -this.bounce.y;
  69682. this.blocked.down = true;
  69683. }
  69684. },
  69685. /**
  69686. * You can modify the size of the physics Body to be any dimension you need.
  69687. * So it could be smaller or larger than the parent Sprite. You can also control the x and y offset, which
  69688. * is the position of the Body relative to the top-left of the Sprite.
  69689. *
  69690. * Calling `setSize` will have no effect if you have previously used `Body.setCircle`. To change a collision
  69691. * circle use `setCircle` instead.
  69692. *
  69693. * @method Phaser.Physics.Arcade.Body#setSize
  69694. * @param {number} width - The width of the Body.
  69695. * @param {number} height - The height of the Body.
  69696. * @param {number} [offsetX] - The X offset of the Body from the Sprite position.
  69697. * @param {number} [offsetY] - The Y offset of the Body from the Sprite position.
  69698. */
  69699. setSize: function (width, height, offsetX, offsetY) {
  69700. if (this.isCircle)
  69701. {
  69702. return;
  69703. }
  69704. if (offsetX === undefined) { offsetX = this.offset.x; }
  69705. if (offsetY === undefined) { offsetY = this.offset.y; }
  69706. this.sourceWidth = width;
  69707. this.sourceHeight = height;
  69708. this.width = this.sourceWidth * this._sx;
  69709. this.height = this.sourceHeight * this._sy;
  69710. this.halfWidth = Math.floor(this.width / 2);
  69711. this.halfHeight = Math.floor(this.height / 2);
  69712. this.offset.setTo(offsetX, offsetY);
  69713. this.center.setTo(this.position.x + this.halfWidth, this.position.y + this.halfHeight);
  69714. },
  69715. /**
  69716. * Sets this Body as using a circle, of the given radius, for all collision detection instead of a rectangle.
  69717. * The radius is given in pixels and is the distance from the center of the circle to the edge.
  69718. *
  69719. * You can also control the x and y offset, which is the position of the Body relative to the top-left of the Sprite.
  69720. *
  69721. * @method Phaser.Physics.Arcade.Body#setCircle
  69722. * @param {number} [radius] - The radius of the Body in pixels. Pass a value of zero / undefined, to stop the Body using a circle for collision.
  69723. * @param {number} [offsetX] - The X offset of the Body from the Sprite position.
  69724. * @param {number} [offsetY] - The Y offset of the Body from the Sprite position.
  69725. */
  69726. setCircle: function (radius, offsetX, offsetY) {
  69727. if (offsetX === undefined) { offsetX = this.offset.x; }
  69728. if (offsetY === undefined) { offsetY = this.offset.y; }
  69729. if (radius > 0)
  69730. {
  69731. this.isCircle = true;
  69732. this.radius = radius;
  69733. this.sourceWidth = radius * 2;
  69734. this.sourceHeight = radius * 2;
  69735. this.width = this.sourceWidth * this._sx;
  69736. this.height = this.sourceHeight * this._sy;
  69737. this.halfWidth = Math.floor(this.width / 2);
  69738. this.halfHeight = Math.floor(this.height / 2);
  69739. this.offset.setTo(offsetX, offsetY);
  69740. this.center.setTo(this.position.x + this.halfWidth, this.position.y + this.halfHeight);
  69741. }
  69742. else
  69743. {
  69744. this.isCircle = false;
  69745. }
  69746. },
  69747. /**
  69748. * Resets all Body values (velocity, acceleration, rotation, etc)
  69749. *
  69750. * @method Phaser.Physics.Arcade.Body#reset
  69751. * @param {number} x - The new x position of the Body.
  69752. * @param {number} y - The new y position of the Body.
  69753. */
  69754. reset: function (x, y) {
  69755. this.velocity.set(0);
  69756. this.acceleration.set(0);
  69757. this.speed = 0;
  69758. this.angularVelocity = 0;
  69759. this.angularAcceleration = 0;
  69760. this.position.x = (x - (this.sprite.anchor.x * this.width)) + this.offset.x;
  69761. this.position.y = (y - (this.sprite.anchor.y * this.height)) + this.offset.y;
  69762. this.prev.x = this.position.x;
  69763. this.prev.y = this.position.y;
  69764. this.rotation = this.sprite.angle;
  69765. this.preRotation = this.rotation;
  69766. this._sx = this.sprite.scale.x;
  69767. this._sy = this.sprite.scale.y;
  69768. this.center.setTo(this.position.x + this.halfWidth, this.position.y + this.halfHeight);
  69769. },
  69770. /**
  69771. * Tests if a world point lies within this Body.
  69772. *
  69773. * @method Phaser.Physics.Arcade.Body#hitTest
  69774. * @param {number} x - The world x coordinate to test.
  69775. * @param {number} y - The world y coordinate to test.
  69776. * @return {boolean} True if the given coordinates are inside this Body, otherwise false.
  69777. */
  69778. hitTest: function (x, y) {
  69779. return (this.isCircle) ? Phaser.Circle.contains(this, x, y) : Phaser.Rectangle.contains(this, x, y);
  69780. },
  69781. /**
  69782. * Returns true if the bottom of this Body is in contact with either the world bounds or a tile.
  69783. *
  69784. * @method Phaser.Physics.Arcade.Body#onFloor
  69785. * @return {boolean} True if in contact with either the world bounds or a tile.
  69786. */
  69787. onFloor: function () {
  69788. return this.blocked.down;
  69789. },
  69790. /**
  69791. * Returns true if the top of this Body is in contact with either the world bounds or a tile.
  69792. *
  69793. * @method Phaser.Physics.Arcade.Body#onTop
  69794. * @return {boolean} True if in contact with either the world bounds or a tile.
  69795. */
  69796. onCeiling: function(){
  69797. return this.blocked.up;
  69798. },
  69799. /**
  69800. * Returns true if either side of this Body is in contact with either the world bounds or a tile.
  69801. *
  69802. * @method Phaser.Physics.Arcade.Body#onWall
  69803. * @return {boolean} True if in contact with either the world bounds or a tile.
  69804. */
  69805. onWall: function () {
  69806. return (this.blocked.left || this.blocked.right);
  69807. },
  69808. /**
  69809. * Returns the absolute delta x value.
  69810. *
  69811. * @method Phaser.Physics.Arcade.Body#deltaAbsX
  69812. * @return {number} The absolute delta value.
  69813. */
  69814. deltaAbsX: function () {
  69815. return (this.deltaX() > 0 ? this.deltaX() : -this.deltaX());
  69816. },
  69817. /**
  69818. * Returns the absolute delta y value.
  69819. *
  69820. * @method Phaser.Physics.Arcade.Body#deltaAbsY
  69821. * @return {number} The absolute delta value.
  69822. */
  69823. deltaAbsY: function () {
  69824. return (this.deltaY() > 0 ? this.deltaY() : -this.deltaY());
  69825. },
  69826. /**
  69827. * Returns the delta x value. The difference between Body.x now and in the previous step.
  69828. *
  69829. * @method Phaser.Physics.Arcade.Body#deltaX
  69830. * @return {number} The delta value. Positive if the motion was to the right, negative if to the left.
  69831. */
  69832. deltaX: function () {
  69833. return this.position.x - this.prev.x;
  69834. },
  69835. /**
  69836. * Returns the delta y value. The difference between Body.y now and in the previous step.
  69837. *
  69838. * @method Phaser.Physics.Arcade.Body#deltaY
  69839. * @return {number} The delta value. Positive if the motion was downwards, negative if upwards.
  69840. */
  69841. deltaY: function () {
  69842. return this.position.y - this.prev.y;
  69843. },
  69844. /**
  69845. * Returns the delta z value. The difference between Body.rotation now and in the previous step.
  69846. *
  69847. * @method Phaser.Physics.Arcade.Body#deltaZ
  69848. * @return {number} The delta value. Positive if the motion was clockwise, negative if anti-clockwise.
  69849. */
  69850. deltaZ: function () {
  69851. return this.rotation - this.preRotation;
  69852. },
  69853. /**
  69854. * Destroys this Body.
  69855. *
  69856. * First it calls Group.removeFromHash if the Game Object this Body belongs to is part of a Group.
  69857. * Then it nulls the Game Objects body reference, and nulls this Body.sprite reference.
  69858. *
  69859. * @method Phaser.Physics.Arcade.Body#destroy
  69860. */
  69861. destroy: function () {
  69862. if (this.sprite.parent && this.sprite.parent instanceof Phaser.Group)
  69863. {
  69864. this.sprite.parent.removeFromHash(this.sprite);
  69865. }
  69866. this.sprite.body = null;
  69867. this.sprite = null;
  69868. }
  69869. };
  69870. /**
  69871. * @name Phaser.Physics.Arcade.Body#left
  69872. * @property {number} left - The x position of the Body. The same as `Body.x`.
  69873. */
  69874. Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "left", {
  69875. get: function () {
  69876. return this.position.x;
  69877. }
  69878. });
  69879. /**
  69880. * @name Phaser.Physics.Arcade.Body#right
  69881. * @property {number} right - The right value of this Body (same as Body.x + Body.width)
  69882. * @readonly
  69883. */
  69884. Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "right", {
  69885. get: function () {
  69886. return this.position.x + this.width;
  69887. }
  69888. });
  69889. /**
  69890. * @name Phaser.Physics.Arcade.Body#top
  69891. * @property {number} top - The y position of the Body. The same as `Body.y`.
  69892. */
  69893. Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "top", {
  69894. get: function () {
  69895. return this.position.y;
  69896. }
  69897. });
  69898. /**
  69899. * @name Phaser.Physics.Arcade.Body#bottom
  69900. * @property {number} bottom - The bottom value of this Body (same as Body.y + Body.height)
  69901. * @readonly
  69902. */
  69903. Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "bottom", {
  69904. get: function () {
  69905. return this.position.y + this.height;
  69906. }
  69907. });
  69908. /**
  69909. * @name Phaser.Physics.Arcade.Body#x
  69910. * @property {number} x - The x position.
  69911. */
  69912. Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "x", {
  69913. get: function () {
  69914. return this.position.x;
  69915. },
  69916. set: function (value) {
  69917. this.position.x = value;
  69918. }
  69919. });
  69920. /**
  69921. * @name Phaser.Physics.Arcade.Body#y
  69922. * @property {number} y - The y position.
  69923. */
  69924. Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "y", {
  69925. get: function () {
  69926. return this.position.y;
  69927. },
  69928. set: function (value) {
  69929. this.position.y = value;
  69930. }
  69931. });
  69932. /**
  69933. * Render Sprite Body.
  69934. *
  69935. * @method Phaser.Physics.Arcade.Body#render
  69936. * @param {object} context - The context to render to.
  69937. * @param {Phaser.Physics.Arcade.Body} body - The Body to render the info of.
  69938. * @param {string} [color='rgba(0,255,0,0.4)'] - color of the debug info to be rendered. (format is css color string).
  69939. * @param {boolean} [filled=true] - Render the objected as a filled (default, true) or a stroked (false)
  69940. */
  69941. Phaser.Physics.Arcade.Body.render = function (context, body, color, filled) {
  69942. if (filled === undefined) { filled = true; }
  69943. color = color || 'rgba(0,255,0,0.4)';
  69944. if (filled)
  69945. {
  69946. context.fillStyle = color;
  69947. context.fillRect(body.position.x - body.game.camera.x, body.position.y - body.game.camera.y, body.width, body.height);
  69948. }
  69949. else
  69950. {
  69951. context.strokeStyle = color;
  69952. context.strokeRect(body.position.x - body.game.camera.x, body.position.y - body.game.camera.y, body.width, body.height);
  69953. }
  69954. };
  69955. /**
  69956. * Render Sprite Body Physics Data as text.
  69957. *
  69958. * @method Phaser.Physics.Arcade.Body#renderBodyInfo
  69959. * @param {Phaser.Physics.Arcade.Body} body - The Body to render the info of.
  69960. * @param {number} x - X position of the debug info to be rendered.
  69961. * @param {number} y - Y position of the debug info to be rendered.
  69962. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  69963. */
  69964. Phaser.Physics.Arcade.Body.renderBodyInfo = function (debug, body) {
  69965. debug.line('x: ' + body.x.toFixed(2), 'y: ' + body.y.toFixed(2), 'width: ' + body.width, 'height: ' + body.height);
  69966. debug.line('velocity x: ' + body.velocity.x.toFixed(2), 'y: ' + body.velocity.y.toFixed(2), 'deltaX: ' + body._dx.toFixed(2), 'deltaY: ' + body._dy.toFixed(2));
  69967. debug.line('acceleration x: ' + body.acceleration.x.toFixed(2), 'y: ' + body.acceleration.y.toFixed(2), 'speed: ' + body.speed.toFixed(2), 'angle: ' + body.angle.toFixed(2));
  69968. debug.line('gravity x: ' + body.gravity.x, 'y: ' + body.gravity.y, 'bounce x: ' + body.bounce.x.toFixed(2), 'y: ' + body.bounce.y.toFixed(2));
  69969. debug.line('touching left: ' + body.touching.left, 'right: ' + body.touching.right, 'up: ' + body.touching.up, 'down: ' + body.touching.down);
  69970. debug.line('blocked left: ' + body.blocked.left, 'right: ' + body.blocked.right, 'up: ' + body.blocked.up, 'down: ' + body.blocked.down);
  69971. };
  69972. Phaser.Physics.Arcade.Body.prototype.constructor = Phaser.Physics.Arcade.Body;
  69973. /**
  69974. * @author Richard Davey <rich@photonstorm.com>
  69975. * @copyright 2016 Photon Storm Ltd.
  69976. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  69977. */
  69978. /**
  69979. * The Arcade Physics Tile map collision methods.
  69980. *
  69981. * @class Phaser.Physics.Arcade.TilemapCollision
  69982. * @constructor
  69983. */
  69984. Phaser.Physics.Arcade.TilemapCollision = function () {};
  69985. Phaser.Physics.Arcade.TilemapCollision.prototype = {
  69986. /**
  69987. * @property {number} TILE_BIAS - A value added to the delta values during collision with tiles. Adjust this if you get tunneling.
  69988. */
  69989. TILE_BIAS: 16,
  69990. /**
  69991. * An internal function. Use Phaser.Physics.Arcade.collide instead.
  69992. *
  69993. * @method Phaser.Physics.Arcade#collideSpriteVsTilemapLayer
  69994. * @private
  69995. * @param {Phaser.Sprite} sprite - The sprite to check.
  69996. * @param {Phaser.TilemapLayer} tilemapLayer - The layer to check.
  69997. * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them.
  69998. * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them.
  69999. * @param {object} callbackContext - The context in which to run the callbacks.
  70000. * @param {boolean} overlapOnly - Just run an overlap or a full collision.
  70001. */
  70002. collideSpriteVsTilemapLayer: function (sprite, tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly) {
  70003. if (!sprite.body)
  70004. {
  70005. return;
  70006. }
  70007. var mapData = tilemapLayer.getTiles(
  70008. sprite.body.position.x - sprite.body.tilePadding.x,
  70009. sprite.body.position.y - sprite.body.tilePadding.y,
  70010. sprite.body.width + sprite.body.tilePadding.x,
  70011. sprite.body.height + sprite.body.tilePadding.y,
  70012. false, false);
  70013. if (mapData.length === 0)
  70014. {
  70015. return;
  70016. }
  70017. for (var i = 0; i < mapData.length; i++)
  70018. {
  70019. if (processCallback)
  70020. {
  70021. if (processCallback.call(callbackContext, sprite, mapData[i]))
  70022. {
  70023. if (this.separateTile(i, sprite.body, mapData[i], overlapOnly))
  70024. {
  70025. this._total++;
  70026. if (collideCallback)
  70027. {
  70028. collideCallback.call(callbackContext, sprite, mapData[i]);
  70029. }
  70030. }
  70031. }
  70032. }
  70033. else
  70034. {
  70035. if (this.separateTile(i, sprite.body, mapData[i], overlapOnly))
  70036. {
  70037. this._total++;
  70038. if (collideCallback)
  70039. {
  70040. collideCallback.call(callbackContext, sprite, mapData[i]);
  70041. }
  70042. }
  70043. }
  70044. }
  70045. },
  70046. /**
  70047. * An internal function. Use Phaser.Physics.Arcade.collide instead.
  70048. *
  70049. * @private
  70050. * @method Phaser.Physics.Arcade#collideGroupVsTilemapLayer
  70051. * @param {Phaser.Group} group - The Group to check.
  70052. * @param {Phaser.TilemapLayer} tilemapLayer - The layer to check.
  70053. * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them.
  70054. * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them.
  70055. * @param {object} callbackContext - The context in which to run the callbacks.
  70056. * @param {boolean} overlapOnly - Just run an overlap or a full collision.
  70057. */
  70058. collideGroupVsTilemapLayer: function (group, tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly) {
  70059. if (group.length === 0)
  70060. {
  70061. return;
  70062. }
  70063. for (var i = 0; i < group.children.length; i++)
  70064. {
  70065. if (group.children[i].exists)
  70066. {
  70067. this.collideSpriteVsTilemapLayer(group.children[i], tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly);
  70068. }
  70069. }
  70070. },
  70071. /**
  70072. * The core separation function to separate a physics body and a tile.
  70073. *
  70074. * @private
  70075. * @method Phaser.Physics.Arcade#separateTile
  70076. * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate.
  70077. * @param {Phaser.Tile} tile - The tile to collide against.
  70078. * @return {boolean} Returns true if the body was separated, otherwise false.
  70079. */
  70080. separateTile: function (i, body, tile, overlapOnly) {
  70081. if (!body.enable)
  70082. {
  70083. return false;
  70084. }
  70085. // We re-check for collision in case body was separated in a previous step
  70086. if (!tile.intersects(body.position.x, body.position.y, body.right, body.bottom))
  70087. {
  70088. // no collision so bail out (separated in a previous step)
  70089. return false;
  70090. }
  70091. else if (overlapOnly)
  70092. {
  70093. // There is an overlap, and we don't need to separate. Bail.
  70094. return true;
  70095. }
  70096. // They overlap. Any custom callbacks?
  70097. // A local callback always takes priority over a layer level callback
  70098. if (tile.collisionCallback && !tile.collisionCallback.call(tile.collisionCallbackContext, body.sprite, tile))
  70099. {
  70100. // If it returns true then we can carry on, otherwise we should abort.
  70101. return false;
  70102. }
  70103. else if (tile.layer.callbacks[tile.index] && !tile.layer.callbacks[tile.index].callback.call(tile.layer.callbacks[tile.index].callbackContext, body.sprite, tile))
  70104. {
  70105. // If it returns true then we can carry on, otherwise we should abort.
  70106. return false;
  70107. }
  70108. // We don't need to go any further if this tile doesn't actually separate
  70109. if (!tile.faceLeft && !tile.faceRight && !tile.faceTop && !tile.faceBottom)
  70110. {
  70111. // This could happen if the tile was meant to be collided with re: a callback, but otherwise isn't needed for separation
  70112. return false;
  70113. }
  70114. var ox = 0;
  70115. var oy = 0;
  70116. var minX = 0;
  70117. var minY = 1;
  70118. if (body.deltaAbsX() > body.deltaAbsY())
  70119. {
  70120. // Moving faster horizontally, check X axis first
  70121. minX = -1;
  70122. }
  70123. else if (body.deltaAbsX() < body.deltaAbsY())
  70124. {
  70125. // Moving faster vertically, check Y axis first
  70126. minY = -1;
  70127. }
  70128. if (body.deltaX() !== 0 && body.deltaY() !== 0 && (tile.faceLeft || tile.faceRight) && (tile.faceTop || tile.faceBottom))
  70129. {
  70130. // We only need do this if both axis have checking faces AND we're moving in both directions
  70131. minX = Math.min(Math.abs(body.position.x - tile.right), Math.abs(body.right - tile.left));
  70132. minY = Math.min(Math.abs(body.position.y - tile.bottom), Math.abs(body.bottom - tile.top));
  70133. }
  70134. if (minX < minY)
  70135. {
  70136. if (tile.faceLeft || tile.faceRight)
  70137. {
  70138. ox = this.tileCheckX(body, tile);
  70139. // That's horizontal done, check if we still intersects? If not then we can return now
  70140. if (ox !== 0 && !tile.intersects(body.position.x, body.position.y, body.right, body.bottom))
  70141. {
  70142. return true;
  70143. }
  70144. }
  70145. if (tile.faceTop || tile.faceBottom)
  70146. {
  70147. oy = this.tileCheckY(body, tile);
  70148. }
  70149. }
  70150. else
  70151. {
  70152. if (tile.faceTop || tile.faceBottom)
  70153. {
  70154. oy = this.tileCheckY(body, tile);
  70155. // That's vertical done, check if we still intersects? If not then we can return now
  70156. if (oy !== 0 && !tile.intersects(body.position.x, body.position.y, body.right, body.bottom))
  70157. {
  70158. return true;
  70159. }
  70160. }
  70161. if (tile.faceLeft || tile.faceRight)
  70162. {
  70163. ox = this.tileCheckX(body, tile);
  70164. }
  70165. }
  70166. return (ox !== 0 || oy !== 0);
  70167. },
  70168. /**
  70169. * Check the body against the given tile on the X axis.
  70170. *
  70171. * @private
  70172. * @method Phaser.Physics.Arcade#tileCheckX
  70173. * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate.
  70174. * @param {Phaser.Tile} tile - The tile to check.
  70175. * @return {number} The amount of separation that occurred.
  70176. */
  70177. tileCheckX: function (body, tile) {
  70178. var ox = 0;
  70179. if (body.deltaX() < 0 && !body.blocked.left && tile.collideRight && body.checkCollision.left)
  70180. {
  70181. // Body is moving LEFT
  70182. if (tile.faceRight && body.x < tile.right)
  70183. {
  70184. ox = body.x - tile.right;
  70185. if (ox < -this.TILE_BIAS)
  70186. {
  70187. ox = 0;
  70188. }
  70189. }
  70190. }
  70191. else if (body.deltaX() > 0 && !body.blocked.right && tile.collideLeft && body.checkCollision.right)
  70192. {
  70193. // Body is moving RIGHT
  70194. if (tile.faceLeft && body.right > tile.left)
  70195. {
  70196. ox = body.right - tile.left;
  70197. if (ox > this.TILE_BIAS)
  70198. {
  70199. ox = 0;
  70200. }
  70201. }
  70202. }
  70203. if (ox !== 0)
  70204. {
  70205. if (body.customSeparateX)
  70206. {
  70207. body.overlapX = ox;
  70208. }
  70209. else
  70210. {
  70211. this.processTileSeparationX(body, ox);
  70212. }
  70213. }
  70214. return ox;
  70215. },
  70216. /**
  70217. * Check the body against the given tile on the Y axis.
  70218. *
  70219. * @private
  70220. * @method Phaser.Physics.Arcade#tileCheckY
  70221. * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate.
  70222. * @param {Phaser.Tile} tile - The tile to check.
  70223. * @return {number} The amount of separation that occurred.
  70224. */
  70225. tileCheckY: function (body, tile) {
  70226. var oy = 0;
  70227. if (body.deltaY() < 0 && !body.blocked.up && tile.collideDown && body.checkCollision.up)
  70228. {
  70229. // Body is moving UP
  70230. if (tile.faceBottom && body.y < tile.bottom)
  70231. {
  70232. oy = body.y - tile.bottom;
  70233. if (oy < -this.TILE_BIAS)
  70234. {
  70235. oy = 0;
  70236. }
  70237. }
  70238. }
  70239. else if (body.deltaY() > 0 && !body.blocked.down && tile.collideUp && body.checkCollision.down)
  70240. {
  70241. // Body is moving DOWN
  70242. if (tile.faceTop && body.bottom > tile.top)
  70243. {
  70244. oy = body.bottom - tile.top;
  70245. if (oy > this.TILE_BIAS)
  70246. {
  70247. oy = 0;
  70248. }
  70249. }
  70250. }
  70251. if (oy !== 0)
  70252. {
  70253. if (body.customSeparateY)
  70254. {
  70255. body.overlapY = oy;
  70256. }
  70257. else
  70258. {
  70259. this.processTileSeparationY(body, oy);
  70260. }
  70261. }
  70262. return oy;
  70263. },
  70264. /**
  70265. * Internal function to process the separation of a physics body from a tile.
  70266. *
  70267. * @private
  70268. * @method Phaser.Physics.Arcade#processTileSeparationX
  70269. * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate.
  70270. * @param {number} x - The x separation amount.
  70271. */
  70272. processTileSeparationX: function (body, x) {
  70273. if (x < 0)
  70274. {
  70275. body.blocked.left = true;
  70276. }
  70277. else if (x > 0)
  70278. {
  70279. body.blocked.right = true;
  70280. }
  70281. body.position.x -= x;
  70282. if (body.bounce.x === 0)
  70283. {
  70284. body.velocity.x = 0;
  70285. }
  70286. else
  70287. {
  70288. body.velocity.x = -body.velocity.x * body.bounce.x;
  70289. }
  70290. },
  70291. /**
  70292. * Internal function to process the separation of a physics body from a tile.
  70293. *
  70294. * @private
  70295. * @method Phaser.Physics.Arcade#processTileSeparationY
  70296. * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate.
  70297. * @param {number} y - The y separation amount.
  70298. */
  70299. processTileSeparationY: function (body, y) {
  70300. if (y < 0)
  70301. {
  70302. body.blocked.up = true;
  70303. }
  70304. else if (y > 0)
  70305. {
  70306. body.blocked.down = true;
  70307. }
  70308. body.position.y -= y;
  70309. if (body.bounce.y === 0)
  70310. {
  70311. body.velocity.y = 0;
  70312. }
  70313. else
  70314. {
  70315. body.velocity.y = -body.velocity.y * body.bounce.y;
  70316. }
  70317. }
  70318. };
  70319. // Merge this with the Arcade Physics prototype
  70320. Phaser.Utils.mixinPrototype(Phaser.Physics.Arcade.prototype, Phaser.Physics.Arcade.TilemapCollision.prototype);
  70321. /**
  70322. * @author Richard Davey <rich@photonstorm.com>
  70323. * @copyright 2016 Photon Storm Ltd.
  70324. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  70325. */
  70326. // Add an extra properties to p2 that we need
  70327. p2.Body.prototype.parent = null;
  70328. p2.Spring.prototype.parent = null;
  70329. /**
  70330. * This is your main access to the P2 Physics World.
  70331. * From here you can create materials, listen for events and add bodies into the physics simulation.
  70332. *
  70333. * @class Phaser.Physics.P2
  70334. * @constructor
  70335. * @param {Phaser.Game} game - Reference to the current game instance.
  70336. * @param {object} [config] - Physics configuration object passed in from the game constructor.
  70337. */
  70338. Phaser.Physics.P2 = function (game, config) {
  70339. /**
  70340. * @property {Phaser.Game} game - Local reference to game.
  70341. */
  70342. this.game = game;
  70343. if (config === undefined)
  70344. {
  70345. config = { gravity: [0, 0], broadphase: new p2.SAPBroadphase() };
  70346. }
  70347. else
  70348. {
  70349. if (!config.hasOwnProperty('gravity'))
  70350. {
  70351. config.gravity = [0, 0];
  70352. }
  70353. if (!config.hasOwnProperty('broadphase'))
  70354. {
  70355. config.broadphase = new p2.SAPBroadphase();
  70356. }
  70357. }
  70358. /**
  70359. * @property {object} config - The p2 World configuration object.
  70360. * @protected
  70361. */
  70362. this.config = config;
  70363. /**
  70364. * @property {p2.World} world - The p2 World in which the simulation is run.
  70365. * @protected
  70366. */
  70367. this.world = new p2.World(this.config);
  70368. /**
  70369. * @property {number} frameRate - The frame rate the world will be stepped at. Defaults to 1 / 60, but you can change here. Also see useElapsedTime property.
  70370. * @default
  70371. */
  70372. this.frameRate = 1 / 60;
  70373. /**
  70374. * @property {boolean} useElapsedTime - If true the frameRate value will be ignored and instead p2 will step with the value of Game.Time.physicsElapsed, which is a delta time value.
  70375. * @default
  70376. */
  70377. this.useElapsedTime = false;
  70378. /**
  70379. * @property {boolean} paused - The paused state of the P2 World.
  70380. * @default
  70381. */
  70382. this.paused = false;
  70383. /**
  70384. * @property {array<Phaser.Physics.P2.Material>} materials - A local array of all created Materials.
  70385. * @protected
  70386. */
  70387. this.materials = [];
  70388. /**
  70389. * @property {Phaser.Physics.P2.InversePointProxy} gravity - The gravity applied to all bodies each step.
  70390. */
  70391. this.gravity = new Phaser.Physics.P2.InversePointProxy(this, this.world.gravity);
  70392. /**
  70393. * @property {object} walls - An object containing the 4 wall bodies that bound the physics world.
  70394. */
  70395. this.walls = { left: null, right: null, top: null, bottom: null };
  70396. /**
  70397. * This signal is dispatched when a new Body is added to the World.
  70398. *
  70399. * It sends 1 argument: `body` which is the `Phaser.Physics.P2.Body` that was added to the world.
  70400. *
  70401. * @property {Phaser.Signal} onBodyAdded
  70402. */
  70403. this.onBodyAdded = new Phaser.Signal();
  70404. /**
  70405. * This signal is dispatched when a Body is removed to the World.
  70406. *
  70407. * It sends 1 argument: `body` which is the `Phaser.Physics.P2.Body` that was removed from the world.
  70408. *
  70409. * @property {Phaser.Signal} onBodyRemoved
  70410. */
  70411. this.onBodyRemoved = new Phaser.Signal();
  70412. /**
  70413. * This signal is dispatched when a Spring is added to the World.
  70414. *
  70415. * It sends 1 argument: `spring` which is either a `Phaser.Physics.P2.Spring`, `p2.LinearSpring` or `p2.RotationalSpring` that was added to the world.
  70416. *
  70417. * @property {Phaser.Signal} onSpringAdded
  70418. */
  70419. this.onSpringAdded = new Phaser.Signal();
  70420. /**
  70421. * This signal is dispatched when a Spring is removed from the World.
  70422. *
  70423. * It sends 1 argument: `spring` which is either a `Phaser.Physics.P2.Spring`, `p2.LinearSpring` or `p2.RotationalSpring` that was removed from the world.
  70424. *
  70425. * @property {Phaser.Signal} onSpringRemoved
  70426. */
  70427. this.onSpringRemoved = new Phaser.Signal();
  70428. /**
  70429. * This signal is dispatched when a Constraint is added to the World.
  70430. *
  70431. * It sends 1 argument: `constraint` which is the `Phaser.Physics.P2.Constraint` that was added to the world.
  70432. *
  70433. * @property {Phaser.Signal} onConstraintAdded
  70434. */
  70435. this.onConstraintAdded = new Phaser.Signal();
  70436. /**
  70437. * This signal is dispatched when a Constraint is removed from the World.
  70438. *
  70439. * It sends 1 argument: `constraint` which is the `Phaser.Physics.P2.Constraint` that was removed from the world.
  70440. *
  70441. * @property {Phaser.Signal} onConstraintRemoved
  70442. */
  70443. this.onConstraintRemoved = new Phaser.Signal();
  70444. /**
  70445. * This signal is dispatched when a Contact Material is added to the World.
  70446. *
  70447. * It sends 1 argument: `material` which is the `Phaser.Physics.P2.ContactMaterial` that was added to the world.
  70448. *
  70449. * @property {Phaser.Signal} onContactMaterialAdded
  70450. */
  70451. this.onContactMaterialAdded = new Phaser.Signal();
  70452. /**
  70453. * This signal is dispatched when a Contact Material is removed from the World.
  70454. *
  70455. * It sends 1 argument: `material` which is the `Phaser.Physics.P2.ContactMaterial` that was removed from the world.
  70456. *
  70457. * @property {Phaser.Signal} onContactMaterialRemoved
  70458. */
  70459. this.onContactMaterialRemoved = new Phaser.Signal();
  70460. /**
  70461. * @property {function} postBroadphaseCallback - A postBroadphase callback.
  70462. */
  70463. this.postBroadphaseCallback = null;
  70464. /**
  70465. * @property {object} callbackContext - The context under which the callbacks are fired.
  70466. */
  70467. this.callbackContext = null;
  70468. /**
  70469. * This Signal is dispatched when a first contact is created between two bodies. This happens *before* the step has been done.
  70470. *
  70471. * It sends 5 arguments: `bodyA`, `bodyB`, `shapeA`, `shapeB` and `contactEquations`.
  70472. *
  70473. * It is possible that in certain situations the `bodyA` or `bodyB` values are `null`. You should check for this
  70474. * in your own code to avoid processing potentially null physics bodies.
  70475. *
  70476. * @property {Phaser.Signal} onBeginContact
  70477. */
  70478. this.onBeginContact = new Phaser.Signal();
  70479. /**
  70480. * This Signal is dispatched when final contact occurs between two bodies. This happens *before* the step has been done.
  70481. *
  70482. * It sends 4 arguments: `bodyA`, `bodyB`, `shapeA` and `shapeB`.
  70483. *
  70484. * It is possible that in certain situations the `bodyA` or `bodyB` values are `null`. You should check for this
  70485. * in your own code to avoid processing potentially null physics bodies.
  70486. *
  70487. * @property {Phaser.Signal} onEndContact
  70488. */
  70489. this.onEndContact = new Phaser.Signal();
  70490. // Pixel to meter function overrides
  70491. if (config.hasOwnProperty('mpx') && config.hasOwnProperty('pxm') && config.hasOwnProperty('mpxi') && config.hasOwnProperty('pxmi'))
  70492. {
  70493. this.mpx = config.mpx;
  70494. this.mpxi = config.mpxi;
  70495. this.pxm = config.pxm;
  70496. this.pxmi = config.pxmi;
  70497. }
  70498. // Hook into the World events
  70499. this.world.on("beginContact", this.beginContactHandler, this);
  70500. this.world.on("endContact", this.endContactHandler, this);
  70501. /**
  70502. * @property {array} collisionGroups - An array containing the collision groups that have been defined in the World.
  70503. */
  70504. this.collisionGroups = [];
  70505. /**
  70506. * @property {Phaser.Physics.P2.CollisionGroup} nothingCollisionGroup - A default collision group.
  70507. */
  70508. this.nothingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(1);
  70509. /**
  70510. * @property {Phaser.Physics.P2.CollisionGroup} boundsCollisionGroup - A default collision group.
  70511. */
  70512. this.boundsCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2);
  70513. /**
  70514. * @property {Phaser.Physics.P2.CollisionGroup} everythingCollisionGroup - A default collision group.
  70515. */
  70516. this.everythingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2147483648);
  70517. /**
  70518. * @property {array} boundsCollidesWith - An array of the bodies the world bounds collides with.
  70519. */
  70520. this.boundsCollidesWith = [];
  70521. /**
  70522. * @property {array} _toRemove - Internal var used to hold references to bodies to remove from the world on the next step.
  70523. * @private
  70524. */
  70525. this._toRemove = [];
  70526. /**
  70527. * @property {number} _collisionGroupID - Internal var.
  70528. * @private
  70529. */
  70530. this._collisionGroupID = 2;
  70531. /**
  70532. * @property {boolean} _boundsLeft - Internal var that keeps track of world bounds settings.
  70533. * @private
  70534. */
  70535. this._boundsLeft = true;
  70536. /**
  70537. * @property {boolean} _boundsRight - Internal var that keeps track of world bounds settings.
  70538. * @private
  70539. */
  70540. this._boundsRight = true;
  70541. /**
  70542. * @property {boolean} _boundsTop - Internal var that keeps track of world bounds settings.
  70543. * @private
  70544. */
  70545. this._boundsTop = true;
  70546. /**
  70547. * @property {boolean} _boundsBottom - Internal var that keeps track of world bounds settings.
  70548. * @private
  70549. */
  70550. this._boundsBottom = true;
  70551. /**
  70552. * @property {boolean} _boundsOwnGroup - Internal var that keeps track of world bounds settings.
  70553. * @private
  70554. */
  70555. this._boundsOwnGroup = false;
  70556. // By default we want everything colliding with everything
  70557. this.setBoundsToWorld(true, true, true, true, false);
  70558. };
  70559. Phaser.Physics.P2.prototype = {
  70560. /**
  70561. * This will add a P2 Physics body into the removal list for the next step.
  70562. *
  70563. * @method Phaser.Physics.P2#removeBodyNextStep
  70564. * @param {Phaser.Physics.P2.Body} body - The body to remove at the start of the next step.
  70565. */
  70566. removeBodyNextStep: function (body) {
  70567. this._toRemove.push(body);
  70568. },
  70569. /**
  70570. * Called at the start of the core update loop. Purges flagged bodies from the world.
  70571. *
  70572. * @method Phaser.Physics.P2#preUpdate
  70573. */
  70574. preUpdate: function () {
  70575. var i = this._toRemove.length;
  70576. while (i--)
  70577. {
  70578. this.removeBody(this._toRemove[i]);
  70579. }
  70580. this._toRemove.length = 0;
  70581. },
  70582. /**
  70583. * This will create a P2 Physics body on the given game object or array of game objects.
  70584. * A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed.
  70585. * Note: When the game object is enabled for P2 physics it has its anchor x/y set to 0.5 so it becomes centered.
  70586. *
  70587. * @method Phaser.Physics.P2#enable
  70588. * @param {object|array|Phaser.Group} object - The game object to create the physics body on. Can also be an array or Group of objects, a body will be created on every child that has a `body` property.
  70589. * @param {boolean} [debug=false] - Create a debug object to go with this body?
  70590. * @param {boolean} [children=true] - Should a body be created on all children of this object? If true it will recurse down the display list as far as it can go.
  70591. */
  70592. enable: function (object, debug, children) {
  70593. if (debug === undefined) { debug = false; }
  70594. if (children === undefined) { children = true; }
  70595. var i = 1;
  70596. if (Array.isArray(object))
  70597. {
  70598. i = object.length;
  70599. while (i--)
  70600. {
  70601. if (object[i] instanceof Phaser.Group)
  70602. {
  70603. // If it's a Group then we do it on the children regardless
  70604. this.enable(object[i].children, debug, children);
  70605. }
  70606. else
  70607. {
  70608. this.enableBody(object[i], debug);
  70609. if (children && object[i].hasOwnProperty('children') && object[i].children.length > 0)
  70610. {
  70611. this.enable(object[i], debug, true);
  70612. }
  70613. }
  70614. }
  70615. }
  70616. else
  70617. {
  70618. if (object instanceof Phaser.Group)
  70619. {
  70620. // If it's a Group then we do it on the children regardless
  70621. this.enable(object.children, debug, children);
  70622. }
  70623. else
  70624. {
  70625. this.enableBody(object, debug);
  70626. if (children && object.hasOwnProperty('children') && object.children.length > 0)
  70627. {
  70628. this.enable(object.children, debug, true);
  70629. }
  70630. }
  70631. }
  70632. },
  70633. /**
  70634. * Creates a P2 Physics body on the given game object.
  70635. * A game object can only have 1 physics body active at any one time, and it can't be changed until the body is nulled.
  70636. *
  70637. * @method Phaser.Physics.P2#enableBody
  70638. * @param {object} object - The game object to create the physics body on. A body will only be created if this object has a null `body` property.
  70639. * @param {boolean} debug - Create a debug object to go with this body?
  70640. */
  70641. enableBody: function (object, debug) {
  70642. if (object.hasOwnProperty('body') && object.body === null)
  70643. {
  70644. object.body = new Phaser.Physics.P2.Body(this.game, object, object.x, object.y, 1);
  70645. object.body.debug = debug;
  70646. if (typeof object.anchor !== 'undefined') {
  70647. object.anchor.set(0.5);
  70648. }
  70649. }
  70650. },
  70651. /**
  70652. * Impact event handling is disabled by default. Enable it before any impact events will be dispatched.
  70653. * In a busy world hundreds of impact events can be generated every step, so only enable this if you cannot do what you need via beginContact or collision masks.
  70654. *
  70655. * @method Phaser.Physics.P2#setImpactEvents
  70656. * @param {boolean} state - Set to true to enable impact events, or false to disable.
  70657. */
  70658. setImpactEvents: function (state) {
  70659. if (state)
  70660. {
  70661. this.world.on("impact", this.impactHandler, this);
  70662. }
  70663. else
  70664. {
  70665. this.world.off("impact", this.impactHandler, this);
  70666. }
  70667. },
  70668. /**
  70669. * Sets a callback to be fired after the Broadphase has collected collision pairs in the world.
  70670. * Just because a pair exists it doesn't mean they *will* collide, just that they potentially could do.
  70671. * If your calback returns `false` the pair will be removed from the narrowphase. This will stop them testing for collision this step.
  70672. * Returning `true` from the callback will ensure they are checked in the narrowphase.
  70673. *
  70674. * @method Phaser.Physics.P2#setPostBroadphaseCallback
  70675. * @param {function} callback - The callback that will receive the postBroadphase event data. It must return a boolean. Set to null to disable an existing callback.
  70676. * @param {object} context - The context under which the callback will be fired.
  70677. */
  70678. setPostBroadphaseCallback: function (callback, context) {
  70679. this.postBroadphaseCallback = callback;
  70680. this.callbackContext = context;
  70681. if (callback !== null)
  70682. {
  70683. this.world.on("postBroadphase", this.postBroadphaseHandler, this);
  70684. }
  70685. else
  70686. {
  70687. this.world.off("postBroadphase", this.postBroadphaseHandler, this);
  70688. }
  70689. },
  70690. /**
  70691. * Internal handler for the postBroadphase event.
  70692. *
  70693. * @method Phaser.Physics.P2#postBroadphaseHandler
  70694. * @private
  70695. * @param {object} event - The event data.
  70696. */
  70697. postBroadphaseHandler: function (event) {
  70698. if (!this.postBroadphaseCallback || event.pairs.length === 0)
  70699. {
  70700. return;
  70701. }
  70702. for (var i = event.pairs.length - 2; i >= 0; i -= 2)
  70703. {
  70704. if (event.pairs[i].parent && event.pairs[i+1].parent && !this.postBroadphaseCallback.call(this.callbackContext, event.pairs[i].parent, event.pairs[i+1].parent))
  70705. {
  70706. event.pairs.splice(i, 2);
  70707. }
  70708. }
  70709. },
  70710. /**
  70711. * Handles a p2 impact event.
  70712. *
  70713. * @method Phaser.Physics.P2#impactHandler
  70714. * @private
  70715. * @param {object} event - The event data.
  70716. */
  70717. impactHandler: function (event) {
  70718. if (event.bodyA.parent && event.bodyB.parent)
  70719. {
  70720. // Body vs. Body callbacks
  70721. var a = event.bodyA.parent;
  70722. var b = event.bodyB.parent;
  70723. if (a._bodyCallbacks[event.bodyB.id])
  70724. {
  70725. a._bodyCallbacks[event.bodyB.id].call(a._bodyCallbackContext[event.bodyB.id], a, b, event.shapeA, event.shapeB);
  70726. }
  70727. if (b._bodyCallbacks[event.bodyA.id])
  70728. {
  70729. b._bodyCallbacks[event.bodyA.id].call(b._bodyCallbackContext[event.bodyA.id], b, a, event.shapeB, event.shapeA);
  70730. }
  70731. // Body vs. Group callbacks
  70732. if (a._groupCallbacks[event.shapeB.collisionGroup])
  70733. {
  70734. a._groupCallbacks[event.shapeB.collisionGroup].call(a._groupCallbackContext[event.shapeB.collisionGroup], a, b, event.shapeA, event.shapeB);
  70735. }
  70736. if (b._groupCallbacks[event.shapeA.collisionGroup])
  70737. {
  70738. b._groupCallbacks[event.shapeA.collisionGroup].call(b._groupCallbackContext[event.shapeA.collisionGroup], b, a, event.shapeB, event.shapeA);
  70739. }
  70740. }
  70741. },
  70742. /**
  70743. * Handles a p2 begin contact event.
  70744. *
  70745. * @method Phaser.Physics.P2#beginContactHandler
  70746. * @param {object} event - The event data.
  70747. */
  70748. beginContactHandler: function (event) {
  70749. if (event.bodyA && event.bodyB)
  70750. {
  70751. this.onBeginContact.dispatch(event.bodyA, event.bodyB, event.shapeA, event.shapeB, event.contactEquations);
  70752. if (event.bodyA.parent)
  70753. {
  70754. event.bodyA.parent.onBeginContact.dispatch(event.bodyB.parent, event.bodyB, event.shapeA, event.shapeB, event.contactEquations);
  70755. }
  70756. if (event.bodyB.parent)
  70757. {
  70758. event.bodyB.parent.onBeginContact.dispatch(event.bodyA.parent, event.bodyA, event.shapeB, event.shapeA, event.contactEquations);
  70759. }
  70760. }
  70761. },
  70762. /**
  70763. * Handles a p2 end contact event.
  70764. *
  70765. * @method Phaser.Physics.P2#endContactHandler
  70766. * @param {object} event - The event data.
  70767. */
  70768. endContactHandler: function (event) {
  70769. if (event.bodyA && event.bodyB)
  70770. {
  70771. this.onEndContact.dispatch(event.bodyA, event.bodyB, event.shapeA, event.shapeB);
  70772. if (event.bodyA.parent)
  70773. {
  70774. event.bodyA.parent.onEndContact.dispatch(event.bodyB.parent, event.bodyB, event.shapeA, event.shapeB);
  70775. }
  70776. if (event.bodyB.parent)
  70777. {
  70778. event.bodyB.parent.onEndContact.dispatch(event.bodyA.parent, event.bodyA, event.shapeB, event.shapeA);
  70779. }
  70780. }
  70781. },
  70782. /**
  70783. * Sets the bounds of the Physics world to match the Game.World dimensions.
  70784. * You can optionally set which 'walls' to create: left, right, top or bottom.
  70785. *
  70786. * @method Phaser.Physics#setBoundsToWorld
  70787. * @param {boolean} [left=true] - If true will create the left bounds wall.
  70788. * @param {boolean} [right=true] - If true will create the right bounds wall.
  70789. * @param {boolean} [top=true] - If true will create the top bounds wall.
  70790. * @param {boolean} [bottom=true] - If true will create the bottom bounds wall.
  70791. * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group.
  70792. */
  70793. setBoundsToWorld: function (left, right, top, bottom, setCollisionGroup) {
  70794. this.setBounds(this.game.world.bounds.x, this.game.world.bounds.y, this.game.world.bounds.width, this.game.world.bounds.height, left, right, top, bottom, setCollisionGroup);
  70795. },
  70796. /**
  70797. * Sets the given material against the 4 bounds of this World.
  70798. *
  70799. * @method Phaser.Physics#setWorldMaterial
  70800. * @param {Phaser.Physics.P2.Material} material - The material to set.
  70801. * @param {boolean} [left=true] - If true will set the material on the left bounds wall.
  70802. * @param {boolean} [right=true] - If true will set the material on the right bounds wall.
  70803. * @param {boolean} [top=true] - If true will set the material on the top bounds wall.
  70804. * @param {boolean} [bottom=true] - If true will set the material on the bottom bounds wall.
  70805. */
  70806. setWorldMaterial: function (material, left, right, top, bottom) {
  70807. if (left === undefined) { left = true; }
  70808. if (right === undefined) { right = true; }
  70809. if (top === undefined) { top = true; }
  70810. if (bottom === undefined) { bottom = true; }
  70811. if (left && this.walls.left)
  70812. {
  70813. this.walls.left.shapes[0].material = material;
  70814. }
  70815. if (right && this.walls.right)
  70816. {
  70817. this.walls.right.shapes[0].material = material;
  70818. }
  70819. if (top && this.walls.top)
  70820. {
  70821. this.walls.top.shapes[0].material = material;
  70822. }
  70823. if (bottom && this.walls.bottom)
  70824. {
  70825. this.walls.bottom.shapes[0].material = material;
  70826. }
  70827. },
  70828. /**
  70829. * By default the World will be set to collide everything with everything. The bounds of the world is a Body with 4 shapes, one for each face.
  70830. * If you start to use your own collision groups then your objects will no longer collide with the bounds.
  70831. * To fix this you need to adjust the bounds to use its own collision group first BEFORE changing your Sprites collision group.
  70832. *
  70833. * @method Phaser.Physics.P2#updateBoundsCollisionGroup
  70834. * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group.
  70835. */
  70836. updateBoundsCollisionGroup: function (setCollisionGroup) {
  70837. if (setCollisionGroup === undefined) { setCollisionGroup = true; }
  70838. var mask = (setCollisionGroup) ? this.boundsCollisionGroup.mask : this.everythingCollisionGroup.mask;
  70839. if (this.walls.left)
  70840. {
  70841. this.walls.left.shapes[0].collisionGroup = mask;
  70842. }
  70843. if (this.walls.right)
  70844. {
  70845. this.walls.right.shapes[0].collisionGroup = mask;
  70846. }
  70847. if (this.walls.top)
  70848. {
  70849. this.walls.top.shapes[0].collisionGroup = mask;
  70850. }
  70851. if (this.walls.bottom)
  70852. {
  70853. this.walls.bottom.shapes[0].collisionGroup = mask;
  70854. }
  70855. this._boundsOwnGroup = setCollisionGroup;
  70856. },
  70857. /**
  70858. * Sets the bounds of the Physics world to match the given world pixel dimensions.
  70859. * You can optionally set which 'walls' to create: left, right, top or bottom.
  70860. * If none of the walls are given it will default to use the walls settings it had previously.
  70861. * I.e. if you previously told it to not have the left or right walls, and you then adjust the world size
  70862. * the newly created bounds will also not have the left and right walls.
  70863. * Explicitly state them in the parameters to override this.
  70864. *
  70865. * @method Phaser.Physics.P2#setBounds
  70866. * @param {number} x - The x coordinate of the top-left corner of the bounds.
  70867. * @param {number} y - The y coordinate of the top-left corner of the bounds.
  70868. * @param {number} width - The width of the bounds.
  70869. * @param {number} height - The height of the bounds.
  70870. * @param {boolean} [left=true] - If true will create the left bounds wall.
  70871. * @param {boolean} [right=true] - If true will create the right bounds wall.
  70872. * @param {boolean} [top=true] - If true will create the top bounds wall.
  70873. * @param {boolean} [bottom=true] - If true will create the bottom bounds wall.
  70874. * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group.
  70875. */
  70876. setBounds: function (x, y, width, height, left, right, top, bottom, setCollisionGroup) {
  70877. if (left === undefined) { left = this._boundsLeft; }
  70878. if (right === undefined) { right = this._boundsRight; }
  70879. if (top === undefined) { top = this._boundsTop; }
  70880. if (bottom === undefined) { bottom = this._boundsBottom; }
  70881. if (setCollisionGroup === undefined) { setCollisionGroup = this._boundsOwnGroup; }
  70882. this.setupWall(left, 'left', x, y, 1.5707963267948966, setCollisionGroup);
  70883. this.setupWall(right, 'right', x + width, y, -1.5707963267948966, setCollisionGroup);
  70884. this.setupWall(top, 'top', x, y, -3.141592653589793, setCollisionGroup);
  70885. this.setupWall(bottom, 'bottom', x, y + height, 0, setCollisionGroup);
  70886. // Remember the bounds settings in case they change later on via World.setBounds
  70887. this._boundsLeft = left;
  70888. this._boundsRight = right;
  70889. this._boundsTop = top;
  70890. this._boundsBottom = bottom;
  70891. this._boundsOwnGroup = setCollisionGroup;
  70892. },
  70893. /**
  70894. * Internal method called by setBounds. Responsible for creating, updating or
  70895. * removing the wall body shapes.
  70896. *
  70897. * @method Phaser.Physics.P2#setupWall
  70898. * @private
  70899. * @param {boolean} create - True to create the wall shape, false to remove it.
  70900. * @param {string} wall - The wall segment to update.
  70901. * @param {number} x - The x coordinate of the wall.
  70902. * @param {number} y - The y coordinate of the wall.
  70903. * @param {float} angle - The angle of the wall.
  70904. * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group.
  70905. */
  70906. setupWall: function (create, wall, x, y, angle, setCollisionGroup) {
  70907. if (create)
  70908. {
  70909. // We need a left wall. Do we have one already?
  70910. if (this.walls[wall])
  70911. {
  70912. this.walls[wall].position = [ this.pxmi(x), this.pxmi(y) ];
  70913. }
  70914. else
  70915. {
  70916. this.walls[wall] = new p2.Body({ mass: 0, position: [ this.pxmi(x), this.pxmi(y) ], angle: angle });
  70917. this.walls[wall].addShape(new p2.Plane());
  70918. if (setCollisionGroup)
  70919. {
  70920. this.walls[wall].shapes[0].collisionGroup = this.boundsCollisionGroup.mask;
  70921. }
  70922. this.world.addBody(this.walls[wall]);
  70923. }
  70924. }
  70925. else
  70926. {
  70927. if (this.walls[wall])
  70928. {
  70929. this.world.removeBody(this.walls[wall]);
  70930. this.walls[wall] = null;
  70931. }
  70932. }
  70933. },
  70934. /**
  70935. * Pauses the P2 World independent of the game pause state.
  70936. *
  70937. * @method Phaser.Physics.P2#pause
  70938. */
  70939. pause: function() {
  70940. this.paused = true;
  70941. },
  70942. /**
  70943. * Resumes a paused P2 World.
  70944. *
  70945. * @method Phaser.Physics.P2#resume
  70946. */
  70947. resume: function() {
  70948. this.paused = false;
  70949. },
  70950. /**
  70951. * Internal P2 update loop.
  70952. *
  70953. * @method Phaser.Physics.P2#update
  70954. */
  70955. update: function () {
  70956. // Do nothing if the physics engine was paused before
  70957. if (this.paused)
  70958. {
  70959. return;
  70960. }
  70961. if (this.useElapsedTime)
  70962. {
  70963. this.world.step(this.game.time.physicsElapsed);
  70964. }
  70965. else
  70966. {
  70967. this.world.step(this.frameRate);
  70968. }
  70969. },
  70970. /**
  70971. * Called by Phaser.Physics when a State swap occurs.
  70972. * Starts the begin and end Contact listeners again.
  70973. *
  70974. * @method Phaser.Physics.P2#reset
  70975. */
  70976. reset: function () {
  70977. this.world.on("beginContact", this.beginContactHandler, this);
  70978. this.world.on("endContact", this.endContactHandler, this);
  70979. this.nothingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(1);
  70980. this.boundsCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2);
  70981. this.everythingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2147483648);
  70982. this._collisionGroupID = 2;
  70983. this.setBoundsToWorld(true, true, true, true, false);
  70984. },
  70985. /**
  70986. * Clears all bodies from the simulation, resets callbacks and resets the collision bitmask.
  70987. *
  70988. * The P2 world is also cleared:
  70989. *
  70990. * * Removes all solver equations
  70991. * * Removes all constraints
  70992. * * Removes all bodies
  70993. * * Removes all springs
  70994. * * Removes all contact materials
  70995. *
  70996. * This is called automatically when you switch state.
  70997. *
  70998. * @method Phaser.Physics.P2#clear
  70999. */
  71000. clear: function () {
  71001. this.world.time = 0;
  71002. this.world.fixedStepTime = 0;
  71003. // Remove all solver equations
  71004. if (this.world.solver && this.world.solver.equations.length)
  71005. {
  71006. this.world.solver.removeAllEquations();
  71007. }
  71008. // Remove all constraints
  71009. var cs = this.world.constraints;
  71010. for (var i = cs.length - 1; i >= 0; i--)
  71011. {
  71012. this.world.removeConstraint(cs[i]);
  71013. }
  71014. // Remove all bodies
  71015. var bodies = this.world.bodies;
  71016. for (var i = bodies.length - 1; i >= 0; i--)
  71017. {
  71018. this.world.removeBody(bodies[i]);
  71019. }
  71020. // Remove all springs
  71021. var springs = this.world.springs;
  71022. for (var i = springs.length - 1; i >= 0; i--)
  71023. {
  71024. this.world.removeSpring(springs[i]);
  71025. }
  71026. // Remove all contact materials
  71027. var cms = this.world.contactMaterials;
  71028. for (var i = cms.length - 1; i >= 0; i--)
  71029. {
  71030. this.world.removeContactMaterial(cms[i]);
  71031. }
  71032. this.world.off("beginContact", this.beginContactHandler, this);
  71033. this.world.off("endContact", this.endContactHandler, this);
  71034. this.postBroadphaseCallback = null;
  71035. this.callbackContext = null;
  71036. this.impactCallback = null;
  71037. this.collisionGroups = [];
  71038. this._toRemove = [];
  71039. this.boundsCollidesWith = [];
  71040. },
  71041. /**
  71042. * Clears all bodies from the simulation and unlinks World from Game. Should only be called on game shutdown. Call `clear` on a State change.
  71043. *
  71044. * @method Phaser.Physics.P2#destroy
  71045. */
  71046. destroy: function () {
  71047. this.clear();
  71048. this.game = null;
  71049. },
  71050. /**
  71051. * Add a body to the world.
  71052. *
  71053. * @method Phaser.Physics.P2#addBody
  71054. * @param {Phaser.Physics.P2.Body} body - The Body to add to the World.
  71055. * @return {boolean} True if the Body was added successfully, otherwise false.
  71056. */
  71057. addBody: function (body) {
  71058. if (body.data.world)
  71059. {
  71060. return false;
  71061. }
  71062. else
  71063. {
  71064. this.world.addBody(body.data);
  71065. this.onBodyAdded.dispatch(body);
  71066. return true;
  71067. }
  71068. },
  71069. /**
  71070. * Removes a body from the world. This will silently fail if the body wasn't part of the world to begin with.
  71071. *
  71072. * @method Phaser.Physics.P2#removeBody
  71073. * @param {Phaser.Physics.P2.Body} body - The Body to remove from the World.
  71074. * @return {Phaser.Physics.P2.Body} The Body that was removed.
  71075. */
  71076. removeBody: function (body) {
  71077. if (body.data.world == this.world)
  71078. {
  71079. this.world.removeBody(body.data);
  71080. this.onBodyRemoved.dispatch(body);
  71081. }
  71082. return body;
  71083. },
  71084. /**
  71085. * Adds a Spring to the world.
  71086. *
  71087. * @method Phaser.Physics.P2#addSpring
  71088. * @param {Phaser.Physics.P2.Spring|p2.LinearSpring|p2.RotationalSpring} spring - The Spring to add to the World.
  71089. * @return {Phaser.Physics.P2.Spring} The Spring that was added.
  71090. */
  71091. addSpring: function (spring) {
  71092. if (spring instanceof Phaser.Physics.P2.Spring || spring instanceof Phaser.Physics.P2.RotationalSpring)
  71093. {
  71094. this.world.addSpring(spring.data);
  71095. }
  71096. else
  71097. {
  71098. this.world.addSpring(spring);
  71099. }
  71100. this.onSpringAdded.dispatch(spring);
  71101. return spring;
  71102. },
  71103. /**
  71104. * Removes a Spring from the world.
  71105. *
  71106. * @method Phaser.Physics.P2#removeSpring
  71107. * @param {Phaser.Physics.P2.Spring} spring - The Spring to remove from the World.
  71108. * @return {Phaser.Physics.P2.Spring} The Spring that was removed.
  71109. */
  71110. removeSpring: function (spring) {
  71111. if (spring instanceof Phaser.Physics.P2.Spring || spring instanceof Phaser.Physics.P2.RotationalSpring)
  71112. {
  71113. this.world.removeSpring(spring.data);
  71114. }
  71115. else
  71116. {
  71117. this.world.removeSpring(spring);
  71118. }
  71119. this.onSpringRemoved.dispatch(spring);
  71120. return spring;
  71121. },
  71122. /**
  71123. * Creates a constraint that tries to keep the distance between two bodies constant.
  71124. *
  71125. * @method Phaser.Physics.P2#createDistanceConstraint
  71126. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body.
  71127. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body.
  71128. * @param {number} distance - The distance to keep between the bodies.
  71129. * @param {Array} [localAnchorA] - The anchor point for bodyA, defined locally in bodyA frame. Defaults to [0,0].
  71130. * @param {Array} [localAnchorB] - The anchor point for bodyB, defined locally in bodyB frame. Defaults to [0,0].
  71131. * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies.
  71132. * @return {Phaser.Physics.P2.DistanceConstraint} The constraint
  71133. */
  71134. createDistanceConstraint: function (bodyA, bodyB, distance, localAnchorA, localAnchorB, maxForce) {
  71135. bodyA = this.getBody(bodyA);
  71136. bodyB = this.getBody(bodyB);
  71137. if (!bodyA || !bodyB)
  71138. {
  71139. console.warn('Cannot create Constraint, invalid body objects given');
  71140. }
  71141. else
  71142. {
  71143. return this.addConstraint(new Phaser.Physics.P2.DistanceConstraint(this, bodyA, bodyB, distance, localAnchorA, localAnchorB, maxForce));
  71144. }
  71145. },
  71146. /**
  71147. * Creates a constraint that tries to keep the distance between two bodies constant.
  71148. *
  71149. * @method Phaser.Physics.P2#createGearConstraint
  71150. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body.
  71151. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body.
  71152. * @param {number} [angle=0] - The relative angle
  71153. * @param {number} [ratio=1] - The gear ratio.
  71154. * @return {Phaser.Physics.P2.GearConstraint} The constraint
  71155. */
  71156. createGearConstraint: function (bodyA, bodyB, angle, ratio) {
  71157. bodyA = this.getBody(bodyA);
  71158. bodyB = this.getBody(bodyB);
  71159. if (!bodyA || !bodyB)
  71160. {
  71161. console.warn('Cannot create Constraint, invalid body objects given');
  71162. }
  71163. else
  71164. {
  71165. return this.addConstraint(new Phaser.Physics.P2.GearConstraint(this, bodyA, bodyB, angle, ratio));
  71166. }
  71167. },
  71168. /**
  71169. * Connects two bodies at given offset points, letting them rotate relative to each other around this point.
  71170. * The pivot points are given in world (pixel) coordinates.
  71171. *
  71172. * @method Phaser.Physics.P2#createRevoluteConstraint
  71173. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body.
  71174. * @param {Array} pivotA - The point relative to the center of mass of bodyA which bodyA is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32].
  71175. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body.
  71176. * @param {Array} pivotB - The point relative to the center of mass of bodyB which bodyB is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32].
  71177. * @param {number} [maxForce=0] - The maximum force that should be applied to constrain the bodies.
  71178. * @param {Float32Array} [worldPivot=null] - A pivot point given in world coordinates. If specified, localPivotA and localPivotB are automatically computed from this value.
  71179. * @return {Phaser.Physics.P2.RevoluteConstraint} The constraint
  71180. */
  71181. createRevoluteConstraint: function (bodyA, pivotA, bodyB, pivotB, maxForce, worldPivot) {
  71182. bodyA = this.getBody(bodyA);
  71183. bodyB = this.getBody(bodyB);
  71184. if (!bodyA || !bodyB)
  71185. {
  71186. console.warn('Cannot create Constraint, invalid body objects given');
  71187. }
  71188. else
  71189. {
  71190. return this.addConstraint(new Phaser.Physics.P2.RevoluteConstraint(this, bodyA, pivotA, bodyB, pivotB, maxForce, worldPivot));
  71191. }
  71192. },
  71193. /**
  71194. * Locks the relative position between two bodies.
  71195. *
  71196. * @method Phaser.Physics.P2#createLockConstraint
  71197. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body.
  71198. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body.
  71199. * @param {Array} [offset] - The offset of bodyB in bodyA's frame. The value is an array with 2 elements matching x and y, i.e: [32, 32].
  71200. * @param {number} [angle=0] - The angle of bodyB in bodyA's frame.
  71201. * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies.
  71202. * @return {Phaser.Physics.P2.LockConstraint} The constraint
  71203. */
  71204. createLockConstraint: function (bodyA, bodyB, offset, angle, maxForce) {
  71205. bodyA = this.getBody(bodyA);
  71206. bodyB = this.getBody(bodyB);
  71207. if (!bodyA || !bodyB)
  71208. {
  71209. console.warn('Cannot create Constraint, invalid body objects given');
  71210. }
  71211. else
  71212. {
  71213. return this.addConstraint(new Phaser.Physics.P2.LockConstraint(this, bodyA, bodyB, offset, angle, maxForce));
  71214. }
  71215. },
  71216. /**
  71217. * Constraint that only allows bodies to move along a line, relative to each other.
  71218. * See http://www.iforce2d.net/b2dtut/joints-prismatic
  71219. *
  71220. * @method Phaser.Physics.P2#createPrismaticConstraint
  71221. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body.
  71222. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body.
  71223. * @param {boolean} [lockRotation=true] - If set to false, bodyB will be free to rotate around its anchor point.
  71224. * @param {Array} [anchorA] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32].
  71225. * @param {Array} [anchorB] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32].
  71226. * @param {Array} [axis] - An axis, defined in body A frame, that body B's anchor point may slide along. The value is an array with 2 elements matching x and y, i.e: [32, 32].
  71227. * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies.
  71228. * @return {Phaser.Physics.P2.PrismaticConstraint} The constraint
  71229. */
  71230. createPrismaticConstraint: function (bodyA, bodyB, lockRotation, anchorA, anchorB, axis, maxForce) {
  71231. bodyA = this.getBody(bodyA);
  71232. bodyB = this.getBody(bodyB);
  71233. if (!bodyA || !bodyB)
  71234. {
  71235. console.warn('Cannot create Constraint, invalid body objects given');
  71236. }
  71237. else
  71238. {
  71239. return this.addConstraint(new Phaser.Physics.P2.PrismaticConstraint(this, bodyA, bodyB, lockRotation, anchorA, anchorB, axis, maxForce));
  71240. }
  71241. },
  71242. /**
  71243. * Adds a Constraint to the world.
  71244. *
  71245. * @method Phaser.Physics.P2#addConstraint
  71246. * @param {Phaser.Physics.P2.Constraint} constraint - The Constraint to add to the World.
  71247. * @return {Phaser.Physics.P2.Constraint} The Constraint that was added.
  71248. */
  71249. addConstraint: function (constraint) {
  71250. this.world.addConstraint(constraint);
  71251. this.onConstraintAdded.dispatch(constraint);
  71252. return constraint;
  71253. },
  71254. /**
  71255. * Removes a Constraint from the world.
  71256. *
  71257. * @method Phaser.Physics.P2#removeConstraint
  71258. * @param {Phaser.Physics.P2.Constraint} constraint - The Constraint to be removed from the World.
  71259. * @return {Phaser.Physics.P2.Constraint} The Constraint that was removed.
  71260. */
  71261. removeConstraint: function (constraint) {
  71262. this.world.removeConstraint(constraint);
  71263. this.onConstraintRemoved.dispatch(constraint);
  71264. return constraint;
  71265. },
  71266. /**
  71267. * Adds a Contact Material to the world.
  71268. *
  71269. * @method Phaser.Physics.P2#addContactMaterial
  71270. * @param {Phaser.Physics.P2.ContactMaterial} material - The Contact Material to be added to the World.
  71271. * @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was added.
  71272. */
  71273. addContactMaterial: function (material) {
  71274. this.world.addContactMaterial(material);
  71275. this.onContactMaterialAdded.dispatch(material);
  71276. return material;
  71277. },
  71278. /**
  71279. * Removes a Contact Material from the world.
  71280. *
  71281. * @method Phaser.Physics.P2#removeContactMaterial
  71282. * @param {Phaser.Physics.P2.ContactMaterial} material - The Contact Material to be removed from the World.
  71283. * @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was removed.
  71284. */
  71285. removeContactMaterial: function (material) {
  71286. this.world.removeContactMaterial(material);
  71287. this.onContactMaterialRemoved.dispatch(material);
  71288. return material;
  71289. },
  71290. /**
  71291. * Gets a Contact Material based on the two given Materials.
  71292. *
  71293. * @method Phaser.Physics.P2#getContactMaterial
  71294. * @param {Phaser.Physics.P2.Material} materialA - The first Material to search for.
  71295. * @param {Phaser.Physics.P2.Material} materialB - The second Material to search for.
  71296. * @return {Phaser.Physics.P2.ContactMaterial|boolean} The Contact Material or false if none was found matching the Materials given.
  71297. */
  71298. getContactMaterial: function (materialA, materialB) {
  71299. return this.world.getContactMaterial(materialA, materialB);
  71300. },
  71301. /**
  71302. * Sets the given Material against all Shapes owned by all the Bodies in the given array.
  71303. *
  71304. * @method Phaser.Physics.P2#setMaterial
  71305. * @param {Phaser.Physics.P2.Material} material - The Material to be applied to the given Bodies.
  71306. * @param {array<Phaser.Physics.P2.Body>} bodies - An Array of Body objects that the given Material will be set on.
  71307. */
  71308. setMaterial: function (material, bodies) {
  71309. var i = bodies.length;
  71310. while (i--)
  71311. {
  71312. bodies[i].setMaterial(material);
  71313. }
  71314. },
  71315. /**
  71316. * Creates a Material. Materials are applied to Shapes owned by a Body and can be set with Body.setMaterial().
  71317. * Materials are a way to control what happens when Shapes collide. Combine unique Materials together to create Contact Materials.
  71318. * Contact Materials have properties such as friction and restitution that allow for fine-grained collision control between different Materials.
  71319. *
  71320. * @method Phaser.Physics.P2#createMaterial
  71321. * @param {string} [name] - Optional name of the Material. Each Material has a unique ID but string names are handy for debugging.
  71322. * @param {Phaser.Physics.P2.Body} [body] - Optional Body. If given it will assign the newly created Material to the Body shapes.
  71323. * @return {Phaser.Physics.P2.Material} The Material that was created. This is also stored in Phaser.Physics.P2.materials.
  71324. */
  71325. createMaterial: function (name, body) {
  71326. name = name || '';
  71327. var material = new Phaser.Physics.P2.Material(name);
  71328. this.materials.push(material);
  71329. if (typeof body !== 'undefined')
  71330. {
  71331. body.setMaterial(material);
  71332. }
  71333. return material;
  71334. },
  71335. /**
  71336. * Creates a Contact Material from the two given Materials. You can then edit the properties of the Contact Material directly.
  71337. *
  71338. * @method Phaser.Physics.P2#createContactMaterial
  71339. * @param {Phaser.Physics.P2.Material} [materialA] - The first Material to create the ContactMaterial from. If undefined it will create a new Material object first.
  71340. * @param {Phaser.Physics.P2.Material} [materialB] - The second Material to create the ContactMaterial from. If undefined it will create a new Material object first.
  71341. * @param {object} [options] - Material options object.
  71342. * @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was created.
  71343. */
  71344. createContactMaterial: function (materialA, materialB, options) {
  71345. if (materialA === undefined) { materialA = this.createMaterial(); }
  71346. if (materialB === undefined) { materialB = this.createMaterial(); }
  71347. var contact = new Phaser.Physics.P2.ContactMaterial(materialA, materialB, options);
  71348. return this.addContactMaterial(contact);
  71349. },
  71350. /**
  71351. * Populates and returns an array with references to of all current Bodies in the world.
  71352. *
  71353. * @method Phaser.Physics.P2#getBodies
  71354. * @return {array<Phaser.Physics.P2.Body>} An array containing all current Bodies in the world.
  71355. */
  71356. getBodies: function () {
  71357. var output = [];
  71358. var i = this.world.bodies.length;
  71359. while (i--)
  71360. {
  71361. output.push(this.world.bodies[i].parent);
  71362. }
  71363. return output;
  71364. },
  71365. /**
  71366. * Checks the given object to see if it has a p2.Body and if so returns it.
  71367. *
  71368. * @method Phaser.Physics.P2#getBody
  71369. * @param {object} object - The object to check for a p2.Body on.
  71370. * @return {p2.Body} The p2.Body, or null if not found.
  71371. */
  71372. getBody: function (object) {
  71373. if (object instanceof p2.Body)
  71374. {
  71375. // Native p2 body
  71376. return object;
  71377. }
  71378. else if (object instanceof Phaser.Physics.P2.Body)
  71379. {
  71380. // Phaser P2 Body
  71381. return object.data;
  71382. }
  71383. else if (object['body'] && object['body'].type === Phaser.Physics.P2JS)
  71384. {
  71385. // Sprite, TileSprite, etc
  71386. return object.body.data;
  71387. }
  71388. return null;
  71389. },
  71390. /**
  71391. * Populates and returns an array of all current Springs in the world.
  71392. *
  71393. * @method Phaser.Physics.P2#getSprings
  71394. * @return {array<Phaser.Physics.P2.Spring>} An array containing all current Springs in the world.
  71395. */
  71396. getSprings: function () {
  71397. var output = [];
  71398. var i = this.world.springs.length;
  71399. while (i--)
  71400. {
  71401. output.push(this.world.springs[i].parent);
  71402. }
  71403. return output;
  71404. },
  71405. /**
  71406. * Populates and returns an array of all current Constraints in the world.
  71407. * You will get an array of p2 constraints back. This can be of mixed types, for example the array may contain
  71408. * PrismaticConstraints, RevoluteConstraints or any other valid p2 constraint type.
  71409. *
  71410. * @method Phaser.Physics.P2#getConstraints
  71411. * @return {array<Phaser.Physics.P2.Constraint>} An array containing all current Constraints in the world.
  71412. */
  71413. getConstraints: function () {
  71414. var output = [];
  71415. var i = this.world.constraints.length;
  71416. while (i--)
  71417. {
  71418. output.push(this.world.constraints[i]);
  71419. }
  71420. return output;
  71421. },
  71422. /**
  71423. * Test if a world point overlaps bodies. You will get an array of actual P2 bodies back. You can find out which Sprite a Body belongs to
  71424. * (if any) by checking the Body.parent.sprite property. Body.parent is a Phaser.Physics.P2.Body property.
  71425. *
  71426. * @method Phaser.Physics.P2#hitTest
  71427. * @param {Phaser.Point} worldPoint - Point to use for intersection tests. The points values must be in world (pixel) coordinates.
  71428. * @param {Array<Phaser.Physics.P2.Body|Phaser.Sprite|p2.Body>} [bodies] - A list of objects to check for intersection. If not given it will check Phaser.Physics.P2.world.bodies (i.e. all world bodies)
  71429. * @param {number} [precision=5] - Used for matching against particles and lines. Adds some margin to these infinitesimal objects.
  71430. * @param {boolean} [filterStatic=false] - If true all Static objects will be removed from the results array.
  71431. * @return {Array} Array of bodies that overlap the point.
  71432. */
  71433. hitTest: function (worldPoint, bodies, precision, filterStatic) {
  71434. if (bodies === undefined) { bodies = this.world.bodies; }
  71435. if (precision === undefined) { precision = 5; }
  71436. if (filterStatic === undefined) { filterStatic = false; }
  71437. var physicsPosition = [ this.pxmi(worldPoint.x), this.pxmi(worldPoint.y) ];
  71438. var query = [];
  71439. var i = bodies.length;
  71440. while (i--)
  71441. {
  71442. if (bodies[i] instanceof Phaser.Physics.P2.Body && !(filterStatic && bodies[i].data.type === p2.Body.STATIC))
  71443. {
  71444. query.push(bodies[i].data);
  71445. }
  71446. else if (bodies[i] instanceof p2.Body && bodies[i].parent && !(filterStatic && bodies[i].type === p2.Body.STATIC))
  71447. {
  71448. query.push(bodies[i]);
  71449. }
  71450. else if (bodies[i] instanceof Phaser.Sprite && bodies[i].hasOwnProperty('body') && !(filterStatic && bodies[i].body.data.type === p2.Body.STATIC))
  71451. {
  71452. query.push(bodies[i].body.data);
  71453. }
  71454. }
  71455. return this.world.hitTest(physicsPosition, query, precision);
  71456. },
  71457. /**
  71458. * Converts the current world into a JSON object.
  71459. *
  71460. * @method Phaser.Physics.P2#toJSON
  71461. * @return {object} A JSON representation of the world.
  71462. */
  71463. toJSON: function () {
  71464. return this.world.toJSON();
  71465. },
  71466. /**
  71467. * Creates a new Collision Group and optionally applies it to the given object.
  71468. * Collision Groups are handled using bitmasks, therefore you have a fixed limit you can create before you need to re-use older groups.
  71469. *
  71470. * @method Phaser.Physics.P2#createCollisionGroup
  71471. * @param {Phaser.Group|Phaser.Sprite} [object] - An optional Sprite or Group to apply the Collision Group to. If a Group is given it will be applied to all top-level children.
  71472. */
  71473. createCollisionGroup: function (object) {
  71474. var bitmask = Math.pow(2, this._collisionGroupID);
  71475. if (this.walls.left)
  71476. {
  71477. this.walls.left.shapes[0].collisionMask = this.walls.left.shapes[0].collisionMask | bitmask;
  71478. }
  71479. if (this.walls.right)
  71480. {
  71481. this.walls.right.shapes[0].collisionMask = this.walls.right.shapes[0].collisionMask | bitmask;
  71482. }
  71483. if (this.walls.top)
  71484. {
  71485. this.walls.top.shapes[0].collisionMask = this.walls.top.shapes[0].collisionMask | bitmask;
  71486. }
  71487. if (this.walls.bottom)
  71488. {
  71489. this.walls.bottom.shapes[0].collisionMask = this.walls.bottom.shapes[0].collisionMask | bitmask;
  71490. }
  71491. this._collisionGroupID++;
  71492. var group = new Phaser.Physics.P2.CollisionGroup(bitmask);
  71493. this.collisionGroups.push(group);
  71494. if (object)
  71495. {
  71496. this.setCollisionGroup(object, group);
  71497. }
  71498. return group;
  71499. },
  71500. /**
  71501. * Sets the given CollisionGroup to be the collision group for all shapes in this Body, unless a shape is specified.
  71502. * Note that this resets the collisionMask and any previously set groups. See Body.collides() for appending them.
  71503. *
  71504. * @method Phaser.Physics.P2y#setCollisionGroup
  71505. * @param {Phaser.Group|Phaser.Sprite} object - A Sprite or Group to apply the Collision Group to. If a Group is given it will be applied to all top-level children.
  71506. * @param {Phaser.Physics.CollisionGroup} group - The Collision Group that this Bodies shapes will use.
  71507. */
  71508. setCollisionGroup: function (object, group) {
  71509. if (object instanceof Phaser.Group)
  71510. {
  71511. for (var i = 0; i < object.total; i++)
  71512. {
  71513. if (object.children[i]['body'] && object.children[i]['body'].type === Phaser.Physics.P2JS)
  71514. {
  71515. object.children[i].body.setCollisionGroup(group);
  71516. }
  71517. }
  71518. }
  71519. else
  71520. {
  71521. object.body.setCollisionGroup(group);
  71522. }
  71523. },
  71524. /**
  71525. * Creates a linear spring, connecting two bodies. A spring can have a resting length, a stiffness and damping.
  71526. *
  71527. * @method Phaser.Physics.P2#createSpring
  71528. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body.
  71529. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body.
  71530. * @param {number} [restLength=1] - Rest length of the spring. A number > 0.
  71531. * @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0.
  71532. * @param {number} [damping=1] - Damping of the spring. A number >= 0.
  71533. * @param {Array} [worldA] - Where to hook the spring to body A in world coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32].
  71534. * @param {Array} [worldB] - Where to hook the spring to body B in world coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32].
  71535. * @param {Array} [localA] - Where to hook the spring to body A in local body coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32].
  71536. * @param {Array} [localB] - Where to hook the spring to body B in local body coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32].
  71537. * @return {Phaser.Physics.P2.Spring} The spring
  71538. */
  71539. createSpring: function (bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB) {
  71540. bodyA = this.getBody(bodyA);
  71541. bodyB = this.getBody(bodyB);
  71542. if (!bodyA || !bodyB)
  71543. {
  71544. console.warn('Cannot create Spring, invalid body objects given');
  71545. }
  71546. else
  71547. {
  71548. return this.addSpring(new Phaser.Physics.P2.Spring(this, bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB));
  71549. }
  71550. },
  71551. /**
  71552. * Creates a rotational spring, connecting two bodies. A spring can have a resting length, a stiffness and damping.
  71553. *
  71554. * @method Phaser.Physics.P2#createRotationalSpring
  71555. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body.
  71556. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body.
  71557. * @param {number} [restAngle] - The relative angle of bodies at which the spring is at rest. If not given, it's set to the current relative angle between the bodies.
  71558. * @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0.
  71559. * @param {number} [damping=1] - Damping of the spring. A number >= 0.
  71560. * @return {Phaser.Physics.P2.RotationalSpring} The spring
  71561. */
  71562. createRotationalSpring: function (bodyA, bodyB, restAngle, stiffness, damping) {
  71563. bodyA = this.getBody(bodyA);
  71564. bodyB = this.getBody(bodyB);
  71565. if (!bodyA || !bodyB)
  71566. {
  71567. console.warn('Cannot create Rotational Spring, invalid body objects given');
  71568. }
  71569. else
  71570. {
  71571. return this.addSpring(new Phaser.Physics.P2.RotationalSpring(this, bodyA, bodyB, restAngle, stiffness, damping));
  71572. }
  71573. },
  71574. /**
  71575. * Creates a new Body and adds it to the World.
  71576. *
  71577. * @method Phaser.Physics.P2#createBody
  71578. * @param {number} x - The x coordinate of Body.
  71579. * @param {number} y - The y coordinate of Body.
  71580. * @param {number} mass - The mass of the Body. A mass of 0 means a 'static' Body is created.
  71581. * @param {boolean} [addToWorld=false] - Automatically add this Body to the world? (usually false as it won't have any shapes on construction).
  71582. * @param {object} options - An object containing the build options:
  71583. * @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices.
  71584. * @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself.
  71585. * @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points.
  71586. * @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon.
  71587. * Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...],
  71588. * or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers.
  71589. * @return {Phaser.Physics.P2.Body} The body
  71590. */
  71591. createBody: function (x, y, mass, addToWorld, options, data) {
  71592. if (addToWorld === undefined) { addToWorld = false; }
  71593. var body = new Phaser.Physics.P2.Body(this.game, null, x, y, mass);
  71594. if (data)
  71595. {
  71596. var result = body.addPolygon(options, data);
  71597. if (!result)
  71598. {
  71599. return false;
  71600. }
  71601. }
  71602. if (addToWorld)
  71603. {
  71604. this.world.addBody(body.data);
  71605. }
  71606. return body;
  71607. },
  71608. /**
  71609. * Creates a new Particle and adds it to the World.
  71610. *
  71611. * @method Phaser.Physics.P2#createParticle
  71612. * @param {number} x - The x coordinate of Body.
  71613. * @param {number} y - The y coordinate of Body.
  71614. * @param {number} mass - The mass of the Body. A mass of 0 means a 'static' Body is created.
  71615. * @param {boolean} [addToWorld=false] - Automatically add this Body to the world? (usually false as it won't have any shapes on construction).
  71616. * @param {object} options - An object containing the build options:
  71617. * @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices.
  71618. * @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself.
  71619. * @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points.
  71620. * @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon.
  71621. * Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...],
  71622. * or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers.
  71623. */
  71624. createParticle: function (x, y, mass, addToWorld, options, data) {
  71625. if (addToWorld === undefined) { addToWorld = false; }
  71626. var body = new Phaser.Physics.P2.Body(this.game, null, x, y, mass);
  71627. if (data)
  71628. {
  71629. var result = body.addPolygon(options, data);
  71630. if (!result)
  71631. {
  71632. return false;
  71633. }
  71634. }
  71635. if (addToWorld)
  71636. {
  71637. this.world.addBody(body.data);
  71638. }
  71639. return body;
  71640. },
  71641. /**
  71642. * Converts all of the polylines objects inside a Tiled ObjectGroup into physics bodies that are added to the world.
  71643. * Note that the polylines must be created in such a way that they can withstand polygon decomposition.
  71644. *
  71645. * @method Phaser.Physics.P2#convertCollisionObjects
  71646. * @param {Phaser.Tilemap} map - The Tilemap to get the map data from.
  71647. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer.
  71648. * @param {boolean} [addToWorld=true] - If true it will automatically add each body to the world.
  71649. * @return {array} An array of the Phaser.Physics.Body objects that have been created.
  71650. */
  71651. convertCollisionObjects: function (map, layer, addToWorld) {
  71652. if (addToWorld === undefined) { addToWorld = true; }
  71653. var output = [];
  71654. for (var i = 0, len = map.collision[layer].length; i < len; i++)
  71655. {
  71656. // name: json.layers[i].objects[v].name,
  71657. // x: json.layers[i].objects[v].x,
  71658. // y: json.layers[i].objects[v].y,
  71659. // width: json.layers[i].objects[v].width,
  71660. // height: json.layers[i].objects[v].height,
  71661. // visible: json.layers[i].objects[v].visible,
  71662. // properties: json.layers[i].objects[v].properties,
  71663. // polyline: json.layers[i].objects[v].polyline
  71664. var object = map.collision[layer][i];
  71665. var body = this.createBody(object.x, object.y, 0, addToWorld, {}, object.polyline);
  71666. if (body)
  71667. {
  71668. output.push(body);
  71669. }
  71670. }
  71671. return output;
  71672. },
  71673. /**
  71674. * Clears all physics bodies from the given TilemapLayer that were created with `World.convertTilemap`.
  71675. *
  71676. * @method Phaser.Physics.P2#clearTilemapLayerBodies
  71677. * @param {Phaser.Tilemap} map - The Tilemap to get the map data from.
  71678. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer.
  71679. */
  71680. clearTilemapLayerBodies: function (map, layer) {
  71681. layer = map.getLayer(layer);
  71682. var i = map.layers[layer].bodies.length;
  71683. while (i--)
  71684. {
  71685. map.layers[layer].bodies[i].destroy();
  71686. }
  71687. map.layers[layer].bodies.length = 0;
  71688. },
  71689. /**
  71690. * Goes through all tiles in the given Tilemap and TilemapLayer and converts those set to collide into physics bodies.
  71691. * Only call this *after* you have specified all of the tiles you wish to collide with calls like Tilemap.setCollisionBetween, etc.
  71692. * Every time you call this method it will destroy any previously created bodies and remove them from the world.
  71693. * Therefore understand it's a very expensive operation and not to be done in a core game update loop.
  71694. *
  71695. * @method Phaser.Physics.P2#convertTilemap
  71696. * @param {Phaser.Tilemap} map - The Tilemap to get the map data from.
  71697. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer.
  71698. * @param {boolean} [addToWorld=true] - If true it will automatically add each body to the world, otherwise it's up to you to do so.
  71699. * @param {boolean} [optimize=true] - If true adjacent colliding tiles will be combined into a single body to save processing. However it means you cannot perform specific Tile to Body collision responses.
  71700. * @return {array} An array of the Phaser.Physics.P2.Body objects that were created.
  71701. */
  71702. convertTilemap: function (map, layer, addToWorld, optimize) {
  71703. layer = map.getLayer(layer);
  71704. if (addToWorld === undefined) { addToWorld = true; }
  71705. if (optimize === undefined) { optimize = true; }
  71706. // If the bodies array is already populated we need to nuke it
  71707. this.clearTilemapLayerBodies(map, layer);
  71708. var width = 0;
  71709. var sx = 0;
  71710. var sy = 0;
  71711. for (var y = 0, h = map.layers[layer].height; y < h; y++)
  71712. {
  71713. width = 0;
  71714. for (var x = 0, w = map.layers[layer].width; x < w; x++)
  71715. {
  71716. var tile = map.layers[layer].data[y][x];
  71717. if (tile && tile.index > -1 && tile.collides)
  71718. {
  71719. if (optimize)
  71720. {
  71721. var right = map.getTileRight(layer, x, y);
  71722. if (width === 0)
  71723. {
  71724. sx = tile.x * tile.width;
  71725. sy = tile.y * tile.height;
  71726. width = tile.width;
  71727. }
  71728. if (right && right.collides)
  71729. {
  71730. width += tile.width;
  71731. }
  71732. else
  71733. {
  71734. var body = this.createBody(sx, sy, 0, false);
  71735. body.addRectangle(width, tile.height, width / 2, tile.height / 2, 0);
  71736. if (addToWorld)
  71737. {
  71738. this.addBody(body);
  71739. }
  71740. map.layers[layer].bodies.push(body);
  71741. width = 0;
  71742. }
  71743. }
  71744. else
  71745. {
  71746. var body = this.createBody(tile.x * tile.width, tile.y * tile.height, 0, false);
  71747. body.addRectangle(tile.width, tile.height, tile.width / 2, tile.height / 2, 0);
  71748. if (addToWorld)
  71749. {
  71750. this.addBody(body);
  71751. }
  71752. map.layers[layer].bodies.push(body);
  71753. }
  71754. }
  71755. }
  71756. }
  71757. return map.layers[layer].bodies;
  71758. },
  71759. /**
  71760. * Convert p2 physics value (meters) to pixel scale.
  71761. * By default Phaser uses a scale of 20px per meter.
  71762. * If you need to modify this you can over-ride these functions via the Physics Configuration object.
  71763. *
  71764. * @method Phaser.Physics.P2#mpx
  71765. * @param {number} v - The value to convert.
  71766. * @return {number} The scaled value.
  71767. */
  71768. mpx: function (v) {
  71769. return v *= 20;
  71770. },
  71771. /**
  71772. * Convert pixel value to p2 physics scale (meters).
  71773. * By default Phaser uses a scale of 20px per meter.
  71774. * If you need to modify this you can over-ride these functions via the Physics Configuration object.
  71775. *
  71776. * @method Phaser.Physics.P2#pxm
  71777. * @param {number} v - The value to convert.
  71778. * @return {number} The scaled value.
  71779. */
  71780. pxm: function (v) {
  71781. return v * 0.05;
  71782. },
  71783. /**
  71784. * Convert p2 physics value (meters) to pixel scale and inverses it.
  71785. * By default Phaser uses a scale of 20px per meter.
  71786. * If you need to modify this you can over-ride these functions via the Physics Configuration object.
  71787. *
  71788. * @method Phaser.Physics.P2#mpxi
  71789. * @param {number} v - The value to convert.
  71790. * @return {number} The scaled value.
  71791. */
  71792. mpxi: function (v) {
  71793. return v *= -20;
  71794. },
  71795. /**
  71796. * Convert pixel value to p2 physics scale (meters) and inverses it.
  71797. * By default Phaser uses a scale of 20px per meter.
  71798. * If you need to modify this you can over-ride these functions via the Physics Configuration object.
  71799. *
  71800. * @method Phaser.Physics.P2#pxmi
  71801. * @param {number} v - The value to convert.
  71802. * @return {number} The scaled value.
  71803. */
  71804. pxmi: function (v) {
  71805. return v * -0.05;
  71806. }
  71807. };
  71808. /**
  71809. * @name Phaser.Physics.P2#friction
  71810. * @property {number} friction - Friction between colliding bodies. This value is used if no matching ContactMaterial is found for a Material pair.
  71811. */
  71812. Object.defineProperty(Phaser.Physics.P2.prototype, "friction", {
  71813. get: function () {
  71814. return this.world.defaultContactMaterial.friction;
  71815. },
  71816. set: function (value) {
  71817. this.world.defaultContactMaterial.friction = value;
  71818. }
  71819. });
  71820. /**
  71821. * @name Phaser.Physics.P2#restitution
  71822. * @property {number} restitution - Default coefficient of restitution between colliding bodies. This value is used if no matching ContactMaterial is found for a Material pair.
  71823. */
  71824. Object.defineProperty(Phaser.Physics.P2.prototype, "restitution", {
  71825. get: function () {
  71826. return this.world.defaultContactMaterial.restitution;
  71827. },
  71828. set: function (value) {
  71829. this.world.defaultContactMaterial.restitution = value;
  71830. }
  71831. });
  71832. /**
  71833. * @name Phaser.Physics.P2#contactMaterial
  71834. * @property {p2.ContactMaterial} contactMaterial - The default Contact Material being used by the World.
  71835. */
  71836. Object.defineProperty(Phaser.Physics.P2.prototype, "contactMaterial", {
  71837. get: function () {
  71838. return this.world.defaultContactMaterial;
  71839. },
  71840. set: function (value) {
  71841. this.world.defaultContactMaterial = value;
  71842. }
  71843. });
  71844. /**
  71845. * @name Phaser.Physics.P2#applySpringForces
  71846. * @property {boolean} applySpringForces - Enable to automatically apply spring forces each step.
  71847. */
  71848. Object.defineProperty(Phaser.Physics.P2.prototype, "applySpringForces", {
  71849. get: function () {
  71850. return this.world.applySpringForces;
  71851. },
  71852. set: function (value) {
  71853. this.world.applySpringForces = value;
  71854. }
  71855. });
  71856. /**
  71857. * @name Phaser.Physics.P2#applyDamping
  71858. * @property {boolean} applyDamping - Enable to automatically apply body damping each step.
  71859. */
  71860. Object.defineProperty(Phaser.Physics.P2.prototype, "applyDamping", {
  71861. get: function () {
  71862. return this.world.applyDamping;
  71863. },
  71864. set: function (value) {
  71865. this.world.applyDamping = value;
  71866. }
  71867. });
  71868. /**
  71869. * @name Phaser.Physics.P2#applyGravity
  71870. * @property {boolean} applyGravity - Enable to automatically apply gravity each step.
  71871. */
  71872. Object.defineProperty(Phaser.Physics.P2.prototype, "applyGravity", {
  71873. get: function () {
  71874. return this.world.applyGravity;
  71875. },
  71876. set: function (value) {
  71877. this.world.applyGravity = value;
  71878. }
  71879. });
  71880. /**
  71881. * @name Phaser.Physics.P2#solveConstraints
  71882. * @property {boolean} solveConstraints - Enable/disable constraint solving in each step.
  71883. */
  71884. Object.defineProperty(Phaser.Physics.P2.prototype, "solveConstraints", {
  71885. get: function () {
  71886. return this.world.solveConstraints;
  71887. },
  71888. set: function (value) {
  71889. this.world.solveConstraints = value;
  71890. }
  71891. });
  71892. /**
  71893. * @name Phaser.Physics.P2#time
  71894. * @property {boolean} time - The World time.
  71895. * @readonly
  71896. */
  71897. Object.defineProperty(Phaser.Physics.P2.prototype, "time", {
  71898. get: function () {
  71899. return this.world.time;
  71900. }
  71901. });
  71902. /**
  71903. * @name Phaser.Physics.P2#emitImpactEvent
  71904. * @property {boolean} emitImpactEvent - Set to true if you want to the world to emit the "impact" event. Turning this off could improve performance.
  71905. */
  71906. Object.defineProperty(Phaser.Physics.P2.prototype, "emitImpactEvent", {
  71907. get: function () {
  71908. return this.world.emitImpactEvent;
  71909. },
  71910. set: function (value) {
  71911. this.world.emitImpactEvent = value;
  71912. }
  71913. });
  71914. /**
  71915. * How to deactivate bodies during simulation. Possible modes are: World.NO_SLEEPING, World.BODY_SLEEPING and World.ISLAND_SLEEPING.
  71916. * If sleeping is enabled, you might need to wake up the bodies if they fall asleep when they shouldn't. If you want to enable sleeping in the world, but want to disable it for a particular body, see Body.allowSleep.
  71917. * @name Phaser.Physics.P2#sleepMode
  71918. * @property {number} sleepMode
  71919. */
  71920. Object.defineProperty(Phaser.Physics.P2.prototype, "sleepMode", {
  71921. get: function () {
  71922. return this.world.sleepMode;
  71923. },
  71924. set: function (value) {
  71925. this.world.sleepMode = value;
  71926. }
  71927. });
  71928. /**
  71929. * @name Phaser.Physics.P2#total
  71930. * @property {number} total - The total number of bodies in the world.
  71931. * @readonly
  71932. */
  71933. Object.defineProperty(Phaser.Physics.P2.prototype, "total", {
  71934. get: function () {
  71935. return this.world.bodies.length;
  71936. }
  71937. });
  71938. /* jshint noarg: false */
  71939. /**
  71940. * @author Georgios Kaleadis https://github.com/georgiee
  71941. * @author Richard Davey <rich@photonstorm.com>
  71942. * @copyright 2016 Photon Storm Ltd.
  71943. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  71944. */
  71945. /**
  71946. * Allow to access a list of created fixture (coming from Body#addPhaserPolygon)
  71947. * which itself parse the input from PhysicsEditor with the custom phaser exporter.
  71948. * You can access fixtures of a Body by a group index or even by providing a fixture Key.
  71949. * You can set the fixture key and also the group index for a fixture in PhysicsEditor.
  71950. * This gives you the power to create a complex body built of many fixtures and modify them
  71951. * during runtime (to remove parts, set masks, categories & sensor properties)
  71952. *
  71953. * @class Phaser.Physics.P2.FixtureList
  71954. * @constructor
  71955. * @param {Array} list - A list of fixtures (from Phaser.Physics.P2.Body#addPhaserPolygon)
  71956. */
  71957. Phaser.Physics.P2.FixtureList = function (list) {
  71958. if (!Array.isArray(list))
  71959. {
  71960. list = [list];
  71961. }
  71962. this.rawList = list;
  71963. this.init();
  71964. this.parse(this.rawList);
  71965. };
  71966. Phaser.Physics.P2.FixtureList.prototype = {
  71967. /**
  71968. * @method Phaser.Physics.P2.FixtureList#init
  71969. */
  71970. init: function () {
  71971. /**
  71972. * @property {object} namedFixtures - Collect all fixtures with a key
  71973. * @private
  71974. */
  71975. this.namedFixtures = {};
  71976. /**
  71977. * @property {Array} groupedFixtures - Collect all given fixtures per group index. Notice: Every fixture with a key also belongs to a group
  71978. * @private
  71979. */
  71980. this.groupedFixtures = [];
  71981. /**
  71982. * @property {Array} allFixtures - This is a list of everything in this collection
  71983. * @private
  71984. */
  71985. this.allFixtures = [];
  71986. },
  71987. /**
  71988. * @method Phaser.Physics.P2.FixtureList#setCategory
  71989. * @param {number} bit - The bit to set as the collision group.
  71990. * @param {string} fixtureKey - Only apply to the fixture with the given key.
  71991. */
  71992. setCategory: function (bit, fixtureKey) {
  71993. var setter = function(fixture) {
  71994. fixture.collisionGroup = bit;
  71995. };
  71996. this.getFixtures(fixtureKey).forEach(setter);
  71997. },
  71998. /**
  71999. * @method Phaser.Physics.P2.FixtureList#setMask
  72000. * @param {number} bit - The bit to set as the collision mask
  72001. * @param {string} fixtureKey - Only apply to the fixture with the given key
  72002. */
  72003. setMask: function (bit, fixtureKey) {
  72004. var setter = function(fixture) {
  72005. fixture.collisionMask = bit;
  72006. };
  72007. this.getFixtures(fixtureKey).forEach(setter);
  72008. },
  72009. /**
  72010. * @method Phaser.Physics.P2.FixtureList#setSensor
  72011. * @param {boolean} value - sensor true or false
  72012. * @param {string} fixtureKey - Only apply to the fixture with the given key
  72013. */
  72014. setSensor: function (value, fixtureKey) {
  72015. var setter = function(fixture) {
  72016. fixture.sensor = value;
  72017. };
  72018. this.getFixtures(fixtureKey).forEach(setter);
  72019. },
  72020. /**
  72021. * @method Phaser.Physics.P2.FixtureList#setMaterial
  72022. * @param {Object} material - The contact material for a fixture
  72023. * @param {string} fixtureKey - Only apply to the fixture with the given key
  72024. */
  72025. setMaterial: function (material, fixtureKey) {
  72026. var setter = function(fixture) {
  72027. fixture.material = material;
  72028. };
  72029. this.getFixtures(fixtureKey).forEach(setter);
  72030. },
  72031. /**
  72032. * Accessor to get either a list of specified fixtures by key or the whole fixture list
  72033. *
  72034. * @method Phaser.Physics.P2.FixtureList#getFixtures
  72035. * @param {array} keys - A list of fixture keys
  72036. */
  72037. getFixtures: function (keys) {
  72038. var fixtures = [];
  72039. if (keys)
  72040. {
  72041. if (!(keys instanceof Array))
  72042. {
  72043. keys = [keys];
  72044. }
  72045. var self = this;
  72046. keys.forEach(function(key) {
  72047. if (self.namedFixtures[key])
  72048. {
  72049. fixtures.push(self.namedFixtures[key]);
  72050. }
  72051. });
  72052. return this.flatten(fixtures);
  72053. }
  72054. else
  72055. {
  72056. return this.allFixtures;
  72057. }
  72058. },
  72059. /**
  72060. * Accessor to get either a single fixture by its key.
  72061. *
  72062. * @method Phaser.Physics.P2.FixtureList#getFixtureByKey
  72063. * @param {string} key - The key of the fixture.
  72064. */
  72065. getFixtureByKey: function (key) {
  72066. return this.namedFixtures[key];
  72067. },
  72068. /**
  72069. * Accessor to get a group of fixtures by its group index.
  72070. *
  72071. * @method Phaser.Physics.P2.FixtureList#getGroup
  72072. * @param {number} groupID - The group index.
  72073. */
  72074. getGroup: function (groupID) {
  72075. return this.groupedFixtures[groupID];
  72076. },
  72077. /**
  72078. * Parser for the output of Phaser.Physics.P2.Body#addPhaserPolygon
  72079. *
  72080. * @method Phaser.Physics.P2.FixtureList#parse
  72081. */
  72082. parse: function () {
  72083. var key, value, _ref, _results;
  72084. _ref = this.rawList;
  72085. _results = [];
  72086. for (key in _ref)
  72087. {
  72088. value = _ref[key];
  72089. if (!isNaN(key - 0))
  72090. {
  72091. this.groupedFixtures[key] = this.groupedFixtures[key] || [];
  72092. this.groupedFixtures[key] = this.groupedFixtures[key].concat(value);
  72093. }
  72094. else
  72095. {
  72096. this.namedFixtures[key] = this.flatten(value);
  72097. }
  72098. _results.push(this.allFixtures = this.flatten(this.groupedFixtures));
  72099. }
  72100. },
  72101. /**
  72102. * A helper to flatten arrays. This is very useful as the fixtures are nested from time to time due to the way P2 creates and splits polygons.
  72103. *
  72104. * @method Phaser.Physics.P2.FixtureList#flatten
  72105. * @param {array} array - The array to flatten. Notice: This will happen recursive not shallow.
  72106. */
  72107. flatten: function (array) {
  72108. var result, self;
  72109. result = [];
  72110. self = arguments.callee;
  72111. array.forEach(function(item) {
  72112. return Array.prototype.push.apply(result, (Array.isArray(item) ? self(item) : [item]));
  72113. });
  72114. return result;
  72115. }
  72116. };
  72117. /**
  72118. * @author Richard Davey <rich@photonstorm.com>
  72119. * @copyright 2016 Photon Storm Ltd.
  72120. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  72121. */
  72122. /**
  72123. * A PointProxy is an internal class that allows for direct getter/setter style property access to Arrays and TypedArrays.
  72124. *
  72125. * @class Phaser.Physics.P2.PointProxy
  72126. * @constructor
  72127. * @param {Phaser.Physics.P2} world - A reference to the P2 World.
  72128. * @param {any} destination - The object to bind to.
  72129. */
  72130. Phaser.Physics.P2.PointProxy = function (world, destination) {
  72131. this.world = world;
  72132. this.destination = destination;
  72133. };
  72134. Phaser.Physics.P2.PointProxy.prototype.constructor = Phaser.Physics.P2.PointProxy;
  72135. /**
  72136. * @name Phaser.Physics.P2.PointProxy#x
  72137. * @property {number} x - The x property of this PointProxy get and set in pixels.
  72138. */
  72139. Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "x", {
  72140. get: function () {
  72141. return this.world.mpx(this.destination[0]);
  72142. },
  72143. set: function (value) {
  72144. this.destination[0] = this.world.pxm(value);
  72145. }
  72146. });
  72147. /**
  72148. * @name Phaser.Physics.P2.PointProxy#y
  72149. * @property {number} y - The y property of this PointProxy get and set in pixels.
  72150. */
  72151. Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "y", {
  72152. get: function () {
  72153. return this.world.mpx(this.destination[1]);
  72154. },
  72155. set: function (value) {
  72156. this.destination[1] = this.world.pxm(value);
  72157. }
  72158. });
  72159. /**
  72160. * @name Phaser.Physics.P2.PointProxy#mx
  72161. * @property {number} mx - The x property of this PointProxy get and set in meters.
  72162. */
  72163. Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "mx", {
  72164. get: function () {
  72165. return this.destination[0];
  72166. },
  72167. set: function (value) {
  72168. this.destination[0] = value;
  72169. }
  72170. });
  72171. /**
  72172. * @name Phaser.Physics.P2.PointProxy#my
  72173. * @property {number} my - The x property of this PointProxy get and set in meters.
  72174. */
  72175. Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "my", {
  72176. get: function () {
  72177. return this.destination[1];
  72178. },
  72179. set: function (value) {
  72180. this.destination[1] = value;
  72181. }
  72182. });
  72183. /**
  72184. * @author Richard Davey <rich@photonstorm.com>
  72185. * @copyright 2016 Photon Storm Ltd.
  72186. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  72187. */
  72188. /**
  72189. * A InversePointProxy is an internal class that allows for direct getter/setter style property access to Arrays and TypedArrays but inverses the values on set.
  72190. *
  72191. * @class Phaser.Physics.P2.InversePointProxy
  72192. * @constructor
  72193. * @param {Phaser.Physics.P2} world - A reference to the P2 World.
  72194. * @param {any} destination - The object to bind to.
  72195. */
  72196. Phaser.Physics.P2.InversePointProxy = function (world, destination) {
  72197. this.world = world;
  72198. this.destination = destination;
  72199. };
  72200. Phaser.Physics.P2.InversePointProxy.prototype.constructor = Phaser.Physics.P2.InversePointProxy;
  72201. /**
  72202. * @name Phaser.Physics.P2.InversePointProxy#x
  72203. * @property {number} x - The x property of this InversePointProxy get and set in pixels.
  72204. */
  72205. Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "x", {
  72206. get: function () {
  72207. return this.world.mpxi(this.destination[0]);
  72208. },
  72209. set: function (value) {
  72210. this.destination[0] = this.world.pxmi(value);
  72211. }
  72212. });
  72213. /**
  72214. * @name Phaser.Physics.P2.InversePointProxy#y
  72215. * @property {number} y - The y property of this InversePointProxy get and set in pixels.
  72216. */
  72217. Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "y", {
  72218. get: function () {
  72219. return this.world.mpxi(this.destination[1]);
  72220. },
  72221. set: function (value) {
  72222. this.destination[1] = this.world.pxmi(value);
  72223. }
  72224. });
  72225. /**
  72226. * @name Phaser.Physics.P2.InversePointProxy#mx
  72227. * @property {number} mx - The x property of this InversePointProxy get and set in meters.
  72228. */
  72229. Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "mx", {
  72230. get: function () {
  72231. return this.destination[0];
  72232. },
  72233. set: function (value) {
  72234. this.destination[0] = -value;
  72235. }
  72236. });
  72237. /**
  72238. * @name Phaser.Physics.P2.InversePointProxy#my
  72239. * @property {number} my - The y property of this InversePointProxy get and set in meters.
  72240. */
  72241. Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "my", {
  72242. get: function () {
  72243. return this.destination[1];
  72244. },
  72245. set: function (value) {
  72246. this.destination[1] = -value;
  72247. }
  72248. });
  72249. /**
  72250. * @author Richard Davey <rich@photonstorm.com>
  72251. * @copyright 2016 Photon Storm Ltd.
  72252. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  72253. */
  72254. /**
  72255. * The Physics Body is typically linked to a single Sprite and defines properties that determine how the physics body is simulated.
  72256. * These properties affect how the body reacts to forces, what forces it generates on itself (to simulate friction), and how it reacts to collisions in the scene.
  72257. * In most cases, the properties are used to simulate physical effects. Each body also has its own property values that determine exactly how it reacts to forces and collisions in the scene.
  72258. * By default a single Rectangle shape is added to the Body that matches the dimensions of the parent Sprite. See addShape, removeShape, clearShapes to add extra shapes around the Body.
  72259. * Note: When bound to a Sprite to avoid single-pixel jitters on mobile devices we strongly recommend using Sprite sizes that are even on both axis, i.e. 128x128 not 127x127.
  72260. * Note: When a game object is given a P2 body it has its anchor x/y set to 0.5, so it becomes centered.
  72261. *
  72262. * @class Phaser.Physics.P2.Body
  72263. * @constructor
  72264. * @param {Phaser.Game} game - Game reference to the currently running game.
  72265. * @param {Phaser.Sprite} [sprite] - The Sprite object this physics body belongs to.
  72266. * @param {number} [x=0] - The x coordinate of this Body.
  72267. * @param {number} [y=0] - The y coordinate of this Body.
  72268. * @param {number} [mass=1] - The default mass of this Body (0 = static).
  72269. */
  72270. Phaser.Physics.P2.Body = function (game, sprite, x, y, mass) {
  72271. sprite = sprite || null;
  72272. x = x || 0;
  72273. y = y || 0;
  72274. if (mass === undefined) { mass = 1; }
  72275. /**
  72276. * @property {Phaser.Game} game - Local reference to game.
  72277. */
  72278. this.game = game;
  72279. /**
  72280. * @property {Phaser.Physics.P2} world - Local reference to the P2 World.
  72281. */
  72282. this.world = game.physics.p2;
  72283. /**
  72284. * @property {Phaser.Sprite} sprite - Reference to the parent Sprite.
  72285. */
  72286. this.sprite = sprite;
  72287. /**
  72288. * @property {number} type - The type of physics system this body belongs to.
  72289. */
  72290. this.type = Phaser.Physics.P2JS;
  72291. /**
  72292. * @property {Phaser.Point} offset - The offset of the Physics Body from the Sprite x/y position.
  72293. */
  72294. this.offset = new Phaser.Point();
  72295. /**
  72296. * @property {p2.Body} data - The p2 Body data.
  72297. * @protected
  72298. */
  72299. this.data = new p2.Body({ position: [ this.world.pxmi(x), this.world.pxmi(y) ], mass: mass });
  72300. this.data.parent = this;
  72301. /**
  72302. * @property {Phaser.Physics.P2.InversePointProxy} velocity - The velocity of the body. Set velocity.x to a negative value to move to the left, position to the right. velocity.y negative values move up, positive move down.
  72303. */
  72304. this.velocity = new Phaser.Physics.P2.InversePointProxy(this.world, this.data.velocity);
  72305. /**
  72306. * @property {Phaser.Physics.P2.InversePointProxy} force - The force applied to the body.
  72307. */
  72308. this.force = new Phaser.Physics.P2.InversePointProxy(this.world, this.data.force);
  72309. /**
  72310. * @property {Phaser.Point} gravity - A locally applied gravity force to the Body. Applied directly before the world step. NOTE: Not currently implemented.
  72311. */
  72312. this.gravity = new Phaser.Point();
  72313. /**
  72314. * Dispatched when a first contact is created between shapes in two bodies.
  72315. * This event is fired during the step, so collision has already taken place.
  72316. *
  72317. * The event will be sent 5 arguments in this order:
  72318. *
  72319. * The Phaser.Physics.P2.Body it is in contact with. *This might be null* if the Body was created directly in the p2 world.
  72320. * The p2.Body this Body is in contact with.
  72321. * The Shape from this body that caused the contact.
  72322. * The Shape from the contact body.
  72323. * The Contact Equation data array.
  72324. *
  72325. * @property {Phaser.Signal} onBeginContact
  72326. */
  72327. this.onBeginContact = new Phaser.Signal();
  72328. /**
  72329. * Dispatched when contact ends between shapes in two bodies.
  72330. * This event is fired during the step, so collision has already taken place.
  72331. *
  72332. * The event will be sent 4 arguments in this order:
  72333. *
  72334. * The Phaser.Physics.P2.Body it is in contact with. *This might be null* if the Body was created directly in the p2 world.
  72335. * The p2.Body this Body has ended contact with.
  72336. * The Shape from this body that caused the original contact.
  72337. * The Shape from the contact body.
  72338. *
  72339. * @property {Phaser.Signal} onEndContact
  72340. */
  72341. this.onEndContact = new Phaser.Signal();
  72342. /**
  72343. * @property {array} collidesWith - Array of CollisionGroups that this Bodies shapes collide with.
  72344. */
  72345. this.collidesWith = [];
  72346. /**
  72347. * @property {boolean} removeNextStep - To avoid deleting this body during a physics step, and causing all kinds of problems, set removeNextStep to true to have it removed in the next preUpdate.
  72348. */
  72349. this.removeNextStep = false;
  72350. /**
  72351. * @property {Phaser.Physics.P2.BodyDebug} debugBody - Reference to the debug body.
  72352. */
  72353. this.debugBody = null;
  72354. /**
  72355. * @property {boolean} dirty - Internally used by Sprite.x/y
  72356. */
  72357. this.dirty = false;
  72358. /**
  72359. * @property {boolean} _collideWorldBounds - Internal var that determines if this Body collides with the world bounds or not.
  72360. * @private
  72361. */
  72362. this._collideWorldBounds = true;
  72363. /**
  72364. * @property {object} _bodyCallbacks - Array of Body callbacks.
  72365. * @private
  72366. */
  72367. this._bodyCallbacks = {};
  72368. /**
  72369. * @property {object} _bodyCallbackContext - Array of Body callback contexts.
  72370. * @private
  72371. */
  72372. this._bodyCallbackContext = {};
  72373. /**
  72374. * @property {object} _groupCallbacks - Array of Group callbacks.
  72375. * @private
  72376. */
  72377. this._groupCallbacks = {};
  72378. /**
  72379. * @property {object} _bodyCallbackContext - Array of Grouo callback contexts.
  72380. * @private
  72381. */
  72382. this._groupCallbackContext = {};
  72383. /**
  72384. * @property {boolean} _reset - Internal var.
  72385. * @private
  72386. */
  72387. this._reset = false;
  72388. // Set-up the default shape
  72389. if (sprite)
  72390. {
  72391. this.setRectangleFromSprite(sprite);
  72392. if (sprite.exists)
  72393. {
  72394. this.game.physics.p2.addBody(this);
  72395. }
  72396. }
  72397. };
  72398. Phaser.Physics.P2.Body.prototype = {
  72399. /**
  72400. * Sets a callback to be fired any time a shape in this Body impacts with a shape in the given Body. The impact test is performed against body.id values.
  72401. * The callback will be sent 4 parameters: This body, the body that impacted, the Shape in this body and the shape in the impacting body.
  72402. * Note that the impact event happens after collision resolution, so it cannot be used to prevent a collision from happening.
  72403. * It also happens mid-step. So do not destroy a Body during this callback, instead set safeDestroy to true so it will be killed on the next preUpdate.
  72404. *
  72405. * @method Phaser.Physics.P2.Body#createBodyCallback
  72406. * @param {Phaser.Sprite|Phaser.TileSprite|Phaser.Physics.P2.Body|p2.Body} object - The object to send impact events for.
  72407. * @param {function} callback - The callback to fire on impact. Set to null to clear a previously set callback.
  72408. * @param {object} callbackContext - The context under which the callback will fire.
  72409. */
  72410. createBodyCallback: function (object, callback, callbackContext) {
  72411. var id = -1;
  72412. if (object['id'])
  72413. {
  72414. id = object.id;
  72415. }
  72416. else if (object['body'])
  72417. {
  72418. id = object.body.id;
  72419. }
  72420. if (id > -1)
  72421. {
  72422. if (callback === null)
  72423. {
  72424. delete (this._bodyCallbacks[id]);
  72425. delete (this._bodyCallbackContext[id]);
  72426. }
  72427. else
  72428. {
  72429. this._bodyCallbacks[id] = callback;
  72430. this._bodyCallbackContext[id] = callbackContext;
  72431. }
  72432. }
  72433. },
  72434. /**
  72435. * Sets a callback to be fired any time this Body impacts with the given Group. The impact test is performed against shape.collisionGroup values.
  72436. * The callback will be sent 4 parameters: This body, the body that impacted, the Shape in this body and the shape in the impacting body.
  72437. * This callback will only fire if this Body has been assigned a collision group.
  72438. * Note that the impact event happens after collision resolution, so it cannot be used to prevent a collision from happening.
  72439. * It also happens mid-step. So do not destroy a Body during this callback, instead set safeDestroy to true so it will be killed on the next preUpdate.
  72440. *
  72441. * @method Phaser.Physics.P2.Body#createGroupCallback
  72442. * @param {Phaser.Physics.CollisionGroup} group - The Group to send impact events for.
  72443. * @param {function} callback - The callback to fire on impact. Set to null to clear a previously set callback.
  72444. * @param {object} callbackContext - The context under which the callback will fire.
  72445. */
  72446. createGroupCallback: function (group, callback, callbackContext) {
  72447. if (callback === null)
  72448. {
  72449. delete (this._groupCallbacks[group.mask]);
  72450. delete (this._groupCallbackContext[group.mask]);
  72451. }
  72452. else
  72453. {
  72454. this._groupCallbacks[group.mask] = callback;
  72455. this._groupCallbackContext[group.mask] = callbackContext;
  72456. }
  72457. },
  72458. /**
  72459. * Gets the collision bitmask from the groups this body collides with.
  72460. *
  72461. * @method Phaser.Physics.P2.Body#getCollisionMask
  72462. * @return {number} The bitmask.
  72463. */
  72464. getCollisionMask: function () {
  72465. var mask = 0;
  72466. if (this._collideWorldBounds)
  72467. {
  72468. mask = this.game.physics.p2.boundsCollisionGroup.mask;
  72469. }
  72470. for (var i = 0; i < this.collidesWith.length; i++)
  72471. {
  72472. mask = mask | this.collidesWith[i].mask;
  72473. }
  72474. return mask;
  72475. },
  72476. /**
  72477. * Updates the collisionMask.
  72478. *
  72479. * @method Phaser.Physics.P2.Body#updateCollisionMask
  72480. * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision group will be added to all Shapes in this Body.
  72481. */
  72482. updateCollisionMask: function (shape) {
  72483. var mask = this.getCollisionMask();
  72484. if (shape === undefined)
  72485. {
  72486. for (var i = this.data.shapes.length - 1; i >= 0; i--)
  72487. {
  72488. this.data.shapes[i].collisionMask = mask;
  72489. }
  72490. }
  72491. else
  72492. {
  72493. shape.collisionMask = mask;
  72494. }
  72495. },
  72496. /**
  72497. * Sets the given CollisionGroup to be the collision group for all shapes in this Body, unless a shape is specified.
  72498. * This also resets the collisionMask.
  72499. *
  72500. * @method Phaser.Physics.P2.Body#setCollisionGroup
  72501. * @param {Phaser.Physics.CollisionGroup} group - The Collision Group that this Bodies shapes will use.
  72502. * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision group will be added to all Shapes in this Body.
  72503. */
  72504. setCollisionGroup: function (group, shape) {
  72505. var mask = this.getCollisionMask();
  72506. if (shape === undefined)
  72507. {
  72508. for (var i = this.data.shapes.length - 1; i >= 0; i--)
  72509. {
  72510. this.data.shapes[i].collisionGroup = group.mask;
  72511. this.data.shapes[i].collisionMask = mask;
  72512. }
  72513. }
  72514. else
  72515. {
  72516. shape.collisionGroup = group.mask;
  72517. shape.collisionMask = mask;
  72518. }
  72519. },
  72520. /**
  72521. * Clears the collision data from the shapes in this Body. Optionally clears Group and/or Mask.
  72522. *
  72523. * @method Phaser.Physics.P2.Body#clearCollision
  72524. * @param {boolean} [clearGroup=true] - Clear the collisionGroup value from the shape/s?
  72525. * @param {boolean} [clearMask=true] - Clear the collisionMask value from the shape/s?
  72526. * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision data will be cleared from all Shapes in this Body.
  72527. */
  72528. clearCollision: function (clearGroup, clearMask, shape) {
  72529. if (clearGroup === undefined) { clearGroup = true; }
  72530. if (clearMask === undefined) { clearMask = true; }
  72531. if (shape === undefined)
  72532. {
  72533. for (var i = this.data.shapes.length - 1; i >= 0; i--)
  72534. {
  72535. if (clearGroup)
  72536. {
  72537. this.data.shapes[i].collisionGroup = null;
  72538. }
  72539. if (clearMask)
  72540. {
  72541. this.data.shapes[i].collisionMask = null;
  72542. }
  72543. }
  72544. }
  72545. else
  72546. {
  72547. if (clearGroup)
  72548. {
  72549. shape.collisionGroup = null;
  72550. }
  72551. if (clearMask)
  72552. {
  72553. shape.collisionMask = null;
  72554. }
  72555. }
  72556. if (clearGroup)
  72557. {
  72558. this.collidesWith.length = 0;
  72559. }
  72560. },
  72561. /**
  72562. * Removes the given CollisionGroup, or array of CollisionGroups, from the list of groups that this body will collide with and updates the collision masks.
  72563. *
  72564. * @method Phaser.Physics.P2.Body#removeCollisionGroup
  72565. * @param {Phaser.Physics.CollisionGroup|array} group - The Collision Group or Array of Collision Groups that this Bodies shapes should not collide with anymore.
  72566. * @param {boolean} [clearCallback=true] - Clear the callback that will be triggered when this Body impacts with the given Group?
  72567. * @param {p2.Shape} [shape] - An optional Shape. If not provided the updated collision mask will be added to all Shapes in this Body.
  72568. */
  72569. removeCollisionGroup: function (group, clearCallback, shape) {
  72570. if (clearCallback === undefined) { clearCallback = true; }
  72571. var index;
  72572. if (Array.isArray(group))
  72573. {
  72574. for (var i = 0; i < group.length; i++)
  72575. {
  72576. index = this.collidesWith.indexOf(group[i]);
  72577. if (index > -1)
  72578. {
  72579. this.collidesWith.splice(index, 1);
  72580. if (clearCallback)
  72581. {
  72582. delete (this._groupCallbacks[group.mask]);
  72583. delete (this._groupCallbackContext[group.mask]);
  72584. }
  72585. }
  72586. }
  72587. }
  72588. else
  72589. {
  72590. index = this.collidesWith.indexOf(group);
  72591. if (index > -1)
  72592. {
  72593. this.collidesWith.splice(index, 1);
  72594. if (clearCallback)
  72595. {
  72596. delete (this._groupCallbacks[group.mask]);
  72597. delete (this._groupCallbackContext[group.mask]);
  72598. }
  72599. }
  72600. }
  72601. var mask = this.getCollisionMask();
  72602. if (shape === undefined)
  72603. {
  72604. for (var i = this.data.shapes.length - 1; i >= 0; i--)
  72605. {
  72606. this.data.shapes[i].collisionMask = mask;
  72607. }
  72608. }
  72609. else
  72610. {
  72611. shape.collisionMask = mask;
  72612. }
  72613. },
  72614. /**
  72615. * Adds the given CollisionGroup, or array of CollisionGroups, to the list of groups that this body will collide with and updates the collision masks.
  72616. *
  72617. * @method Phaser.Physics.P2.Body#collides
  72618. * @param {Phaser.Physics.CollisionGroup|array} group - The Collision Group or Array of Collision Groups that this Bodies shapes will collide with.
  72619. * @param {function} [callback] - Optional callback that will be triggered when this Body impacts with the given Group.
  72620. * @param {object} [callbackContext] - The context under which the callback will be called.
  72621. * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision mask will be added to all Shapes in this Body.
  72622. */
  72623. collides: function (group, callback, callbackContext, shape) {
  72624. if (Array.isArray(group))
  72625. {
  72626. for (var i = 0; i < group.length; i++)
  72627. {
  72628. if (this.collidesWith.indexOf(group[i]) === -1)
  72629. {
  72630. this.collidesWith.push(group[i]);
  72631. if (callback)
  72632. {
  72633. this.createGroupCallback(group[i], callback, callbackContext);
  72634. }
  72635. }
  72636. }
  72637. }
  72638. else
  72639. {
  72640. if (this.collidesWith.indexOf(group) === -1)
  72641. {
  72642. this.collidesWith.push(group);
  72643. if (callback)
  72644. {
  72645. this.createGroupCallback(group, callback, callbackContext);
  72646. }
  72647. }
  72648. }
  72649. var mask = this.getCollisionMask();
  72650. if (shape === undefined)
  72651. {
  72652. for (var i = this.data.shapes.length - 1; i >= 0; i--)
  72653. {
  72654. this.data.shapes[i].collisionMask = mask;
  72655. }
  72656. }
  72657. else
  72658. {
  72659. shape.collisionMask = mask;
  72660. }
  72661. },
  72662. /**
  72663. * Moves the shape offsets so their center of mass becomes the body center of mass.
  72664. *
  72665. * @method Phaser.Physics.P2.Body#adjustCenterOfMass
  72666. */
  72667. adjustCenterOfMass: function () {
  72668. this.data.adjustCenterOfMass();
  72669. this.shapeChanged();
  72670. },
  72671. /**
  72672. * Gets the velocity of a point in the body.
  72673. *
  72674. * @method Phaser.Physics.P2.Body#getVelocityAtPoint
  72675. * @param {Array} result - A vector to store the result in.
  72676. * @param {Array} relativePoint - A world oriented vector, indicating the position of the point to get the velocity from.
  72677. * @return {Array} The result vector.
  72678. */
  72679. getVelocityAtPoint: function (result, relativePoint) {
  72680. return this.data.getVelocityAtPoint(result, relativePoint);
  72681. },
  72682. /**
  72683. * Apply damping, see http://code.google.com/p/bullet/issues/detail?id=74 for details.
  72684. *
  72685. * @method Phaser.Physics.P2.Body#applyDamping
  72686. * @param {number} dt - Current time step.
  72687. */
  72688. applyDamping: function (dt) {
  72689. this.data.applyDamping(dt);
  72690. },
  72691. /**
  72692. * Apply impulse to a point relative to the body.
  72693. * This could for example be a point on the Body surface. An impulse is a force added to a body during a short
  72694. * period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity.
  72695. *
  72696. * @method Phaser.Physics.P2.Body#applyImpulse
  72697. * @param {Float32Array|Array} impulse - The impulse vector to add, oriented in world space.
  72698. * @param {number} worldX - A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be exerted on the center of mass.
  72699. * @param {number} worldY - A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be exerted on the center of mass.
  72700. */
  72701. applyImpulse: function (impulse, worldX, worldY) {
  72702. this.data.applyImpulse(impulse, [this.world.pxmi(worldX), this.world.pxmi(worldY)]);
  72703. },
  72704. /**
  72705. * Apply impulse to a point local to the body.
  72706. *
  72707. * This could for example be a point on the Body surface. An impulse is a force added to a body during a short
  72708. * period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity.
  72709. *
  72710. * @method Phaser.Physics.P2.Body#applyImpulseLocal
  72711. * @param {Float32Array|Array} impulse - The impulse vector to add, oriented in local space.
  72712. * @param {number} localX - A local point on the body.
  72713. * @param {number} localY - A local point on the body.
  72714. */
  72715. applyImpulseLocal: function (impulse, localX, localY) {
  72716. this.data.applyImpulseLocal(impulse, [this.world.pxmi(localX), this.world.pxmi(localY)]);
  72717. },
  72718. /**
  72719. * Apply force to a world point.
  72720. *
  72721. * This could for example be a point on the RigidBody surface. Applying force
  72722. * this way will add to Body.force and Body.angularForce.
  72723. *
  72724. * @method Phaser.Physics.P2.Body#applyForce
  72725. * @param {Float32Array|Array} force - The force vector to add.
  72726. * @param {number} worldX - The world x point to apply the force on.
  72727. * @param {number} worldY - The world y point to apply the force on.
  72728. */
  72729. applyForce: function (force, worldX, worldY) {
  72730. this.data.applyForce(force, [this.world.pxmi(worldX), this.world.pxmi(worldY)]);
  72731. },
  72732. /**
  72733. * Sets the force on the body to zero.
  72734. *
  72735. * @method Phaser.Physics.P2.Body#setZeroForce
  72736. */
  72737. setZeroForce: function () {
  72738. this.data.setZeroForce();
  72739. },
  72740. /**
  72741. * If this Body is dynamic then this will zero its angular velocity.
  72742. *
  72743. * @method Phaser.Physics.P2.Body#setZeroRotation
  72744. */
  72745. setZeroRotation: function () {
  72746. this.data.angularVelocity = 0;
  72747. },
  72748. /**
  72749. * If this Body is dynamic then this will zero its velocity on both axis.
  72750. *
  72751. * @method Phaser.Physics.P2.Body#setZeroVelocity
  72752. */
  72753. setZeroVelocity: function () {
  72754. this.data.velocity[0] = 0;
  72755. this.data.velocity[1] = 0;
  72756. },
  72757. /**
  72758. * Sets the Body damping and angularDamping to zero.
  72759. *
  72760. * @method Phaser.Physics.P2.Body#setZeroDamping
  72761. */
  72762. setZeroDamping: function () {
  72763. this.data.damping = 0;
  72764. this.data.angularDamping = 0;
  72765. },
  72766. /**
  72767. * Transform a world point to local body frame.
  72768. *
  72769. * @method Phaser.Physics.P2.Body#toLocalFrame
  72770. * @param {Float32Array|Array} out - The vector to store the result in.
  72771. * @param {Float32Array|Array} worldPoint - The input world vector.
  72772. */
  72773. toLocalFrame: function (out, worldPoint) {
  72774. return this.data.toLocalFrame(out, worldPoint);
  72775. },
  72776. /**
  72777. * Transform a local point to world frame.
  72778. *
  72779. * @method Phaser.Physics.P2.Body#toWorldFrame
  72780. * @param {Array} out - The vector to store the result in.
  72781. * @param {Array} localPoint - The input local vector.
  72782. */
  72783. toWorldFrame: function (out, localPoint) {
  72784. return this.data.toWorldFrame(out, localPoint);
  72785. },
  72786. /**
  72787. * This will rotate the Body by the given speed to the left (counter-clockwise).
  72788. *
  72789. * @method Phaser.Physics.P2.Body#rotateLeft
  72790. * @param {number} speed - The speed at which it should rotate.
  72791. */
  72792. rotateLeft: function (speed) {
  72793. this.data.angularVelocity = this.world.pxm(-speed);
  72794. },
  72795. /**
  72796. * This will rotate the Body by the given speed to the left (clockwise).
  72797. *
  72798. * @method Phaser.Physics.P2.Body#rotateRight
  72799. * @param {number} speed - The speed at which it should rotate.
  72800. */
  72801. rotateRight: function (speed) {
  72802. this.data.angularVelocity = this.world.pxm(speed);
  72803. },
  72804. /**
  72805. * Moves the Body forwards based on its current angle and the given speed.
  72806. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
  72807. *
  72808. * @method Phaser.Physics.P2.Body#moveForward
  72809. * @param {number} speed - The speed at which it should move forwards.
  72810. */
  72811. moveForward: function (speed) {
  72812. var magnitude = this.world.pxmi(-speed);
  72813. var angle = this.data.angle + Math.PI / 2;
  72814. this.data.velocity[0] = magnitude * Math.cos(angle);
  72815. this.data.velocity[1] = magnitude * Math.sin(angle);
  72816. },
  72817. /**
  72818. * Moves the Body backwards based on its current angle and the given speed.
  72819. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
  72820. *
  72821. * @method Phaser.Physics.P2.Body#moveBackward
  72822. * @param {number} speed - The speed at which it should move backwards.
  72823. */
  72824. moveBackward: function (speed) {
  72825. var magnitude = this.world.pxmi(-speed);
  72826. var angle = this.data.angle + Math.PI / 2;
  72827. this.data.velocity[0] = -(magnitude * Math.cos(angle));
  72828. this.data.velocity[1] = -(magnitude * Math.sin(angle));
  72829. },
  72830. /**
  72831. * Applies a force to the Body that causes it to 'thrust' forwards, based on its current angle and the given speed.
  72832. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
  72833. *
  72834. * @method Phaser.Physics.P2.Body#thrust
  72835. * @param {number} speed - The speed at which it should thrust.
  72836. */
  72837. thrust: function (speed) {
  72838. var magnitude = this.world.pxmi(-speed);
  72839. var angle = this.data.angle + Math.PI / 2;
  72840. this.data.force[0] += magnitude * Math.cos(angle);
  72841. this.data.force[1] += magnitude * Math.sin(angle);
  72842. },
  72843. /**
  72844. * Applies a force to the Body that causes it to 'thrust' to the left, based on its current angle and the given speed.
  72845. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
  72846. *
  72847. * @method Phaser.Physics.P2.Body#thrustLeft
  72848. * @param {number} speed - The speed at which it should move to the left.
  72849. */
  72850. thrustLeft: function (speed) {
  72851. var magnitude = this.world.pxmi(-speed);
  72852. var angle = this.data.angle;
  72853. this.data.force[0] += magnitude * Math.cos(angle);
  72854. this.data.force[1] += magnitude * Math.sin(angle);
  72855. },
  72856. /**
  72857. * Applies a force to the Body that causes it to 'thrust' to the right, based on its current angle and the given speed.
  72858. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
  72859. *
  72860. * @method Phaser.Physics.P2.Body#thrustRight
  72861. * @param {number} speed - The speed at which it should move to the right.
  72862. */
  72863. thrustRight: function (speed) {
  72864. var magnitude = this.world.pxmi(-speed);
  72865. var angle = this.data.angle;
  72866. this.data.force[0] -= magnitude * Math.cos(angle);
  72867. this.data.force[1] -= magnitude * Math.sin(angle);
  72868. },
  72869. /**
  72870. * Applies a force to the Body that causes it to 'thrust' backwards (in reverse), based on its current angle and the given speed.
  72871. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
  72872. *
  72873. * @method Phaser.Physics.P2.Body#reverse
  72874. * @param {number} speed - The speed at which it should reverse.
  72875. */
  72876. reverse: function (speed) {
  72877. var magnitude = this.world.pxmi(-speed);
  72878. var angle = this.data.angle + Math.PI / 2;
  72879. this.data.force[0] -= magnitude * Math.cos(angle);
  72880. this.data.force[1] -= magnitude * Math.sin(angle);
  72881. },
  72882. /**
  72883. * If this Body is dynamic then this will move it to the left by setting its x velocity to the given speed.
  72884. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
  72885. *
  72886. * @method Phaser.Physics.P2.Body#moveLeft
  72887. * @param {number} speed - The speed at which it should move to the left, in pixels per second.
  72888. */
  72889. moveLeft: function (speed) {
  72890. this.data.velocity[0] = this.world.pxmi(-speed);
  72891. },
  72892. /**
  72893. * If this Body is dynamic then this will move it to the right by setting its x velocity to the given speed.
  72894. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
  72895. *
  72896. * @method Phaser.Physics.P2.Body#moveRight
  72897. * @param {number} speed - The speed at which it should move to the right, in pixels per second.
  72898. */
  72899. moveRight: function (speed) {
  72900. this.data.velocity[0] = this.world.pxmi(speed);
  72901. },
  72902. /**
  72903. * If this Body is dynamic then this will move it up by setting its y velocity to the given speed.
  72904. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
  72905. *
  72906. * @method Phaser.Physics.P2.Body#moveUp
  72907. * @param {number} speed - The speed at which it should move up, in pixels per second.
  72908. */
  72909. moveUp: function (speed) {
  72910. this.data.velocity[1] = this.world.pxmi(-speed);
  72911. },
  72912. /**
  72913. * If this Body is dynamic then this will move it down by setting its y velocity to the given speed.
  72914. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
  72915. *
  72916. * @method Phaser.Physics.P2.Body#moveDown
  72917. * @param {number} speed - The speed at which it should move down, in pixels per second.
  72918. */
  72919. moveDown: function (speed) {
  72920. this.data.velocity[1] = this.world.pxmi(speed);
  72921. },
  72922. /**
  72923. * Internal method. This is called directly before the sprites are sent to the renderer and after the update function has finished.
  72924. *
  72925. * @method Phaser.Physics.P2.Body#preUpdate
  72926. * @protected
  72927. */
  72928. preUpdate: function () {
  72929. this.dirty = true;
  72930. if (this.removeNextStep)
  72931. {
  72932. this.removeFromWorld();
  72933. this.removeNextStep = false;
  72934. }
  72935. },
  72936. /**
  72937. * Internal method. This is called directly before the sprites are sent to the renderer and after the update function has finished.
  72938. *
  72939. * @method Phaser.Physics.P2.Body#postUpdate
  72940. * @protected
  72941. */
  72942. postUpdate: function () {
  72943. this.sprite.x = this.world.mpxi(this.data.position[0]) + this.offset.x;
  72944. this.sprite.y = this.world.mpxi(this.data.position[1]) + this.offset.y;
  72945. if (!this.fixedRotation)
  72946. {
  72947. this.sprite.rotation = this.data.angle;
  72948. }
  72949. if (this.debugBody)
  72950. {
  72951. this.debugBody.updateSpriteTransform();
  72952. }
  72953. this.dirty = false;
  72954. },
  72955. /**
  72956. * Resets the Body force, velocity (linear and angular) and rotation. Optionally resets damping and mass.
  72957. *
  72958. * @method Phaser.Physics.P2.Body#reset
  72959. * @param {number} x - The new x position of the Body.
  72960. * @param {number} y - The new x position of the Body.
  72961. * @param {boolean} [resetDamping=false] - Resets the linear and angular damping.
  72962. * @param {boolean} [resetMass=false] - Sets the Body mass back to 1.
  72963. */
  72964. reset: function (x, y, resetDamping, resetMass) {
  72965. if (resetDamping === undefined) { resetDamping = false; }
  72966. if (resetMass === undefined) { resetMass = false; }
  72967. this.setZeroForce();
  72968. this.setZeroVelocity();
  72969. this.setZeroRotation();
  72970. if (resetDamping)
  72971. {
  72972. this.setZeroDamping();
  72973. }
  72974. if (resetMass)
  72975. {
  72976. this.mass = 1;
  72977. }
  72978. this.x = x;
  72979. this.y = y;
  72980. },
  72981. /**
  72982. * Adds this physics body to the world.
  72983. *
  72984. * @method Phaser.Physics.P2.Body#addToWorld
  72985. */
  72986. addToWorld: function () {
  72987. if (this.game.physics.p2._toRemove)
  72988. {
  72989. for (var i = 0; i < this.game.physics.p2._toRemove.length; i++)
  72990. {
  72991. if (this.game.physics.p2._toRemove[i] === this)
  72992. {
  72993. this.game.physics.p2._toRemove.splice(i, 1);
  72994. }
  72995. }
  72996. }
  72997. if (this.data.world !== this.game.physics.p2.world)
  72998. {
  72999. this.game.physics.p2.addBody(this);
  73000. }
  73001. },
  73002. /**
  73003. * Removes this physics body from the world.
  73004. *
  73005. * @method Phaser.Physics.P2.Body#removeFromWorld
  73006. */
  73007. removeFromWorld: function () {
  73008. if (this.data.world === this.game.physics.p2.world)
  73009. {
  73010. this.game.physics.p2.removeBodyNextStep(this);
  73011. }
  73012. },
  73013. /**
  73014. * Destroys this Body and all references it holds to other objects.
  73015. *
  73016. * @method Phaser.Physics.P2.Body#destroy
  73017. */
  73018. destroy: function () {
  73019. this.removeFromWorld();
  73020. this.clearShapes();
  73021. this._bodyCallbacks = {};
  73022. this._bodyCallbackContext = {};
  73023. this._groupCallbacks = {};
  73024. this._groupCallbackContext = {};
  73025. if (this.debugBody)
  73026. {
  73027. this.debugBody.destroy(true, true);
  73028. }
  73029. this.debugBody = null;
  73030. if (this.sprite)
  73031. {
  73032. this.sprite.body = null;
  73033. this.sprite = null;
  73034. }
  73035. },
  73036. /**
  73037. * Removes all Shapes from this Body.
  73038. *
  73039. * @method Phaser.Physics.P2.Body#clearShapes
  73040. */
  73041. clearShapes: function () {
  73042. var i = this.data.shapes.length;
  73043. while (i--)
  73044. {
  73045. this.data.removeShape(this.data.shapes[i]);
  73046. }
  73047. this.shapeChanged();
  73048. },
  73049. /**
  73050. * Add a shape to the body. You can pass a local transform when adding a shape, so that the shape gets an offset and an angle relative to the body center of mass.
  73051. * Will automatically update the mass properties and bounding radius.
  73052. * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates.
  73053. *
  73054. * @method Phaser.Physics.P2.Body#addShape
  73055. * @param {p2.Shape} shape - The shape to add to the body.
  73056. * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass.
  73057. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass.
  73058. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians.
  73059. * @return {p2.Shape} The shape that was added to the body.
  73060. */
  73061. addShape: function (shape, offsetX, offsetY, rotation) {
  73062. if (offsetX === undefined) { offsetX = 0; }
  73063. if (offsetY === undefined) { offsetY = 0; }
  73064. if (rotation === undefined) { rotation = 0; }
  73065. this.data.addShape(shape, [this.world.pxmi(offsetX), this.world.pxmi(offsetY)], rotation);
  73066. this.shapeChanged();
  73067. return shape;
  73068. },
  73069. /**
  73070. * Adds a Circle shape to this Body. You can control the offset from the center of the body and the rotation.
  73071. *
  73072. * @method Phaser.Physics.P2.Body#addCircle
  73073. * @param {number} radius - The radius of this circle (in pixels)
  73074. * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass.
  73075. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass.
  73076. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians.
  73077. * @return {p2.Circle} The Circle shape that was added to the Body.
  73078. */
  73079. addCircle: function (radius, offsetX, offsetY, rotation) {
  73080. var shape = new p2.Circle({ radius: this.world.pxm(radius) });
  73081. return this.addShape(shape, offsetX, offsetY, rotation);
  73082. },
  73083. /**
  73084. * Adds a Rectangle shape to this Body. You can control the offset from the center of the body and the rotation.
  73085. *
  73086. * @method Phaser.Physics.P2.Body#addRectangle
  73087. * @param {number} width - The width of the rectangle in pixels.
  73088. * @param {number} height - The height of the rectangle in pixels.
  73089. * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass.
  73090. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass.
  73091. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians.
  73092. * @return {p2.Box} The shape that was added to the Body.
  73093. */
  73094. addRectangle: function (width, height, offsetX, offsetY, rotation) {
  73095. var shape = new p2.Box({ width: this.world.pxm(width), height: this.world.pxm(height)});
  73096. return this.addShape(shape, offsetX, offsetY, rotation);
  73097. },
  73098. /**
  73099. * Adds a Plane shape to this Body. The plane is facing in the Y direction. You can control the offset from the center of the body and the rotation.
  73100. *
  73101. * @method Phaser.Physics.P2.Body#addPlane
  73102. * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass.
  73103. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass.
  73104. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians.
  73105. * @return {p2.Plane} The Plane shape that was added to the Body.
  73106. */
  73107. addPlane: function (offsetX, offsetY, rotation) {
  73108. var shape = new p2.Plane();
  73109. return this.addShape(shape, offsetX, offsetY, rotation);
  73110. },
  73111. /**
  73112. * Adds a Particle shape to this Body. You can control the offset from the center of the body and the rotation.
  73113. *
  73114. * @method Phaser.Physics.P2.Body#addParticle
  73115. * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass.
  73116. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass.
  73117. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians.
  73118. * @return {p2.Particle} The Particle shape that was added to the Body.
  73119. */
  73120. addParticle: function (offsetX, offsetY, rotation) {
  73121. var shape = new p2.Particle();
  73122. return this.addShape(shape, offsetX, offsetY, rotation);
  73123. },
  73124. /**
  73125. * Adds a Line shape to this Body.
  73126. * The line shape is along the x direction, and stretches from [-length/2, 0] to [length/2,0].
  73127. * You can control the offset from the center of the body and the rotation.
  73128. *
  73129. * @method Phaser.Physics.P2.Body#addLine
  73130. * @param {number} length - The length of this line (in pixels)
  73131. * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass.
  73132. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass.
  73133. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians.
  73134. * @return {p2.Line} The Line shape that was added to the Body.
  73135. */
  73136. addLine: function (length, offsetX, offsetY, rotation) {
  73137. var shape = new p2.Line({ length: this.world.pxm(length)});
  73138. return this.addShape(shape, offsetX, offsetY, rotation);
  73139. },
  73140. /**
  73141. * Adds a Capsule shape to this Body.
  73142. * You can control the offset from the center of the body and the rotation.
  73143. *
  73144. * @method Phaser.Physics.P2.Body#addCapsule
  73145. * @param {number} length - The distance between the end points in pixels.
  73146. * @param {number} radius - Radius of the capsule in pixels.
  73147. * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass.
  73148. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass.
  73149. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians.
  73150. * @return {p2.Capsule} The Capsule shape that was added to the Body.
  73151. */
  73152. addCapsule: function (length, radius, offsetX, offsetY, rotation) {
  73153. var shape = new p2.Capsule({ length: this.world.pxm(length), radius: this.world.pxm(radius) });
  73154. return this.addShape(shape, offsetX, offsetY, rotation);
  73155. },
  73156. /**
  73157. * Reads a polygon shape path, and assembles convex shapes from that and puts them at proper offset points. The shape must be simple and without holes.
  73158. * This function expects the x.y values to be given in pixels. If you want to provide them at p2 world scales then call Body.data.fromPolygon directly.
  73159. *
  73160. * @method Phaser.Physics.P2.Body#addPolygon
  73161. * @param {object} options - An object containing the build options:
  73162. * @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices.
  73163. * @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself.
  73164. * @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points.
  73165. * @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon.
  73166. * Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...],
  73167. * or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers.
  73168. * @return {boolean} True on success, else false.
  73169. */
  73170. addPolygon: function (options, points) {
  73171. options = options || {};
  73172. if (!Array.isArray(points))
  73173. {
  73174. points = Array.prototype.slice.call(arguments, 1);
  73175. }
  73176. var path = [];
  73177. // Did they pass in a single array of points?
  73178. if (points.length === 1 && Array.isArray(points[0]))
  73179. {
  73180. path = points[0].slice(0);
  73181. }
  73182. else if (Array.isArray(points[0]))
  73183. {
  73184. path = points.slice();
  73185. }
  73186. else if (typeof points[0] === 'number')
  73187. {
  73188. // We've a list of numbers
  73189. for (var i = 0, len = points.length; i < len; i += 2)
  73190. {
  73191. path.push([points[i], points[i + 1]]);
  73192. }
  73193. }
  73194. // top and tail
  73195. var idx = path.length - 1;
  73196. if (path[idx][0] === path[0][0] && path[idx][1] === path[0][1])
  73197. {
  73198. path.pop();
  73199. }
  73200. // Now process them into p2 values
  73201. for (var p = 0; p < path.length; p++)
  73202. {
  73203. path[p][0] = this.world.pxmi(path[p][0]);
  73204. path[p][1] = this.world.pxmi(path[p][1]);
  73205. }
  73206. var result = this.data.fromPolygon(path, options);
  73207. this.shapeChanged();
  73208. return result;
  73209. },
  73210. /**
  73211. * Remove a shape from the body. Will automatically update the mass properties and bounding radius.
  73212. *
  73213. * @method Phaser.Physics.P2.Body#removeShape
  73214. * @param {p2.Circle|p2.Rectangle|p2.Plane|p2.Line|p2.Particle} shape - The shape to remove from the body.
  73215. * @return {boolean} True if the shape was found and removed, else false.
  73216. */
  73217. removeShape: function (shape) {
  73218. var result = this.data.removeShape(shape);
  73219. this.shapeChanged();
  73220. return result;
  73221. },
  73222. /**
  73223. * Clears any previously set shapes. Then creates a new Circle shape and adds it to this Body.
  73224. * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates.
  73225. *
  73226. * @method Phaser.Physics.P2.Body#setCircle
  73227. * @param {number} radius - The radius of this circle (in pixels)
  73228. * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass.
  73229. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass.
  73230. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians.
  73231. */
  73232. setCircle: function (radius, offsetX, offsetY, rotation) {
  73233. this.clearShapes();
  73234. return this.addCircle(radius, offsetX, offsetY, rotation);
  73235. },
  73236. /**
  73237. * Clears any previously set shapes. The creates a new Rectangle shape at the given size and offset, and adds it to this Body.
  73238. * If you wish to create a Rectangle to match the size of a Sprite or Image see Body.setRectangleFromSprite.
  73239. * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates.
  73240. *
  73241. * @method Phaser.Physics.P2.Body#setRectangle
  73242. * @param {number} [width=16] - The width of the rectangle in pixels.
  73243. * @param {number} [height=16] - The height of the rectangle in pixels.
  73244. * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass.
  73245. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass.
  73246. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians.
  73247. * @return {p2.Rectangle} The Rectangle shape that was added to the Body.
  73248. */
  73249. setRectangle: function (width, height, offsetX, offsetY, rotation) {
  73250. if (width === undefined) { width = 16; }
  73251. if (height === undefined) { height = 16; }
  73252. this.clearShapes();
  73253. return this.addRectangle(width, height, offsetX, offsetY, rotation);
  73254. },
  73255. /**
  73256. * Clears any previously set shapes.
  73257. * Then creates a Rectangle shape sized to match the dimensions and orientation of the Sprite given.
  73258. * If no Sprite is given it defaults to using the parent of this Body.
  73259. * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates.
  73260. *
  73261. * @method Phaser.Physics.P2.Body#setRectangleFromSprite
  73262. * @param {Phaser.Sprite|Phaser.Image} [sprite] - The Sprite on which the Rectangle will get its dimensions.
  73263. * @return {p2.Rectangle} The Rectangle shape that was added to the Body.
  73264. */
  73265. setRectangleFromSprite: function (sprite) {
  73266. if (sprite === undefined) { sprite = this.sprite; }
  73267. this.clearShapes();
  73268. return this.addRectangle(sprite.width, sprite.height, 0, 0, sprite.rotation);
  73269. },
  73270. /**
  73271. * Adds the given Material to all Shapes that belong to this Body.
  73272. * If you only wish to apply it to a specific Shape in this Body then provide that as the 2nd parameter.
  73273. *
  73274. * @method Phaser.Physics.P2.Body#setMaterial
  73275. * @param {Phaser.Physics.P2.Material} material - The Material that will be applied.
  73276. * @param {p2.Shape} [shape] - An optional Shape. If not provided the Material will be added to all Shapes in this Body.
  73277. */
  73278. setMaterial: function (material, shape) {
  73279. if (shape === undefined)
  73280. {
  73281. for (var i = this.data.shapes.length - 1; i >= 0; i--)
  73282. {
  73283. this.data.shapes[i].material = material;
  73284. }
  73285. }
  73286. else
  73287. {
  73288. shape.material = material;
  73289. }
  73290. },
  73291. /**
  73292. * Updates the debug draw if any body shapes change.
  73293. *
  73294. * @method Phaser.Physics.P2.Body#shapeChanged
  73295. */
  73296. shapeChanged: function() {
  73297. if (this.debugBody)
  73298. {
  73299. this.debugBody.draw();
  73300. }
  73301. },
  73302. /**
  73303. * Reads the shape data from a physics data file stored in the Game.Cache and adds it as a polygon to this Body.
  73304. * The shape data format is based on the output of the
  73305. * {@link https://github.com/photonstorm/phaser/tree/master/resources/PhysicsEditor%20Exporter|custom phaser exporter} for
  73306. * {@link https://www.codeandweb.com/physicseditor|PhysicsEditor}
  73307. *
  73308. * @method Phaser.Physics.P2.Body#addPhaserPolygon
  73309. * @param {string} key - The key of the Physics Data file as stored in Game.Cache.
  73310. * @param {string} object - The key of the object within the Physics data file that you wish to load the shape data from.
  73311. * @returns {Array} A list of created fixtures to be used with Phaser.Physics.P2.FixtureList
  73312. */
  73313. addPhaserPolygon: function (key, object) {
  73314. var data = this.game.cache.getPhysicsData(key, object);
  73315. var createdFixtures = [];
  73316. // Cycle through the fixtures
  73317. for (var i = 0; i < data.length; i++)
  73318. {
  73319. var fixtureData = data[i];
  73320. var shapesOfFixture = this.addFixture(fixtureData);
  73321. // Always add to a group
  73322. createdFixtures[fixtureData.filter.group] = createdFixtures[fixtureData.filter.group] || [];
  73323. createdFixtures[fixtureData.filter.group] = createdFixtures[fixtureData.filter.group].concat(shapesOfFixture);
  73324. // if (unique) fixture key is provided
  73325. if (fixtureData.fixtureKey)
  73326. {
  73327. createdFixtures[fixtureData.fixtureKey] = shapesOfFixture;
  73328. }
  73329. }
  73330. this.data.aabbNeedsUpdate = true;
  73331. this.shapeChanged();
  73332. return createdFixtures;
  73333. },
  73334. /**
  73335. * Add a polygon fixture. This is used during #loadPolygon.
  73336. *
  73337. * @method Phaser.Physics.P2.Body#addFixture
  73338. * @param {string} fixtureData - The data for the fixture. It contains: isSensor, filter (collision) and the actual polygon shapes.
  73339. * @return {array} An array containing the generated shapes for the given polygon.
  73340. */
  73341. addFixture: function (fixtureData) {
  73342. var generatedShapes = [];
  73343. if (fixtureData.circle)
  73344. {
  73345. var shape = new p2.Circle({ radius: this.world.pxm(fixtureData.circle.radius) });
  73346. shape.collisionGroup = fixtureData.filter.categoryBits;
  73347. shape.collisionMask = fixtureData.filter.maskBits;
  73348. shape.sensor = fixtureData.isSensor;
  73349. var offset = p2.vec2.create();
  73350. offset[0] = this.world.pxmi(fixtureData.circle.position[0] - this.sprite.width/2);
  73351. offset[1] = this.world.pxmi(fixtureData.circle.position[1] - this.sprite.height/2);
  73352. this.data.addShape(shape, offset);
  73353. generatedShapes.push(shape);
  73354. }
  73355. else
  73356. {
  73357. var polygons = fixtureData.polygons;
  73358. var cm = p2.vec2.create();
  73359. for (var i = 0; i < polygons.length; i++)
  73360. {
  73361. var shapes = polygons[i];
  73362. var vertices = [];
  73363. for (var s = 0; s < shapes.length; s += 2)
  73364. {
  73365. vertices.push([ this.world.pxmi(shapes[s]), this.world.pxmi(shapes[s + 1]) ]);
  73366. }
  73367. var shape = new p2.Convex({ vertices: vertices });
  73368. // Move all vertices so its center of mass is in the local center of the convex
  73369. for (var j = 0; j !== shape.vertices.length; j++)
  73370. {
  73371. var v = shape.vertices[j];
  73372. p2.vec2.sub(v, v, shape.centerOfMass);
  73373. }
  73374. p2.vec2.scale(cm, shape.centerOfMass, 1);
  73375. cm[0] -= this.world.pxmi(this.sprite.width / 2);
  73376. cm[1] -= this.world.pxmi(this.sprite.height / 2);
  73377. shape.updateTriangles();
  73378. shape.updateCenterOfMass();
  73379. shape.updateBoundingRadius();
  73380. shape.collisionGroup = fixtureData.filter.categoryBits;
  73381. shape.collisionMask = fixtureData.filter.maskBits;
  73382. shape.sensor = fixtureData.isSensor;
  73383. this.data.addShape(shape, cm);
  73384. generatedShapes.push(shape);
  73385. }
  73386. }
  73387. return generatedShapes;
  73388. },
  73389. /**
  73390. * Reads the shape data from a physics data file stored in the Game.Cache and adds it as a polygon to this Body.
  73391. *
  73392. * As well as reading the data from the Cache you can also pass `null` as the first argument and a
  73393. * physics data object as the second. When doing this you must ensure the structure of the object is correct in advance.
  73394. *
  73395. * For more details see the format of the Lime / Corona Physics Editor export.
  73396. *
  73397. * @method Phaser.Physics.P2.Body#loadPolygon
  73398. * @param {string} key - The key of the Physics Data file as stored in Game.Cache. Alternatively set to `null` and pass the
  73399. * data as the 2nd argument.
  73400. * @param {string|object} object - The key of the object within the Physics data file that you wish to load the shape data from,
  73401. * or if key is null pass the actual physics data object itself as this parameter.
  73402. * @return {boolean} True on success, else false.
  73403. */
  73404. loadPolygon: function (key, object) {
  73405. if (key === null)
  73406. {
  73407. var data = object;
  73408. }
  73409. else
  73410. {
  73411. var data = this.game.cache.getPhysicsData(key, object);
  73412. }
  73413. // We've multiple Convex shapes, they should be CCW automatically
  73414. var cm = p2.vec2.create();
  73415. for (var i = 0; i < data.length; i++)
  73416. {
  73417. var vertices = [];
  73418. for (var s = 0; s < data[i].shape.length; s += 2)
  73419. {
  73420. vertices.push([ this.world.pxmi(data[i].shape[s]), this.world.pxmi(data[i].shape[s + 1]) ]);
  73421. }
  73422. var c = new p2.Convex({ vertices: vertices });
  73423. // Move all vertices so its center of mass is in the local center of the convex
  73424. for (var j = 0; j !== c.vertices.length; j++)
  73425. {
  73426. var v = c.vertices[j];
  73427. p2.vec2.sub(v, v, c.centerOfMass);
  73428. }
  73429. p2.vec2.scale(cm, c.centerOfMass, 1);
  73430. cm[0] -= this.world.pxmi(this.sprite.width / 2);
  73431. cm[1] -= this.world.pxmi(this.sprite.height / 2);
  73432. c.updateTriangles();
  73433. c.updateCenterOfMass();
  73434. c.updateBoundingRadius();
  73435. this.data.addShape(c, cm);
  73436. }
  73437. this.data.aabbNeedsUpdate = true;
  73438. this.shapeChanged();
  73439. return true;
  73440. }
  73441. };
  73442. Phaser.Physics.P2.Body.prototype.constructor = Phaser.Physics.P2.Body;
  73443. /**
  73444. * Dynamic body. Dynamic bodies body can move and respond to collisions and forces.
  73445. * @property DYNAMIC
  73446. * @type {Number}
  73447. * @static
  73448. */
  73449. Phaser.Physics.P2.Body.DYNAMIC = 1;
  73450. /**
  73451. * Static body. Static bodies do not move, and they do not respond to forces or collision.
  73452. * @property STATIC
  73453. * @type {Number}
  73454. * @static
  73455. */
  73456. Phaser.Physics.P2.Body.STATIC = 2;
  73457. /**
  73458. * Kinematic body. Kinematic bodies only moves according to its .velocity, and does not respond to collisions or force.
  73459. * @property KINEMATIC
  73460. * @type {Number}
  73461. * @static
  73462. */
  73463. Phaser.Physics.P2.Body.KINEMATIC = 4;
  73464. /**
  73465. * @name Phaser.Physics.P2.Body#static
  73466. * @property {boolean} static - Returns true if the Body is static. Setting Body.static to 'false' will make it dynamic.
  73467. */
  73468. Object.defineProperty(Phaser.Physics.P2.Body.prototype, "static", {
  73469. get: function () {
  73470. return (this.data.type === Phaser.Physics.P2.Body.STATIC);
  73471. },
  73472. set: function (value) {
  73473. if (value && this.data.type !== Phaser.Physics.P2.Body.STATIC)
  73474. {
  73475. this.data.type = Phaser.Physics.P2.Body.STATIC;
  73476. this.mass = 0;
  73477. }
  73478. else if (!value && this.data.type === Phaser.Physics.P2.Body.STATIC)
  73479. {
  73480. this.data.type = Phaser.Physics.P2.Body.DYNAMIC;
  73481. this.mass = 1;
  73482. }
  73483. }
  73484. });
  73485. /**
  73486. * @name Phaser.Physics.P2.Body#dynamic
  73487. * @property {boolean} dynamic - Returns true if the Body is dynamic. Setting Body.dynamic to 'false' will make it static.
  73488. */
  73489. Object.defineProperty(Phaser.Physics.P2.Body.prototype, "dynamic", {
  73490. get: function () {
  73491. return (this.data.type === Phaser.Physics.P2.Body.DYNAMIC);
  73492. },
  73493. set: function (value) {
  73494. if (value && this.data.type !== Phaser.Physics.P2.Body.DYNAMIC)
  73495. {
  73496. this.data.type = Phaser.Physics.P2.Body.DYNAMIC;
  73497. this.mass = 1;
  73498. }
  73499. else if (!value && this.data.type === Phaser.Physics.P2.Body.DYNAMIC)
  73500. {
  73501. this.data.type = Phaser.Physics.P2.Body.STATIC;
  73502. this.mass = 0;
  73503. }
  73504. }
  73505. });
  73506. /**
  73507. * @name Phaser.Physics.P2.Body#kinematic
  73508. * @property {boolean} kinematic - Returns true if the Body is kinematic. Setting Body.kinematic to 'false' will make it static.
  73509. */
  73510. Object.defineProperty(Phaser.Physics.P2.Body.prototype, "kinematic", {
  73511. get: function () {
  73512. return (this.data.type === Phaser.Physics.P2.Body.KINEMATIC);
  73513. },
  73514. set: function (value) {
  73515. if (value && this.data.type !== Phaser.Physics.P2.Body.KINEMATIC)
  73516. {
  73517. this.data.type = Phaser.Physics.P2.Body.KINEMATIC;
  73518. this.mass = 4;
  73519. }
  73520. else if (!value && this.data.type === Phaser.Physics.P2.Body.KINEMATIC)
  73521. {
  73522. this.data.type = Phaser.Physics.P2.Body.STATIC;
  73523. this.mass = 0;
  73524. }
  73525. }
  73526. });
  73527. /**
  73528. * @name Phaser.Physics.P2.Body#allowSleep
  73529. * @property {boolean} allowSleep -
  73530. */
  73531. Object.defineProperty(Phaser.Physics.P2.Body.prototype, "allowSleep", {
  73532. get: function () {
  73533. return this.data.allowSleep;
  73534. },
  73535. set: function (value) {
  73536. if (value !== this.data.allowSleep)
  73537. {
  73538. this.data.allowSleep = value;
  73539. }
  73540. }
  73541. });
  73542. /**
  73543. * The angle of the Body in degrees from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation.
  73544. * Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement Body.angle = 450 is the same as Body.angle = 90.
  73545. * If you wish to work in radians instead of degrees use the property Body.rotation instead. Working in radians is faster as it doesn't have to convert values.
  73546. *
  73547. * @name Phaser.Physics.P2.Body#angle
  73548. * @property {number} angle - The angle of this Body in degrees.
  73549. */
  73550. Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angle", {
  73551. get: function() {
  73552. return Phaser.Math.wrapAngle(Phaser.Math.radToDeg(this.data.angle));
  73553. },
  73554. set: function(value) {
  73555. this.data.angle = Phaser.Math.degToRad(Phaser.Math.wrapAngle(value));
  73556. }
  73557. });
  73558. /**
  73559. * Damping is specified as a value between 0 and 1, which is the proportion of velocity lost per second.
  73560. * @name Phaser.Physics.P2.Body#angularDamping
  73561. * @property {number} angularDamping - The angular damping acting acting on the body.
  73562. */
  73563. Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularDamping", {
  73564. get: function () {
  73565. return this.data.angularDamping;
  73566. },
  73567. set: function (value) {
  73568. this.data.angularDamping = value;
  73569. }
  73570. });
  73571. /**
  73572. * @name Phaser.Physics.P2.Body#angularForce
  73573. * @property {number} angularForce - The angular force acting on the body.
  73574. */
  73575. Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularForce", {
  73576. get: function () {
  73577. return this.data.angularForce;
  73578. },
  73579. set: function (value) {
  73580. this.data.angularForce = value;
  73581. }
  73582. });
  73583. /**
  73584. * @name Phaser.Physics.P2.Body#angularVelocity
  73585. * @property {number} angularVelocity - The angular velocity of the body.
  73586. */
  73587. Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularVelocity", {
  73588. get: function () {
  73589. return this.data.angularVelocity;
  73590. },
  73591. set: function (value) {
  73592. this.data.angularVelocity = value;
  73593. }
  73594. });
  73595. /**
  73596. * Damping is specified as a value between 0 and 1, which is the proportion of velocity lost per second.
  73597. * @name Phaser.Physics.P2.Body#damping
  73598. * @property {number} damping - The linear damping acting on the body in the velocity direction.
  73599. */
  73600. Object.defineProperty(Phaser.Physics.P2.Body.prototype, "damping", {
  73601. get: function () {
  73602. return this.data.damping;
  73603. },
  73604. set: function (value) {
  73605. this.data.damping = value;
  73606. }
  73607. });
  73608. /**
  73609. * @name Phaser.Physics.P2.Body#fixedRotation
  73610. * @property {boolean} fixedRotation -
  73611. */
  73612. Object.defineProperty(Phaser.Physics.P2.Body.prototype, "fixedRotation", {
  73613. get: function () {
  73614. return this.data.fixedRotation;
  73615. },
  73616. set: function (value) {
  73617. if (value !== this.data.fixedRotation)
  73618. {
  73619. this.data.fixedRotation = value;
  73620. }
  73621. }
  73622. });
  73623. /**
  73624. * @name Phaser.Physics.P2.Body#inertia
  73625. * @property {number} inertia - The inertia of the body around the Z axis..
  73626. */
  73627. Object.defineProperty(Phaser.Physics.P2.Body.prototype, "inertia", {
  73628. get: function () {
  73629. return this.data.inertia;
  73630. },
  73631. set: function (value) {
  73632. this.data.inertia = value;
  73633. }
  73634. });
  73635. /**
  73636. * @name Phaser.Physics.P2.Body#mass
  73637. * @property {number} mass - The mass of the body.
  73638. */
  73639. Object.defineProperty(Phaser.Physics.P2.Body.prototype, "mass", {
  73640. get: function () {
  73641. return this.data.mass;
  73642. },
  73643. set: function (value) {
  73644. if (value !== this.data.mass)
  73645. {
  73646. this.data.mass = value;
  73647. this.data.updateMassProperties();
  73648. }
  73649. }
  73650. });
  73651. /**
  73652. * @name Phaser.Physics.P2.Body#motionState
  73653. * @property {number} motionState - The type of motion this body has. Should be one of: Body.STATIC (the body does not move), Body.DYNAMIC (body can move and respond to collisions) and Body.KINEMATIC (only moves according to its .velocity).
  73654. */
  73655. Object.defineProperty(Phaser.Physics.P2.Body.prototype, "motionState", {
  73656. get: function () {
  73657. return this.data.type;
  73658. },
  73659. set: function (value) {
  73660. if (value !== this.data.type)
  73661. {
  73662. this.data.type = value;
  73663. }
  73664. }
  73665. });
  73666. /**
  73667. * The angle of the Body in radians.
  73668. * If you wish to work in degrees instead of radians use the Body.angle property instead. Working in radians is faster as it doesn't have to convert values.
  73669. *
  73670. * @name Phaser.Physics.P2.Body#rotation
  73671. * @property {number} rotation - The angle of this Body in radians.
  73672. */
  73673. Object.defineProperty(Phaser.Physics.P2.Body.prototype, "rotation", {
  73674. get: function() {
  73675. return this.data.angle;
  73676. },
  73677. set: function(value) {
  73678. this.data.angle = value;
  73679. }
  73680. });
  73681. /**
  73682. * @name Phaser.Physics.P2.Body#sleepSpeedLimit
  73683. * @property {number} sleepSpeedLimit - .
  73684. */
  73685. Object.defineProperty(Phaser.Physics.P2.Body.prototype, "sleepSpeedLimit", {
  73686. get: function () {
  73687. return this.data.sleepSpeedLimit;
  73688. },
  73689. set: function (value) {
  73690. this.data.sleepSpeedLimit = value;
  73691. }
  73692. });
  73693. /**
  73694. * @name Phaser.Physics.P2.Body#x
  73695. * @property {number} x - The x coordinate of this Body.
  73696. */
  73697. Object.defineProperty(Phaser.Physics.P2.Body.prototype, "x", {
  73698. get: function () {
  73699. return this.world.mpxi(this.data.position[0]);
  73700. },
  73701. set: function (value) {
  73702. this.data.position[0] = this.world.pxmi(value);
  73703. }
  73704. });
  73705. /**
  73706. * @name Phaser.Physics.P2.Body#y
  73707. * @property {number} y - The y coordinate of this Body.
  73708. */
  73709. Object.defineProperty(Phaser.Physics.P2.Body.prototype, "y", {
  73710. get: function () {
  73711. return this.world.mpxi(this.data.position[1]);
  73712. },
  73713. set: function (value) {
  73714. this.data.position[1] = this.world.pxmi(value);
  73715. }
  73716. });
  73717. /**
  73718. * @name Phaser.Physics.P2.Body#id
  73719. * @property {number} id - The Body ID. Each Body that has been added to the World has a unique ID.
  73720. * @readonly
  73721. */
  73722. Object.defineProperty(Phaser.Physics.P2.Body.prototype, "id", {
  73723. get: function () {
  73724. return this.data.id;
  73725. }
  73726. });
  73727. /**
  73728. * @name Phaser.Physics.P2.Body#debug
  73729. * @property {boolean} debug - Enable or disable debug drawing of this body
  73730. */
  73731. Object.defineProperty(Phaser.Physics.P2.Body.prototype, "debug", {
  73732. get: function () {
  73733. return (this.debugBody !== null);
  73734. },
  73735. set: function (value) {
  73736. if (value && !this.debugBody)
  73737. {
  73738. // This will be added to the global space
  73739. this.debugBody = new Phaser.Physics.P2.BodyDebug(this.game, this.data);
  73740. }
  73741. else if (!value && this.debugBody)
  73742. {
  73743. this.debugBody.destroy();
  73744. this.debugBody = null;
  73745. }
  73746. }
  73747. });
  73748. /**
  73749. * A Body can be set to collide against the World bounds automatically if this is set to true. Otherwise it will leave the World.
  73750. * Note that this only applies if your World has bounds! The response to the collision should be managed via CollisionMaterials.
  73751. * Also note that when you set this it will only effect Body shapes that already exist. If you then add further shapes to your Body
  73752. * after setting this it will *not* proactively set them to collide with the bounds.
  73753. *
  73754. * @name Phaser.Physics.P2.Body#collideWorldBounds
  73755. * @property {boolean} collideWorldBounds - Should the Body collide with the World bounds?
  73756. */
  73757. Object.defineProperty(Phaser.Physics.P2.Body.prototype, "collideWorldBounds", {
  73758. get: function () {
  73759. return this._collideWorldBounds;
  73760. },
  73761. set: function (value) {
  73762. if (value && !this._collideWorldBounds)
  73763. {
  73764. this._collideWorldBounds = true;
  73765. this.updateCollisionMask();
  73766. }
  73767. else if (!value && this._collideWorldBounds)
  73768. {
  73769. this._collideWorldBounds = false;
  73770. this.updateCollisionMask();
  73771. }
  73772. }
  73773. });
  73774. /**
  73775. * @author George https://github.com/georgiee
  73776. * @author Richard Davey <rich@photonstorm.com>
  73777. * @copyright 2016 Photon Storm Ltd.
  73778. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  73779. */
  73780. /**
  73781. * Draws a P2 Body to a Graphics instance for visual debugging.
  73782. * Needless to say, for every body you enable debug drawing on, you are adding processor and graphical overhead.
  73783. * So use sparingly and rarely (if ever) in production code.
  73784. *
  73785. * Also be aware that the Debug body is only updated when the Sprite it is connected to changes position. If you
  73786. * manipulate the sprite in any other way (such as moving it to another Group or bringToTop, etc) then you will
  73787. * need to manually adjust its BodyDebug as well.
  73788. *
  73789. * @class Phaser.Physics.P2.BodyDebug
  73790. * @constructor
  73791. * @extends Phaser.Group
  73792. * @param {Phaser.Game} game - Game reference to the currently running game.
  73793. * @param {Phaser.Physics.P2.Body} body - The P2 Body to display debug data for.
  73794. * @param {object} settings - Settings object.
  73795. */
  73796. Phaser.Physics.P2.BodyDebug = function(game, body, settings) {
  73797. Phaser.Group.call(this, game);
  73798. /**
  73799. * @property {object} defaultSettings - Default debug settings.
  73800. * @private
  73801. */
  73802. var defaultSettings = {
  73803. pixelsPerLengthUnit: game.physics.p2.mpx(1),
  73804. debugPolygons: false,
  73805. lineWidth: 1,
  73806. alpha: 0.5
  73807. };
  73808. this.settings = Phaser.Utils.extend(defaultSettings, settings);
  73809. /**
  73810. * @property {number} ppu - Pixels per Length Unit.
  73811. */
  73812. this.ppu = this.settings.pixelsPerLengthUnit;
  73813. this.ppu = -1 * this.ppu;
  73814. /**
  73815. * @property {Phaser.Physics.P2.Body} body - The P2 Body to display debug data for.
  73816. */
  73817. this.body = body;
  73818. /**
  73819. * @property {Phaser.Graphics} canvas - The canvas to render the debug info to.
  73820. */
  73821. this.canvas = new Phaser.Graphics(game);
  73822. this.canvas.alpha = this.settings.alpha;
  73823. this.add(this.canvas);
  73824. this.draw();
  73825. this.updateSpriteTransform();
  73826. };
  73827. Phaser.Physics.P2.BodyDebug.prototype = Object.create(Phaser.Group.prototype);
  73828. Phaser.Physics.P2.BodyDebug.prototype.constructor = Phaser.Physics.P2.BodyDebug;
  73829. Phaser.Utils.extend(Phaser.Physics.P2.BodyDebug.prototype, {
  73830. /**
  73831. * Core update.
  73832. *
  73833. * @method Phaser.Physics.P2.BodyDebug#updateSpriteTransform
  73834. */
  73835. updateSpriteTransform: function() {
  73836. this.position.x = this.body.position[0] * this.ppu;
  73837. this.position.y = this.body.position[1] * this.ppu;
  73838. this.rotation = this.body.angle;
  73839. },
  73840. /**
  73841. * Draws the P2 shapes to the Graphics object.
  73842. *
  73843. * @method Phaser.Physics.P2.BodyDebug#draw
  73844. */
  73845. draw: function() {
  73846. var angle, child, color, i, j, lineColor, lw, obj, offset, sprite, v, verts, vrot, _j, _ref1;
  73847. obj = this.body;
  73848. sprite = this.canvas;
  73849. sprite.clear();
  73850. color = parseInt(this.randomPastelHex(), 16);
  73851. lineColor = 0xff0000;
  73852. lw = this.lineWidth;
  73853. if (obj instanceof p2.Body && obj.shapes.length)
  73854. {
  73855. var l = obj.shapes.length;
  73856. i = 0;
  73857. while (i !== l)
  73858. {
  73859. child = obj.shapes[i];
  73860. offset = child.position || 0;
  73861. angle = child.angle || 0;
  73862. if (child instanceof p2.Circle)
  73863. {
  73864. this.drawCircle(sprite, offset[0] * this.ppu, offset[1] * this.ppu, angle, child.radius * this.ppu, color, lw);
  73865. }
  73866. else if (child instanceof p2.Capsule)
  73867. {
  73868. this.drawCapsule(sprite, offset[0] * this.ppu, offset[1] * this.ppu, angle, child.length * this.ppu, child.radius * this.ppu, lineColor, color, lw);
  73869. }
  73870. else if (child instanceof p2.Plane)
  73871. {
  73872. this.drawPlane(sprite, offset[0] * this.ppu, -offset[1] * this.ppu, color, lineColor, lw * 5, lw * 10, lw * 10, this.ppu * 100, angle);
  73873. }
  73874. else if (child instanceof p2.Line)
  73875. {
  73876. this.drawLine(sprite, child.length * this.ppu, lineColor, lw);
  73877. }
  73878. else if (child instanceof p2.Box)
  73879. {
  73880. this.drawRectangle(sprite, offset[0] * this.ppu, offset[1] * this.ppu, angle, child.width * this.ppu, child.height * this.ppu, lineColor, color, lw);
  73881. }
  73882. else if (child instanceof p2.Convex)
  73883. {
  73884. verts = [];
  73885. vrot = p2.vec2.create();
  73886. for (j = _j = 0, _ref1 = child.vertices.length; 0 <= _ref1 ? _j < _ref1 : _j > _ref1; j = 0 <= _ref1 ? ++_j : --_j)
  73887. {
  73888. v = child.vertices[j];
  73889. p2.vec2.rotate(vrot, v, angle);
  73890. verts.push([(vrot[0] + offset[0]) * this.ppu, -(vrot[1] + offset[1]) * this.ppu]);
  73891. }
  73892. this.drawConvex(sprite, verts, child.triangles, lineColor, color, lw, this.settings.debugPolygons, [offset[0] * this.ppu, -offset[1] * this.ppu]);
  73893. }
  73894. i++;
  73895. }
  73896. }
  73897. },
  73898. /**
  73899. * Draws a p2.Box to the Graphics object.
  73900. *
  73901. * @method Phaser.Physics.P2.BodyDebug#drawRectangle
  73902. * @private
  73903. */
  73904. drawRectangle: function(g, x, y, angle, w, h, color, fillColor, lineWidth) {
  73905. if (lineWidth === undefined) { lineWidth = 1; }
  73906. if (color === undefined) { color = 0x000000; }
  73907. g.lineStyle(lineWidth, color, 1);
  73908. g.beginFill(fillColor);
  73909. g.drawRect(x - w / 2, y - h / 2, w, h);
  73910. },
  73911. /**
  73912. * Draws a p2.Circle to the Graphics object.
  73913. *
  73914. * @method Phaser.Physics.P2.BodyDebug#drawCircle
  73915. * @private
  73916. */
  73917. drawCircle: function(g, x, y, angle, radius, color, lineWidth) {
  73918. if (lineWidth === undefined) { lineWidth = 1; }
  73919. if (color === undefined) { color = 0xffffff; }
  73920. g.lineStyle(lineWidth, 0x000000, 1);
  73921. g.beginFill(color, 1.0);
  73922. g.drawCircle(x, y, -radius*2);
  73923. g.endFill();
  73924. g.moveTo(x, y);
  73925. g.lineTo(x + radius * Math.cos(-angle), y + radius * Math.sin(-angle));
  73926. },
  73927. /**
  73928. * Draws a p2.Line to the Graphics object.
  73929. *
  73930. * @method Phaser.Physics.P2.BodyDebug#drawLine
  73931. * @private
  73932. */
  73933. drawLine: function(g, len, color, lineWidth) {
  73934. if (lineWidth === undefined) { lineWidth = 1; }
  73935. if (color === undefined) { color = 0x000000; }
  73936. g.lineStyle(lineWidth * 5, color, 1);
  73937. g.moveTo(-len / 2, 0);
  73938. g.lineTo(len / 2, 0);
  73939. },
  73940. /**
  73941. * Draws a p2.Convex to the Graphics object.
  73942. *
  73943. * @method Phaser.Physics.P2.BodyDebug#drawConvex
  73944. * @private
  73945. */
  73946. drawConvex: function(g, verts, triangles, color, fillColor, lineWidth, debug, offset) {
  73947. var colors, i, v, v0, v1, x, x0, x1, y, y0, y1;
  73948. if (lineWidth === undefined) { lineWidth = 1; }
  73949. if (color === undefined) { color = 0x000000; }
  73950. if (!debug)
  73951. {
  73952. g.lineStyle(lineWidth, color, 1);
  73953. g.beginFill(fillColor);
  73954. i = 0;
  73955. while (i !== verts.length)
  73956. {
  73957. v = verts[i];
  73958. x = v[0];
  73959. y = v[1];
  73960. if (i === 0)
  73961. {
  73962. g.moveTo(x, -y);
  73963. }
  73964. else
  73965. {
  73966. g.lineTo(x, -y);
  73967. }
  73968. i++;
  73969. }
  73970. g.endFill();
  73971. if (verts.length > 2)
  73972. {
  73973. g.moveTo(verts[verts.length - 1][0], -verts[verts.length - 1][1]);
  73974. return g.lineTo(verts[0][0], -verts[0][1]);
  73975. }
  73976. }
  73977. else
  73978. {
  73979. colors = [0xff0000, 0x00ff00, 0x0000ff];
  73980. i = 0;
  73981. while (i !== verts.length + 1)
  73982. {
  73983. v0 = verts[i % verts.length];
  73984. v1 = verts[(i + 1) % verts.length];
  73985. x0 = v0[0];
  73986. y0 = v0[1];
  73987. x1 = v1[0];
  73988. y1 = v1[1];
  73989. g.lineStyle(lineWidth, colors[i % colors.length], 1);
  73990. g.moveTo(x0, -y0);
  73991. g.lineTo(x1, -y1);
  73992. g.drawCircle(x0, -y0, lineWidth * 2);
  73993. i++;
  73994. }
  73995. g.lineStyle(lineWidth, 0x000000, 1);
  73996. return g.drawCircle(offset[0], offset[1], lineWidth * 2);
  73997. }
  73998. },
  73999. /**
  74000. * Draws a p2.Path to the Graphics object.
  74001. *
  74002. * @method Phaser.Physics.P2.BodyDebug#drawPath
  74003. * @private
  74004. */
  74005. drawPath: function(g, path, color, fillColor, lineWidth) {
  74006. var area, i, lastx, lasty, p1x, p1y, p2x, p2y, p3x, p3y, v, x, y;
  74007. if (lineWidth === undefined) { lineWidth = 1; }
  74008. if (color === undefined) { color = 0x000000; }
  74009. g.lineStyle(lineWidth, color, 1);
  74010. if (typeof fillColor === "number")
  74011. {
  74012. g.beginFill(fillColor);
  74013. }
  74014. lastx = null;
  74015. lasty = null;
  74016. i = 0;
  74017. while (i < path.length)
  74018. {
  74019. v = path[i];
  74020. x = v[0];
  74021. y = v[1];
  74022. if (x !== lastx || y !== lasty)
  74023. {
  74024. if (i === 0)
  74025. {
  74026. g.moveTo(x, y);
  74027. }
  74028. else
  74029. {
  74030. p1x = lastx;
  74031. p1y = lasty;
  74032. p2x = x;
  74033. p2y = y;
  74034. p3x = path[(i + 1) % path.length][0];
  74035. p3y = path[(i + 1) % path.length][1];
  74036. area = ((p2x - p1x) * (p3y - p1y)) - ((p3x - p1x) * (p2y - p1y));
  74037. if (area !== 0)
  74038. {
  74039. g.lineTo(x, y);
  74040. }
  74041. }
  74042. lastx = x;
  74043. lasty = y;
  74044. }
  74045. i++;
  74046. }
  74047. if (typeof fillColor === "number")
  74048. {
  74049. g.endFill();
  74050. }
  74051. if (path.length > 2 && typeof fillColor === "number")
  74052. {
  74053. g.moveTo(path[path.length - 1][0], path[path.length - 1][1]);
  74054. g.lineTo(path[0][0], path[0][1]);
  74055. }
  74056. },
  74057. /**
  74058. * Draws a p2.Plane to the Graphics object.
  74059. *
  74060. * @method Phaser.Physics.P2.BodyDebug#drawPlane
  74061. * @private
  74062. */
  74063. drawPlane: function(g, x0, x1, color, lineColor, lineWidth, diagMargin, diagSize, maxLength, angle) {
  74064. var max, xd, yd;
  74065. if (lineWidth === undefined) { lineWidth = 1; }
  74066. if (color === undefined) { color = 0xffffff; }
  74067. g.lineStyle(lineWidth, lineColor, 11);
  74068. g.beginFill(color);
  74069. max = maxLength;
  74070. g.moveTo(x0, -x1);
  74071. xd = x0 + Math.cos(angle) * this.game.width;
  74072. yd = x1 + Math.sin(angle) * this.game.height;
  74073. g.lineTo(xd, -yd);
  74074. g.moveTo(x0, -x1);
  74075. xd = x0 + Math.cos(angle) * -this.game.width;
  74076. yd = x1 + Math.sin(angle) * -this.game.height;
  74077. g.lineTo(xd, -yd);
  74078. },
  74079. /**
  74080. * Draws a p2.Capsule to the Graphics object.
  74081. *
  74082. * @method Phaser.Physics.P2.BodyDebug#drawCapsule
  74083. * @private
  74084. */
  74085. drawCapsule: function(g, x, y, angle, len, radius, color, fillColor, lineWidth) {
  74086. if (lineWidth === undefined) { lineWidth = 1; }
  74087. if (color === undefined) { color = 0x000000; }
  74088. g.lineStyle(lineWidth, color, 1);
  74089. // Draw circles at ends
  74090. var c = Math.cos(angle);
  74091. var s = Math.sin(angle);
  74092. g.beginFill(fillColor, 1);
  74093. g.drawCircle(-len/2*c + x, -len/2*s + y, -radius * 2);
  74094. g.drawCircle( len/2*c + x, len/2*s + y, -radius * 2);
  74095. g.endFill();
  74096. // Draw rectangle
  74097. g.lineStyle(lineWidth, color, 0);
  74098. g.beginFill(fillColor, 1);
  74099. g.moveTo(-len/2*c + radius*s + x, -len/2*s + radius*c + y);
  74100. g.lineTo( len/2*c + radius*s + x, len/2*s + radius*c + y);
  74101. g.lineTo( len/2*c - radius*s + x, len/2*s - radius*c + y);
  74102. g.lineTo(-len/2*c - radius*s + x, -len/2*s - radius*c + y);
  74103. g.endFill();
  74104. // Draw lines in between
  74105. g.lineStyle(lineWidth, color, 1);
  74106. g.moveTo(-len/2*c + radius*s + x, -len/2*s + radius*c + y);
  74107. g.lineTo( len/2*c + radius*s + x, len/2*s + radius*c + y);
  74108. g.moveTo(-len/2*c - radius*s + x, -len/2*s - radius*c + y);
  74109. g.lineTo( len/2*c - radius*s + x, len/2*s - radius*c + y);
  74110. },
  74111. /**
  74112. * Picks a random pastel color.
  74113. *
  74114. * @method Phaser.Physics.P2.BodyDebug#randomPastelHex
  74115. * @private
  74116. */
  74117. randomPastelHex: function() {
  74118. var blue, green, mix, red;
  74119. mix = [255, 255, 255];
  74120. red = Math.floor(Math.random() * 256);
  74121. green = Math.floor(Math.random() * 256);
  74122. blue = Math.floor(Math.random() * 256);
  74123. red = Math.floor((red + 3 * mix[0]) / 4);
  74124. green = Math.floor((green + 3 * mix[1]) / 4);
  74125. blue = Math.floor((blue + 3 * mix[2]) / 4);
  74126. return this.rgbToHex(red, green, blue);
  74127. },
  74128. /**
  74129. * Converts from RGB to Hex.
  74130. *
  74131. * @method Phaser.Physics.P2.BodyDebug#rgbToHex
  74132. * @private
  74133. */
  74134. rgbToHex: function(r, g, b) {
  74135. return this.componentToHex(r) + this.componentToHex(g) + this.componentToHex(b);
  74136. },
  74137. /**
  74138. * Component to hex conversion.
  74139. *
  74140. * @method Phaser.Physics.P2.BodyDebug#componentToHex
  74141. * @private
  74142. */
  74143. componentToHex: function(c) {
  74144. var hex;
  74145. hex = c.toString(16);
  74146. if (hex.length === 2)
  74147. {
  74148. return hex;
  74149. }
  74150. else
  74151. {
  74152. return hex + '0';
  74153. }
  74154. }
  74155. });
  74156. /**
  74157. * @author Richard Davey <rich@photonstorm.com>
  74158. * @copyright 2016 Photon Storm Ltd.
  74159. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  74160. */
  74161. /**
  74162. * Creates a linear spring, connecting two bodies. A spring can have a resting length, a stiffness and damping.
  74163. *
  74164. * @class Phaser.Physics.P2.Spring
  74165. * @constructor
  74166. * @param {Phaser.Physics.P2} world - A reference to the P2 World.
  74167. * @param {p2.Body} bodyA - First connected body.
  74168. * @param {p2.Body} bodyB - Second connected body.
  74169. * @param {number} [restLength=1] - Rest length of the spring. A number > 0.
  74170. * @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0.
  74171. * @param {number} [damping=1] - Damping of the spring. A number >= 0.
  74172. * @param {Array} [worldA] - Where to hook the spring to body A in world coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32].
  74173. * @param {Array} [worldB] - Where to hook the spring to body B in world coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32].
  74174. * @param {Array} [localA] - Where to hook the spring to body A in local body coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32].
  74175. * @param {Array} [localB] - Where to hook the spring to body B in local body coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32].
  74176. */
  74177. Phaser.Physics.P2.Spring = function (world, bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB) {
  74178. /**
  74179. * @property {Phaser.Game} game - Local reference to game.
  74180. */
  74181. this.game = world.game;
  74182. /**
  74183. * @property {Phaser.Physics.P2} world - Local reference to P2 World.
  74184. */
  74185. this.world = world;
  74186. if (restLength === undefined) { restLength = 1; }
  74187. if (stiffness === undefined) { stiffness = 100; }
  74188. if (damping === undefined) { damping = 1; }
  74189. restLength = world.pxm(restLength);
  74190. var options = {
  74191. restLength: restLength,
  74192. stiffness: stiffness,
  74193. damping: damping
  74194. };
  74195. if (typeof worldA !== 'undefined' && worldA !== null)
  74196. {
  74197. options.worldAnchorA = [ world.pxm(worldA[0]), world.pxm(worldA[1]) ];
  74198. }
  74199. if (typeof worldB !== 'undefined' && worldB !== null)
  74200. {
  74201. options.worldAnchorB = [ world.pxm(worldB[0]), world.pxm(worldB[1]) ];
  74202. }
  74203. if (typeof localA !== 'undefined' && localA !== null)
  74204. {
  74205. options.localAnchorA = [ world.pxm(localA[0]), world.pxm(localA[1]) ];
  74206. }
  74207. if (typeof localB !== 'undefined' && localB !== null)
  74208. {
  74209. options.localAnchorB = [ world.pxm(localB[0]), world.pxm(localB[1]) ];
  74210. }
  74211. /**
  74212. * @property {p2.LinearSpring} data - The actual p2 spring object.
  74213. */
  74214. this.data = new p2.LinearSpring(bodyA, bodyB, options);
  74215. this.data.parent = this;
  74216. };
  74217. Phaser.Physics.P2.Spring.prototype.constructor = Phaser.Physics.P2.Spring;
  74218. /**
  74219. * @author Richard Davey <rich@photonstorm.com>
  74220. * @copyright 2016 Photon Storm Ltd.
  74221. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  74222. */
  74223. /**
  74224. * Creates a rotational spring, connecting two bodies. A spring can have a resting length, a stiffness and damping.
  74225. *
  74226. * @class Phaser.Physics.P2.RotationalSpring
  74227. * @constructor
  74228. * @param {Phaser.Physics.P2} world - A reference to the P2 World.
  74229. * @param {p2.Body} bodyA - First connected body.
  74230. * @param {p2.Body} bodyB - Second connected body.
  74231. * @param {number} [restAngle] - The relative angle of bodies at which the spring is at rest. If not given, it's set to the current relative angle between the bodies.
  74232. * @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0.
  74233. * @param {number} [damping=1] - Damping of the spring. A number >= 0.
  74234. */
  74235. Phaser.Physics.P2.RotationalSpring = function (world, bodyA, bodyB, restAngle, stiffness, damping) {
  74236. /**
  74237. * @property {Phaser.Game} game - Local reference to game.
  74238. */
  74239. this.game = world.game;
  74240. /**
  74241. * @property {Phaser.Physics.P2} world - Local reference to P2 World.
  74242. */
  74243. this.world = world;
  74244. if (restAngle === undefined) { restAngle = null; }
  74245. if (stiffness === undefined) { stiffness = 100; }
  74246. if (damping === undefined) { damping = 1; }
  74247. if (restAngle)
  74248. {
  74249. restAngle = world.pxm(restAngle);
  74250. }
  74251. var options = {
  74252. restAngle: restAngle,
  74253. stiffness: stiffness,
  74254. damping: damping
  74255. };
  74256. /**
  74257. * @property {p2.RotationalSpring} data - The actual p2 spring object.
  74258. */
  74259. this.data = new p2.RotationalSpring(bodyA, bodyB, options);
  74260. this.data.parent = this;
  74261. };
  74262. Phaser.Physics.P2.Spring.prototype.constructor = Phaser.Physics.P2.Spring;
  74263. /**
  74264. * @author Richard Davey <rich@photonstorm.com>
  74265. * @copyright 2016 Photon Storm Ltd.
  74266. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  74267. */
  74268. /**
  74269. * A P2 Material.
  74270. *
  74271. * \o/ ~ "Because I'm a Material girl"
  74272. *
  74273. * @class Phaser.Physics.P2.Material
  74274. * @constructor
  74275. * @param {string} name - The user defined name given to this Material.
  74276. */
  74277. Phaser.Physics.P2.Material = function (name) {
  74278. /**
  74279. * @property {string} name - The user defined name given to this Material.
  74280. * @default
  74281. */
  74282. this.name = name;
  74283. p2.Material.call(this);
  74284. };
  74285. Phaser.Physics.P2.Material.prototype = Object.create(p2.Material.prototype);
  74286. Phaser.Physics.P2.Material.prototype.constructor = Phaser.Physics.P2.Material;
  74287. /**
  74288. * @author Richard Davey <rich@photonstorm.com>
  74289. * @copyright 2016 Photon Storm Ltd.
  74290. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  74291. */
  74292. /**
  74293. * Defines a physics material
  74294. *
  74295. * @class Phaser.Physics.P2.ContactMaterial
  74296. * @constructor
  74297. * @param {Phaser.Physics.P2.Material} materialA - First material participating in the contact material.
  74298. * @param {Phaser.Physics.P2.Material} materialB - Second material participating in the contact material.
  74299. * @param {object} [options] - Additional configuration options.
  74300. */
  74301. Phaser.Physics.P2.ContactMaterial = function (materialA, materialB, options) {
  74302. /**
  74303. * @property {number} id - The contact material identifier.
  74304. */
  74305. /**
  74306. * @property {Phaser.Physics.P2.Material} materialA - First material participating in the contact material.
  74307. */
  74308. /**
  74309. * @property {Phaser.Physics.P2.Material} materialB - Second material participating in the contact material.
  74310. */
  74311. /**
  74312. * @property {number} [friction=0.3] - Friction to use in the contact of these two materials.
  74313. */
  74314. /**
  74315. * @property {number} [restitution=0.0] - Restitution to use in the contact of these two materials.
  74316. */
  74317. /**
  74318. * @property {number} [stiffness=1e7] - Stiffness of the resulting ContactEquation that this ContactMaterial generates.
  74319. */
  74320. /**
  74321. * @property {number} [relaxation=3] - Relaxation of the resulting ContactEquation that this ContactMaterial generates.
  74322. */
  74323. /**
  74324. * @property {number} [frictionStiffness=1e7] - Stiffness of the resulting FrictionEquation that this ContactMaterial generates.
  74325. */
  74326. /**
  74327. * @property {number} [frictionRelaxation=3] - Relaxation of the resulting FrictionEquation that this ContactMaterial generates.
  74328. */
  74329. /**
  74330. * @property {number} [surfaceVelocity=0] - Will add surface velocity to this material. If bodyA rests on top if bodyB, and the surface velocity is positive, bodyA will slide to the right.
  74331. */
  74332. p2.ContactMaterial.call(this, materialA, materialB, options);
  74333. };
  74334. Phaser.Physics.P2.ContactMaterial.prototype = Object.create(p2.ContactMaterial.prototype);
  74335. Phaser.Physics.P2.ContactMaterial.prototype.constructor = Phaser.Physics.P2.ContactMaterial;
  74336. /**
  74337. * @author Richard Davey <rich@photonstorm.com>
  74338. * @copyright 2016 Photon Storm Ltd.
  74339. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  74340. */
  74341. /**
  74342. * Collision Group
  74343. *
  74344. * @class Phaser.Physics.P2.CollisionGroup
  74345. * @constructor
  74346. * @param {number} bitmask - The CollisionGroup bitmask.
  74347. */
  74348. Phaser.Physics.P2.CollisionGroup = function (bitmask) {
  74349. /**
  74350. * @property {number} mask - The CollisionGroup bitmask.
  74351. */
  74352. this.mask = bitmask;
  74353. };
  74354. /**
  74355. * @author Richard Davey <rich@photonstorm.com>
  74356. * @copyright 2016 Photon Storm Ltd.
  74357. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  74358. */
  74359. /**
  74360. * A constraint that tries to keep the distance between two bodies constant.
  74361. *
  74362. * @class Phaser.Physics.P2.DistanceConstraint
  74363. * @constructor
  74364. * @param {Phaser.Physics.P2} world - A reference to the P2 World.
  74365. * @param {p2.Body} bodyA - First connected body.
  74366. * @param {p2.Body} bodyB - Second connected body.
  74367. * @param {number} distance - The distance to keep between the bodies.
  74368. * @param {Array} [localAnchorA] - The anchor point for bodyA, defined locally in bodyA frame. Defaults to [0,0].
  74369. * @param {Array} [localAnchorB] - The anchor point for bodyB, defined locally in bodyB frame. Defaults to [0,0].
  74370. * @param {object} [maxForce=Number.MAX_VALUE] - Maximum force to apply.
  74371. */
  74372. Phaser.Physics.P2.DistanceConstraint = function (world, bodyA, bodyB, distance, localAnchorA, localAnchorB, maxForce) {
  74373. if (distance === undefined) { distance = 100; }
  74374. if (localAnchorA === undefined) { localAnchorA = [0, 0]; }
  74375. if (localAnchorB === undefined) { localAnchorB = [0, 0]; }
  74376. if (maxForce === undefined) { maxForce = Number.MAX_VALUE; }
  74377. /**
  74378. * @property {Phaser.Game} game - Local reference to game.
  74379. */
  74380. this.game = world.game;
  74381. /**
  74382. * @property {Phaser.Physics.P2} world - Local reference to P2 World.
  74383. */
  74384. this.world = world;
  74385. distance = world.pxm(distance);
  74386. localAnchorA = [ world.pxmi(localAnchorA[0]), world.pxmi(localAnchorA[1]) ];
  74387. localAnchorB = [ world.pxmi(localAnchorB[0]), world.pxmi(localAnchorB[1]) ];
  74388. var options = { distance: distance, localAnchorA: localAnchorA, localAnchorB: localAnchorB, maxForce: maxForce };
  74389. p2.DistanceConstraint.call(this, bodyA, bodyB, options);
  74390. };
  74391. Phaser.Physics.P2.DistanceConstraint.prototype = Object.create(p2.DistanceConstraint.prototype);
  74392. Phaser.Physics.P2.DistanceConstraint.prototype.constructor = Phaser.Physics.P2.DistanceConstraint;
  74393. /**
  74394. * @author Richard Davey <rich@photonstorm.com>
  74395. * @copyright 2016 Photon Storm Ltd.
  74396. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  74397. */
  74398. /**
  74399. * Connects two bodies at given offset points, letting them rotate relative to each other around this point.
  74400. *
  74401. * @class Phaser.Physics.P2.GearConstraint
  74402. * @constructor
  74403. * @param {Phaser.Physics.P2} world - A reference to the P2 World.
  74404. * @param {p2.Body} bodyA - First connected body.
  74405. * @param {p2.Body} bodyB - Second connected body.
  74406. * @param {number} [angle=0] - The relative angle
  74407. * @param {number} [ratio=1] - The gear ratio.
  74408. */
  74409. Phaser.Physics.P2.GearConstraint = function (world, bodyA, bodyB, angle, ratio) {
  74410. if (angle === undefined) { angle = 0; }
  74411. if (ratio === undefined) { ratio = 1; }
  74412. /**
  74413. * @property {Phaser.Game} game - Local reference to game.
  74414. */
  74415. this.game = world.game;
  74416. /**
  74417. * @property {Phaser.Physics.P2} world - Local reference to P2 World.
  74418. */
  74419. this.world = world;
  74420. var options = { angle: angle, ratio: ratio };
  74421. p2.GearConstraint.call(this, bodyA, bodyB, options);
  74422. };
  74423. Phaser.Physics.P2.GearConstraint.prototype = Object.create(p2.GearConstraint.prototype);
  74424. Phaser.Physics.P2.GearConstraint.prototype.constructor = Phaser.Physics.P2.GearConstraint;
  74425. /**
  74426. * @author Richard Davey <rich@photonstorm.com>
  74427. * @copyright 2016 Photon Storm Ltd.
  74428. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  74429. */
  74430. /**
  74431. * Locks the relative position between two bodies.
  74432. *
  74433. * @class Phaser.Physics.P2.LockConstraint
  74434. * @constructor
  74435. * @param {Phaser.Physics.P2} world - A reference to the P2 World.
  74436. * @param {p2.Body} bodyA - First connected body.
  74437. * @param {p2.Body} bodyB - Second connected body.
  74438. * @param {Array} [offset] - The offset of bodyB in bodyA's frame. The value is an array with 2 elements matching x and y, i.e: [32, 32].
  74439. * @param {number} [angle=0] - The angle of bodyB in bodyA's frame.
  74440. * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies.
  74441. */
  74442. Phaser.Physics.P2.LockConstraint = function (world, bodyA, bodyB, offset, angle, maxForce) {
  74443. if (offset === undefined) { offset = [0, 0]; }
  74444. if (angle === undefined) { angle = 0; }
  74445. if (maxForce === undefined) { maxForce = Number.MAX_VALUE; }
  74446. /**
  74447. * @property {Phaser.Game} game - Local reference to game.
  74448. */
  74449. this.game = world.game;
  74450. /**
  74451. * @property {Phaser.Physics.P2} world - Local reference to P2 World.
  74452. */
  74453. this.world = world;
  74454. offset = [ world.pxm(offset[0]), world.pxm(offset[1]) ];
  74455. var options = { localOffsetB: offset, localAngleB: angle, maxForce: maxForce };
  74456. p2.LockConstraint.call(this, bodyA, bodyB, options);
  74457. };
  74458. Phaser.Physics.P2.LockConstraint.prototype = Object.create(p2.LockConstraint.prototype);
  74459. Phaser.Physics.P2.LockConstraint.prototype.constructor = Phaser.Physics.P2.LockConstraint;
  74460. /**
  74461. * @author Richard Davey <rich@photonstorm.com>
  74462. * @copyright 2016 Photon Storm Ltd.
  74463. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  74464. */
  74465. /**
  74466. * Connects two bodies at given offset points, letting them rotate relative to each other around this point.
  74467. *
  74468. * @class Phaser.Physics.P2.PrismaticConstraint
  74469. * @constructor
  74470. * @param {Phaser.Physics.P2} world - A reference to the P2 World.
  74471. * @param {p2.Body} bodyA - First connected body.
  74472. * @param {p2.Body} bodyB - Second connected body.
  74473. * @param {boolean} [lockRotation=true] - If set to false, bodyB will be free to rotate around its anchor point.
  74474. * @param {Array} [anchorA] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32].
  74475. * @param {Array} [anchorB] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32].
  74476. * @param {Array} [axis] - An axis, defined in body A frame, that body B's anchor point may slide along. The value is an array with 2 elements matching x and y, i.e: [32, 32].
  74477. * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies.
  74478. */
  74479. Phaser.Physics.P2.PrismaticConstraint = function (world, bodyA, bodyB, lockRotation, anchorA, anchorB, axis, maxForce) {
  74480. if (lockRotation === undefined) { lockRotation = true; }
  74481. if (anchorA === undefined) { anchorA = [0, 0]; }
  74482. if (anchorB === undefined) { anchorB = [0, 0]; }
  74483. if (axis === undefined) { axis = [0, 0]; }
  74484. if (maxForce === undefined) { maxForce = Number.MAX_VALUE; }
  74485. /**
  74486. * @property {Phaser.Game} game - Local reference to game.
  74487. */
  74488. this.game = world.game;
  74489. /**
  74490. * @property {Phaser.Physics.P2} world - Local reference to P2 World.
  74491. */
  74492. this.world = world;
  74493. anchorA = [ world.pxmi(anchorA[0]), world.pxmi(anchorA[1]) ];
  74494. anchorB = [ world.pxmi(anchorB[0]), world.pxmi(anchorB[1]) ];
  74495. var options = { localAnchorA: anchorA, localAnchorB: anchorB, localAxisA: axis, maxForce: maxForce, disableRotationalLock: !lockRotation };
  74496. p2.PrismaticConstraint.call(this, bodyA, bodyB, options);
  74497. };
  74498. Phaser.Physics.P2.PrismaticConstraint.prototype = Object.create(p2.PrismaticConstraint.prototype);
  74499. Phaser.Physics.P2.PrismaticConstraint.prototype.constructor = Phaser.Physics.P2.PrismaticConstraint;
  74500. /**
  74501. * @author Richard Davey <rich@photonstorm.com>
  74502. * @copyright 2016 Photon Storm Ltd.
  74503. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  74504. */
  74505. /**
  74506. * Connects two bodies at given offset points, letting them rotate relative to each other around this point.
  74507. * The pivot points are given in world (pixel) coordinates.
  74508. *
  74509. * @class Phaser.Physics.P2.RevoluteConstraint
  74510. * @constructor
  74511. * @param {Phaser.Physics.P2} world - A reference to the P2 World.
  74512. * @param {p2.Body} bodyA - First connected body.
  74513. * @param {Float32Array} pivotA - The point relative to the center of mass of bodyA which bodyA is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32].
  74514. * @param {p2.Body} bodyB - Second connected body.
  74515. * @param {Float32Array} pivotB - The point relative to the center of mass of bodyB which bodyB is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32].
  74516. * @param {number} [maxForce=0] - The maximum force that should be applied to constrain the bodies.
  74517. * @param {Float32Array} [worldPivot=null] - A pivot point given in world coordinates. If specified, localPivotA and localPivotB are automatically computed from this value.
  74518. */
  74519. Phaser.Physics.P2.RevoluteConstraint = function (world, bodyA, pivotA, bodyB, pivotB, maxForce, worldPivot) {
  74520. if (maxForce === undefined) { maxForce = Number.MAX_VALUE; }
  74521. if (worldPivot === undefined) { worldPivot = null; }
  74522. /**
  74523. * @property {Phaser.Game} game - Local reference to game.
  74524. */
  74525. this.game = world.game;
  74526. /**
  74527. * @property {Phaser.Physics.P2} world - Local reference to P2 World.
  74528. */
  74529. this.world = world;
  74530. pivotA = [ world.pxmi(pivotA[0]), world.pxmi(pivotA[1]) ];
  74531. pivotB = [ world.pxmi(pivotB[0]), world.pxmi(pivotB[1]) ];
  74532. if (worldPivot)
  74533. {
  74534. worldPivot = [ world.pxmi(worldPivot[0]), world.pxmi(worldPivot[1]) ];
  74535. }
  74536. var options = { worldPivot: worldPivot, localPivotA: pivotA, localPivotB: pivotB, maxForce: maxForce };
  74537. p2.RevoluteConstraint.call(this, bodyA, bodyB, options);
  74538. };
  74539. Phaser.Physics.P2.RevoluteConstraint.prototype = Object.create(p2.RevoluteConstraint.prototype);
  74540. Phaser.Physics.P2.RevoluteConstraint.prototype.constructor = Phaser.Physics.P2.RevoluteConstraint;
  74541. /**
  74542. * @author Richard Davey <rich@photonstorm.com>
  74543. * @copyright 2016 Photon Storm Ltd.
  74544. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  74545. */
  74546. /**
  74547. * An Image Collection is a special tileset containing mulitple images, with no slicing into each image.
  74548. *
  74549. * Image Collections are normally created automatically when Tiled data is loaded.
  74550. *
  74551. * @class Phaser.ImageCollection
  74552. * @constructor
  74553. * @param {string} name - The name of the image collection in the map data.
  74554. * @param {integer} firstgid - The first image index this image collection contains.
  74555. * @param {integer} [width=32] - Width of widest image (in pixels).
  74556. * @param {integer} [height=32] - Height of tallest image (in pixels).
  74557. * @param {integer} [margin=0] - The margin around all images in the collection (in pixels).
  74558. * @param {integer} [spacing=0] - The spacing between each image in the collection (in pixels).
  74559. * @param {object} [properties={}] - Custom Image Collection properties.
  74560. */
  74561. Phaser.ImageCollection = function (name, firstgid, width, height, margin, spacing, properties) {
  74562. if (width === undefined || width <= 0) { width = 32; }
  74563. if (height === undefined || height <= 0) { height = 32; }
  74564. if (margin === undefined) { margin = 0; }
  74565. if (spacing === undefined) { spacing = 0; }
  74566. /**
  74567. * The name of the Image Collection.
  74568. * @property {string} name
  74569. */
  74570. this.name = name;
  74571. /**
  74572. * The Tiled firstgid value.
  74573. * This is the starting index of the first image index this Image Collection contains.
  74574. * @property {integer} firstgid
  74575. */
  74576. this.firstgid = firstgid | 0;
  74577. /**
  74578. * The width of the widest image (in pixels).
  74579. * @property {integer} imageWidth
  74580. * @readonly
  74581. */
  74582. this.imageWidth = width | 0;
  74583. /**
  74584. * The height of the tallest image (in pixels).
  74585. * @property {integer} imageHeight
  74586. * @readonly
  74587. */
  74588. this.imageHeight = height | 0;
  74589. /**
  74590. * The margin around the images in the collection (in pixels).
  74591. * Use `setSpacing` to change.
  74592. * @property {integer} imageMarge
  74593. * @readonly
  74594. */
  74595. // Modified internally
  74596. this.imageMargin = margin | 0;
  74597. /**
  74598. * The spacing between each image in the collection (in pixels).
  74599. * Use `setSpacing` to change.
  74600. * @property {integer} imageSpacing
  74601. * @readonly
  74602. */
  74603. this.imageSpacing = spacing | 0;
  74604. /**
  74605. * Image Collection-specific properties that are typically defined in the Tiled editor.
  74606. * @property {object} properties
  74607. */
  74608. this.properties = properties || {};
  74609. /**
  74610. * The cached images that are a part of this collection.
  74611. * @property {array} images
  74612. * @readonly
  74613. */
  74614. // Modified internally
  74615. this.images = [];
  74616. /**
  74617. * The total number of images in the image collection.
  74618. * @property {integer} total
  74619. * @readonly
  74620. */
  74621. // Modified internally
  74622. this.total = 0;
  74623. };
  74624. Phaser.ImageCollection.prototype = {
  74625. /**
  74626. * Returns true if and only if this image collection contains the given image index.
  74627. *
  74628. * @method Phaser.ImageCollection#containsImageIndex
  74629. * @param {integer} imageIndex - The image index to search for.
  74630. * @return {boolean} True if this Image Collection contains the given index.
  74631. */
  74632. containsImageIndex: function (imageIndex) {
  74633. return (
  74634. imageIndex >= this.firstgid &&
  74635. imageIndex < (this.firstgid + this.total)
  74636. );
  74637. },
  74638. /**
  74639. * Add an image to this Image Collection.
  74640. *
  74641. * @method Phaser.ImageCollection#addImage
  74642. * @param {integer} gid - The gid of the image in the Image Collection.
  74643. * @param {string} image - The the key of the image in the Image Collection and in the cache.
  74644. */
  74645. addImage: function (gid, image) {
  74646. this.images.push({ gid: gid, image: image });
  74647. this.total++;
  74648. }
  74649. };
  74650. Phaser.ImageCollection.prototype.constructor = Phaser.ImageCollection;
  74651. /**
  74652. * @author Richard Davey <rich@photonstorm.com>
  74653. * @copyright 2016 Photon Storm Ltd.
  74654. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  74655. */
  74656. /**
  74657. * A Tile is a representation of a single tile within the Tilemap.
  74658. *
  74659. * @class Phaser.Tile
  74660. * @constructor
  74661. * @param {object} layer - The layer in the Tilemap data that this tile belongs to.
  74662. * @param {number} index - The index of this tile type in the core map data.
  74663. * @param {number} x - The x coordinate of this tile.
  74664. * @param {number} y - The y coordinate of this tile.
  74665. * @param {number} width - Width of the tile.
  74666. * @param {number} height - Height of the tile.
  74667. */
  74668. Phaser.Tile = function (layer, index, x, y, width, height) {
  74669. /**
  74670. * @property {object} layer - The layer in the Tilemap data that this tile belongs to.
  74671. */
  74672. this.layer = layer;
  74673. /**
  74674. * @property {number} index - The index of this tile within the map data corresponding to the tileset, or -1 if this represents a blank/null tile.
  74675. */
  74676. this.index = index;
  74677. /**
  74678. * @property {number} x - The x map coordinate of this tile.
  74679. */
  74680. this.x = x;
  74681. /**
  74682. * @property {number} y - The y map coordinate of this tile.
  74683. */
  74684. this.y = y;
  74685. /**
  74686. * @property {number} rotation - The rotation angle of this tile.
  74687. */
  74688. this.rotation = 0;
  74689. /**
  74690. * @property {boolean} flipped - Whether this tile is flipped (mirrored) or not.
  74691. */
  74692. this.flipped = false;
  74693. /**
  74694. * @property {number} x - The x map coordinate of this tile.
  74695. */
  74696. this.worldX = x * width;
  74697. /**
  74698. * @property {number} y - The y map coordinate of this tile.
  74699. */
  74700. this.worldY = y * height;
  74701. /**
  74702. * @property {number} width - The width of the tile in pixels.
  74703. */
  74704. this.width = width;
  74705. /**
  74706. * @property {number} height - The height of the tile in pixels.
  74707. */
  74708. this.height = height;
  74709. /**
  74710. * @property {number} width - The width of the tile in pixels.
  74711. */
  74712. this.centerX = Math.abs(width / 2);
  74713. /**
  74714. * @property {number} height - The height of the tile in pixels.
  74715. */
  74716. this.centerY = Math.abs(height / 2);
  74717. /**
  74718. * @property {number} alpha - The alpha value at which this tile is drawn to the canvas.
  74719. */
  74720. this.alpha = 1;
  74721. /**
  74722. * @property {object} properties - Tile specific properties.
  74723. */
  74724. this.properties = {};
  74725. /**
  74726. * @property {boolean} scanned - Has this tile been walked / turned into a poly?
  74727. */
  74728. this.scanned = false;
  74729. /**
  74730. * @property {boolean} faceTop - Is the top of this tile an interesting edge?
  74731. */
  74732. this.faceTop = false;
  74733. /**
  74734. * @property {boolean} faceBottom - Is the bottom of this tile an interesting edge?
  74735. */
  74736. this.faceBottom = false;
  74737. /**
  74738. * @property {boolean} faceLeft - Is the left of this tile an interesting edge?
  74739. */
  74740. this.faceLeft = false;
  74741. /**
  74742. * @property {boolean} faceRight - Is the right of this tile an interesting edge?
  74743. */
  74744. this.faceRight = false;
  74745. /**
  74746. * @property {boolean} collideLeft - Indicating collide with any object on the left.
  74747. * @default
  74748. */
  74749. this.collideLeft = false;
  74750. /**
  74751. * @property {boolean} collideRight - Indicating collide with any object on the right.
  74752. * @default
  74753. */
  74754. this.collideRight = false;
  74755. /**
  74756. * @property {boolean} collideUp - Indicating collide with any object on the top.
  74757. * @default
  74758. */
  74759. this.collideUp = false;
  74760. /**
  74761. * @property {boolean} collideDown - Indicating collide with any object on the bottom.
  74762. * @default
  74763. */
  74764. this.collideDown = false;
  74765. /**
  74766. * @property {function} collisionCallback - Tile collision callback.
  74767. * @default
  74768. */
  74769. this.collisionCallback = null;
  74770. /**
  74771. * @property {object} collisionCallbackContext - The context in which the collision callback will be called.
  74772. * @default
  74773. */
  74774. this.collisionCallbackContext = this;
  74775. };
  74776. Phaser.Tile.prototype = {
  74777. /**
  74778. * Check if the given x and y world coordinates are within this Tile.
  74779. *
  74780. * @method Phaser.Tile#containsPoint
  74781. * @param {number} x - The x coordinate to test.
  74782. * @param {number} y - The y coordinate to test.
  74783. * @return {boolean} True if the coordinates are within this Tile, otherwise false.
  74784. */
  74785. containsPoint: function (x, y) {
  74786. return !(x < this.worldX || y < this.worldY || x > this.right || y > this.bottom);
  74787. },
  74788. /**
  74789. * Check for intersection with this tile.
  74790. *
  74791. * @method Phaser.Tile#intersects
  74792. * @param {number} x - The x axis in pixels.
  74793. * @param {number} y - The y axis in pixels.
  74794. * @param {number} right - The right point.
  74795. * @param {number} bottom - The bottom point.
  74796. */
  74797. intersects: function (x, y, right, bottom) {
  74798. if (right <= this.worldX)
  74799. {
  74800. return false;
  74801. }
  74802. if (bottom <= this.worldY)
  74803. {
  74804. return false;
  74805. }
  74806. if (x >= this.worldX + this.width)
  74807. {
  74808. return false;
  74809. }
  74810. if (y >= this.worldY + this.height)
  74811. {
  74812. return false;
  74813. }
  74814. return true;
  74815. },
  74816. /**
  74817. * Set a callback to be called when this tile is hit by an object.
  74818. * The callback must true true for collision processing to take place.
  74819. *
  74820. * @method Phaser.Tile#setCollisionCallback
  74821. * @param {function} callback - Callback function.
  74822. * @param {object} context - Callback will be called within this context.
  74823. */
  74824. setCollisionCallback: function (callback, context) {
  74825. this.collisionCallback = callback;
  74826. this.collisionCallbackContext = context;
  74827. },
  74828. /**
  74829. * Clean up memory.
  74830. *
  74831. * @method Phaser.Tile#destroy
  74832. */
  74833. destroy: function () {
  74834. this.collisionCallback = null;
  74835. this.collisionCallbackContext = null;
  74836. this.properties = null;
  74837. },
  74838. /**
  74839. * Sets the collision flags for each side of this tile and updates the interesting faces list.
  74840. *
  74841. * @method Phaser.Tile#setCollision
  74842. * @param {boolean} left - Indicating collide with any object on the left.
  74843. * @param {boolean} right - Indicating collide with any object on the right.
  74844. * @param {boolean} up - Indicating collide with any object on the top.
  74845. * @param {boolean} down - Indicating collide with any object on the bottom.
  74846. */
  74847. setCollision: function (left, right, up, down) {
  74848. this.collideLeft = left;
  74849. this.collideRight = right;
  74850. this.collideUp = up;
  74851. this.collideDown = down;
  74852. this.faceLeft = left;
  74853. this.faceRight = right;
  74854. this.faceTop = up;
  74855. this.faceBottom = down;
  74856. },
  74857. /**
  74858. * Reset collision status flags.
  74859. *
  74860. * @method Phaser.Tile#resetCollision
  74861. */
  74862. resetCollision: function () {
  74863. this.collideLeft = false;
  74864. this.collideRight = false;
  74865. this.collideUp = false;
  74866. this.collideDown = false;
  74867. this.faceTop = false;
  74868. this.faceBottom = false;
  74869. this.faceLeft = false;
  74870. this.faceRight = false;
  74871. },
  74872. /**
  74873. * Is this tile interesting?
  74874. *
  74875. * @method Phaser.Tile#isInteresting
  74876. * @param {boolean} collides - If true will check any collides value.
  74877. * @param {boolean} faces - If true will check any face value.
  74878. * @return {boolean} True if the Tile is interesting, otherwise false.
  74879. */
  74880. isInteresting: function (collides, faces) {
  74881. if (collides && faces)
  74882. {
  74883. // Does this tile have any collide flags OR interesting face?
  74884. return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown || this.faceTop || this.faceBottom || this.faceLeft || this.faceRight || this.collisionCallback);
  74885. }
  74886. else if (collides)
  74887. {
  74888. // Does this tile collide?
  74889. return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown);
  74890. }
  74891. else if (faces)
  74892. {
  74893. // Does this tile have an interesting face?
  74894. return (this.faceTop || this.faceBottom || this.faceLeft || this.faceRight);
  74895. }
  74896. return false;
  74897. },
  74898. /**
  74899. * Copies the tile data and properties from the given tile to this tile.
  74900. *
  74901. * @method Phaser.Tile#copy
  74902. * @param {Phaser.Tile} tile - The tile to copy from.
  74903. */
  74904. copy: function (tile) {
  74905. this.index = tile.index;
  74906. this.alpha = tile.alpha;
  74907. this.properties = tile.properties;
  74908. this.collideUp = tile.collideUp;
  74909. this.collideDown = tile.collideDown;
  74910. this.collideLeft = tile.collideLeft;
  74911. this.collideRight = tile.collideRight;
  74912. this.collisionCallback = tile.collisionCallback;
  74913. this.collisionCallbackContext = tile.collisionCallbackContext;
  74914. }
  74915. };
  74916. Phaser.Tile.prototype.constructor = Phaser.Tile;
  74917. /**
  74918. * @name Phaser.Tile#collides
  74919. * @property {boolean} collides - True if this tile can collide on any of its faces.
  74920. * @readonly
  74921. */
  74922. Object.defineProperty(Phaser.Tile.prototype, "collides", {
  74923. get: function () {
  74924. return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown);
  74925. }
  74926. });
  74927. /**
  74928. * @name Phaser.Tile#canCollide
  74929. * @property {boolean} canCollide - True if this tile can collide on any of its faces or has a collision callback set.
  74930. * @readonly
  74931. */
  74932. Object.defineProperty(Phaser.Tile.prototype, "canCollide", {
  74933. get: function () {
  74934. return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown || this.collisionCallback);
  74935. }
  74936. });
  74937. /**
  74938. * @name Phaser.Tile#left
  74939. * @property {number} left - The x value in pixels.
  74940. * @readonly
  74941. */
  74942. Object.defineProperty(Phaser.Tile.prototype, "left", {
  74943. get: function () {
  74944. return this.worldX;
  74945. }
  74946. });
  74947. /**
  74948. * @name Phaser.Tile#right
  74949. * @property {number} right - The sum of the x and width properties.
  74950. * @readonly
  74951. */
  74952. Object.defineProperty(Phaser.Tile.prototype, "right", {
  74953. get: function () {
  74954. return this.worldX + this.width;
  74955. }
  74956. });
  74957. /**
  74958. * @name Phaser.Tile#top
  74959. * @property {number} top - The y value.
  74960. * @readonly
  74961. */
  74962. Object.defineProperty(Phaser.Tile.prototype, "top", {
  74963. get: function () {
  74964. return this.worldY;
  74965. }
  74966. });
  74967. /**
  74968. * @name Phaser.Tile#bottom
  74969. * @property {number} bottom - The sum of the y and height properties.
  74970. * @readonly
  74971. */
  74972. Object.defineProperty(Phaser.Tile.prototype, "bottom", {
  74973. get: function () {
  74974. return this.worldY + this.height;
  74975. }
  74976. });
  74977. /**
  74978. * @author Richard Davey <rich@photonstorm.com>
  74979. * @copyright 2016 Photon Storm Ltd.
  74980. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  74981. */
  74982. /**
  74983. * Creates a new Phaser.Tilemap object. The map can either be populated with data from a Tiled JSON file or from a CSV file.
  74984. * To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key.
  74985. * When using CSV data you must provide the key and the tileWidth and tileHeight parameters.
  74986. * If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here.
  74987. * Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it.
  74988. * A Tile map is rendered to the display using a TilemapLayer. It is not added to the display list directly itself.
  74989. * A map may have multiple layers. You can perform operations on the map data such as copying, pasting, filling and shuffling the tiles around.
  74990. *
  74991. * @class Phaser.Tilemap
  74992. * @constructor
  74993. * @param {Phaser.Game} game - Game reference to the currently running game.
  74994. * @param {string} [key] - The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`.
  74995. * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
  74996. * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
  74997. * @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this.
  74998. * @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this.
  74999. */
  75000. Phaser.Tilemap = function (game, key, tileWidth, tileHeight, width, height) {
  75001. /**
  75002. * @property {Phaser.Game} game - A reference to the currently running Game.
  75003. */
  75004. this.game = game;
  75005. /**
  75006. * @property {string} key - The key of this map data in the Phaser.Cache.
  75007. */
  75008. this.key = key;
  75009. var data = Phaser.TilemapParser.parse(this.game, key, tileWidth, tileHeight, width, height);
  75010. if (data === null)
  75011. {
  75012. return;
  75013. }
  75014. /**
  75015. * @property {number} width - The width of the map (in tiles).
  75016. */
  75017. this.width = data.width;
  75018. /**
  75019. * @property {number} height - The height of the map (in tiles).
  75020. */
  75021. this.height = data.height;
  75022. /**
  75023. * @property {number} tileWidth - The base width of the tiles in the map (in pixels).
  75024. */
  75025. this.tileWidth = data.tileWidth;
  75026. /**
  75027. * @property {number} tileHeight - The base height of the tiles in the map (in pixels).
  75028. */
  75029. this.tileHeight = data.tileHeight;
  75030. /**
  75031. * @property {string} orientation - The orientation of the map data (as specified in Tiled), usually 'orthogonal'.
  75032. */
  75033. this.orientation = data.orientation;
  75034. /**
  75035. * @property {number} format - The format of the map data, either Phaser.Tilemap.CSV or Phaser.Tilemap.TILED_JSON.
  75036. */
  75037. this.format = data.format;
  75038. /**
  75039. * @property {number} version - The version of the map data (as specified in Tiled, usually 1).
  75040. */
  75041. this.version = data.version;
  75042. /**
  75043. * @property {object} properties - Map specific properties as specified in Tiled.
  75044. */
  75045. this.properties = data.properties;
  75046. /**
  75047. * @property {number} widthInPixels - The width of the map in pixels based on width * tileWidth.
  75048. */
  75049. this.widthInPixels = data.widthInPixels;
  75050. /**
  75051. * @property {number} heightInPixels - The height of the map in pixels based on height * tileHeight.
  75052. */
  75053. this.heightInPixels = data.heightInPixels;
  75054. /**
  75055. * @property {array} layers - An array of Tilemap layer data.
  75056. */
  75057. this.layers = data.layers;
  75058. /**
  75059. * @property {array} tilesets - An array of Tilesets.
  75060. */
  75061. this.tilesets = data.tilesets;
  75062. /**
  75063. * @property {array} imagecollections - An array of Image Collections.
  75064. */
  75065. this.imagecollections = data.imagecollections;
  75066. /**
  75067. * @property {array} tiles - The super array of Tiles.
  75068. */
  75069. this.tiles = data.tiles;
  75070. /**
  75071. * @property {array} objects - An array of Tiled Object Layers.
  75072. */
  75073. this.objects = data.objects;
  75074. /**
  75075. * @property {array} collideIndexes - An array of tile indexes that collide.
  75076. */
  75077. this.collideIndexes = [];
  75078. /**
  75079. * @property {array} collision - An array of collision data (polylines, etc).
  75080. */
  75081. this.collision = data.collision;
  75082. /**
  75083. * @property {array} images - An array of Tiled Image Layers.
  75084. */
  75085. this.images = data.images;
  75086. /**
  75087. * @property {number} currentLayer - The current layer.
  75088. */
  75089. this.currentLayer = 0;
  75090. /**
  75091. * @property {array} debugMap - Map data used for debug values only.
  75092. */
  75093. this.debugMap = [];
  75094. /**
  75095. * @property {array} _results - Internal var.
  75096. * @private
  75097. */
  75098. this._results = [];
  75099. /**
  75100. * @property {number} _tempA - Internal var.
  75101. * @private
  75102. */
  75103. this._tempA = 0;
  75104. /**
  75105. * @property {number} _tempB - Internal var.
  75106. * @private
  75107. */
  75108. this._tempB = 0;
  75109. };
  75110. /**
  75111. * @constant
  75112. * @type {number}
  75113. */
  75114. Phaser.Tilemap.CSV = 0;
  75115. /**
  75116. * @constant
  75117. * @type {number}
  75118. */
  75119. Phaser.Tilemap.TILED_JSON = 1;
  75120. /**
  75121. * @constant
  75122. * @type {number}
  75123. */
  75124. Phaser.Tilemap.NORTH = 0;
  75125. /**
  75126. * @constant
  75127. * @type {number}
  75128. */
  75129. Phaser.Tilemap.EAST = 1;
  75130. /**
  75131. * @constant
  75132. * @type {number}
  75133. */
  75134. Phaser.Tilemap.SOUTH = 2;
  75135. /**
  75136. * @constant
  75137. * @type {number}
  75138. */
  75139. Phaser.Tilemap.WEST = 3;
  75140. Phaser.Tilemap.prototype = {
  75141. /**
  75142. * Creates an empty map of the given dimensions and one blank layer. If layers already exist they are erased.
  75143. *
  75144. * @method Phaser.Tilemap#create
  75145. * @param {string} name - The name of the default layer of the map.
  75146. * @param {number} width - The width of the map in tiles.
  75147. * @param {number} height - The height of the map in tiles.
  75148. * @param {number} tileWidth - The width of the tiles the map uses for calculations.
  75149. * @param {number} tileHeight - The height of the tiles the map uses for calculations.
  75150. * @param {Phaser.Group} [group] - Optional Group to add the layer to. If not specified it will be added to the World group.
  75151. * @return {Phaser.TilemapLayer} The TilemapLayer object. This is an extension of Phaser.Image and can be moved around the display list accordingly.
  75152. */
  75153. create: function (name, width, height, tileWidth, tileHeight, group) {
  75154. if (group === undefined) { group = this.game.world; }
  75155. this.width = width;
  75156. this.height = height;
  75157. this.setTileSize(tileWidth, tileHeight);
  75158. this.layers.length = 0;
  75159. return this.createBlankLayer(name, width, height, tileWidth, tileHeight, group);
  75160. },
  75161. /**
  75162. * Sets the base tile size for the map.
  75163. *
  75164. * @method Phaser.Tilemap#setTileSize
  75165. * @param {number} tileWidth - The width of the tiles the map uses for calculations.
  75166. * @param {number} tileHeight - The height of the tiles the map uses for calculations.
  75167. */
  75168. setTileSize: function (tileWidth, tileHeight) {
  75169. this.tileWidth = tileWidth;
  75170. this.tileHeight = tileHeight;
  75171. this.widthInPixels = this.width * tileWidth;
  75172. this.heightInPixels = this.height * tileHeight;
  75173. },
  75174. /**
  75175. * Adds an image to the map to be used as a tileset. A single map may use multiple tilesets.
  75176. * Note that the tileset name can be found in the JSON file exported from Tiled, or in the Tiled editor.
  75177. *
  75178. * @method Phaser.Tilemap#addTilesetImage
  75179. * @param {string} tileset - The name of the tileset as specified in the map data.
  75180. * @param {string|Phaser.BitmapData} [key] - The key of the Phaser.Cache image used for this tileset.
  75181. * If `undefined` or `null` it will look for an image with a key matching the tileset parameter.
  75182. * You can also pass in a BitmapData which can be used instead of an Image.
  75183. * @param {number} [tileWidth=32] - The width of the tiles in the Tileset Image. If not given it will default to the map.tileWidth value, if that isn't set then 32.
  75184. * @param {number} [tileHeight=32] - The height of the tiles in the Tileset Image. If not given it will default to the map.tileHeight value, if that isn't set then 32.
  75185. * @param {number} [tileMargin=0] - The width of the tiles in the Tileset Image.
  75186. * @param {number} [tileSpacing=0] - The height of the tiles in the Tileset Image.
  75187. * @param {number} [gid=0] - If adding multiple tilesets to a blank/dynamic map, specify the starting GID the set will use here.
  75188. * @return {Phaser.Tileset} Returns the Tileset object that was created or updated, or null if it failed.
  75189. */
  75190. addTilesetImage: function (tileset, key, tileWidth, tileHeight, tileMargin, tileSpacing, gid) {
  75191. if (tileset === undefined) { return null; }
  75192. if (tileWidth === undefined) { tileWidth = this.tileWidth; }
  75193. if (tileHeight === undefined) { tileHeight = this.tileHeight; }
  75194. if (tileMargin === undefined) { tileMargin = 0; }
  75195. if (tileSpacing === undefined) { tileSpacing = 0; }
  75196. if (gid === undefined) { gid = 0; }
  75197. // In-case we're working from a blank map
  75198. if (tileWidth === 0)
  75199. {
  75200. tileWidth = 32;
  75201. }
  75202. if (tileHeight === 0)
  75203. {
  75204. tileHeight = 32;
  75205. }
  75206. var img = null;
  75207. if (key === undefined || key === null)
  75208. {
  75209. key = tileset;
  75210. }
  75211. if (key instanceof Phaser.BitmapData)
  75212. {
  75213. img = key.canvas;
  75214. }
  75215. else
  75216. {
  75217. if (!this.game.cache.checkImageKey(key))
  75218. {
  75219. console.warn('Phaser.Tilemap.addTilesetImage: Invalid image key given: "' + key + '"');
  75220. return null;
  75221. }
  75222. img = this.game.cache.getImage(key);
  75223. }
  75224. var idx = this.getTilesetIndex(tileset);
  75225. if (idx === null && this.format === Phaser.Tilemap.TILED_JSON)
  75226. {
  75227. console.warn('Phaser.Tilemap.addTilesetImage: No data found in the JSON matching the tileset name: "' + tileset + '"');
  75228. return null;
  75229. }
  75230. if (this.tilesets[idx])
  75231. {
  75232. this.tilesets[idx].setImage(img);
  75233. return this.tilesets[idx];
  75234. }
  75235. else
  75236. {
  75237. var newSet = new Phaser.Tileset(tileset, gid, tileWidth, tileHeight, tileMargin, tileSpacing, {});
  75238. newSet.setImage(img);
  75239. this.tilesets.push(newSet);
  75240. var i = this.tilesets.length - 1;
  75241. var x = tileMargin;
  75242. var y = tileMargin;
  75243. var count = 0;
  75244. var countX = 0;
  75245. var countY = 0;
  75246. for (var t = gid; t < gid + newSet.total; t++)
  75247. {
  75248. this.tiles[t] = [x, y, i];
  75249. x += tileWidth + tileSpacing;
  75250. count++;
  75251. if (count === newSet.total)
  75252. {
  75253. break;
  75254. }
  75255. countX++;
  75256. if (countX === newSet.columns)
  75257. {
  75258. x = tileMargin;
  75259. y += tileHeight + tileSpacing;
  75260. countX = 0;
  75261. countY++;
  75262. if (countY === newSet.rows)
  75263. {
  75264. break;
  75265. }
  75266. }
  75267. }
  75268. return newSet;
  75269. }
  75270. return null;
  75271. },
  75272. /**
  75273. * Creates a Sprite for every object matching the given gid in the map data. You can optionally specify the group that the Sprite will be created in. If none is
  75274. * given it will be created in the World. All properties from the map data objectgroup are copied across to the Sprite, so you can use this as an easy way to
  75275. * configure Sprite properties from within the map editor. For example giving an object a property of alpha: 0.5 in the map editor will duplicate that when the
  75276. * Sprite is created. You could also give it a value like: body.velocity.x: 100 to set it moving automatically.
  75277. *
  75278. * @method Phaser.Tilemap#createFromObjects
  75279. * @param {string} name - The name of the Object Group to create Sprites from.
  75280. * @param {number} gid - The layer array index value, or if a string is given the layer name within the map data.
  75281. * @param {string} key - The Game.cache key of the image that this Sprite will use.
  75282. * @param {number|string} [frame] - If the Sprite image contains multiple frames you can specify which one to use here.
  75283. * @param {boolean} [exists=true] - The default exists state of the Sprite.
  75284. * @param {boolean} [autoCull=false] - The default autoCull state of the Sprite. Sprites that are autoCulled are culled from the camera if out of its range.
  75285. * @param {Phaser.Group} [group=Phaser.World] - Group to add the Sprite to. If not specified it will be added to the World group.
  75286. * @param {object} [CustomClass=Phaser.Sprite] - If you wish to create your own class, rather than Phaser.Sprite, pass the class here. Your class must extend Phaser.Sprite and have the same constructor parameters.
  75287. * @param {boolean} [adjustY=true] - By default the Tiled map editor uses a bottom-left coordinate system. Phaser uses top-left. So most objects will appear too low down. This parameter moves them up by their height.
  75288. */
  75289. createFromObjects: function (name, gid, key, frame, exists, autoCull, group, CustomClass, adjustY) {
  75290. if (exists === undefined) { exists = true; }
  75291. if (autoCull === undefined) { autoCull = false; }
  75292. if (group === undefined) { group = this.game.world; }
  75293. if (CustomClass === undefined) { CustomClass = Phaser.Sprite; }
  75294. if (adjustY === undefined) { adjustY = true; }
  75295. if (!this.objects[name])
  75296. {
  75297. console.warn('Tilemap.createFromObjects: Invalid objectgroup name given: ' + name);
  75298. return;
  75299. }
  75300. for (var i = 0; i < this.objects[name].length; i++)
  75301. {
  75302. var found = false;
  75303. var obj = this.objects[name][i];
  75304. if (obj.gid !== undefined && typeof gid === 'number' && obj.gid === gid)
  75305. {
  75306. found = true;
  75307. }
  75308. else if (obj.id !== undefined && typeof gid === 'number' && obj.id === gid)
  75309. {
  75310. found = true;
  75311. }
  75312. else if (obj.name !== undefined && typeof gid === 'string' && obj.name === gid)
  75313. {
  75314. found = true;
  75315. }
  75316. if (found)
  75317. {
  75318. var sprite = new CustomClass(this.game, parseFloat(obj.x, 10), parseFloat(obj.y, 10), key, frame);
  75319. sprite.name = obj.name;
  75320. sprite.visible = obj.visible;
  75321. sprite.autoCull = autoCull;
  75322. sprite.exists = exists;
  75323. if (obj.width)
  75324. {
  75325. sprite.width = obj.width;
  75326. }
  75327. if (obj.height)
  75328. {
  75329. sprite.height = obj.height;
  75330. }
  75331. if (obj.rotation)
  75332. {
  75333. sprite.angle = obj.rotation;
  75334. }
  75335. if (adjustY)
  75336. {
  75337. sprite.y -= sprite.height;
  75338. }
  75339. group.add(sprite);
  75340. for (var property in obj.properties)
  75341. {
  75342. group.set(sprite, property, obj.properties[property], false, false, 0, true);
  75343. }
  75344. }
  75345. }
  75346. },
  75347. /**
  75348. * Creates a Sprite for every object matching the given tile indexes in the map data.
  75349. * You can specify the group that the Sprite will be created in. If none is given it will be created in the World.
  75350. * You can optional specify if the tile will be replaced with another after the Sprite is created. This is useful if you want to lay down special
  75351. * tiles in a level that are converted to Sprites, but want to replace the tile itself with a floor tile or similar once converted.
  75352. *
  75353. * @method Phaser.Tilemap#createFromTiles
  75354. * @param {integer|Array} tiles - The tile index, or array of indexes, to create Sprites from.
  75355. * @param {integer|Array} replacements - The tile index, or array of indexes, to change a converted tile to. Set to `null` to not change.
  75356. * @param {string} key - The Game.cache key of the image that this Sprite will use.
  75357. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on.
  75358. * @param {Phaser.Group} [group=Phaser.World] - Group to add the Sprite to. If not specified it will be added to the World group.
  75359. * @param {object} [properties] - An object that contains the default properties for your newly created Sprite. This object will be iterated and any matching Sprite property will be set.
  75360. * @return {integer} The number of Sprites that were created.
  75361. */
  75362. createFromTiles: function (tiles, replacements, key, layer, group, properties) {
  75363. if (typeof tiles === 'number') { tiles = [tiles]; }
  75364. if (replacements === undefined || replacements === null)
  75365. {
  75366. replacements = [];
  75367. }
  75368. else if (typeof replacements === 'number')
  75369. {
  75370. replacements = [replacements];
  75371. }
  75372. layer = this.getLayer(layer);
  75373. if (group === undefined) { group = this.game.world; }
  75374. if (properties === undefined) { properties = {}; }
  75375. if (properties.customClass === undefined)
  75376. {
  75377. properties.customClass = Phaser.Sprite;
  75378. }
  75379. if (properties.adjustY === undefined)
  75380. {
  75381. properties.adjustY = true;
  75382. }
  75383. var lw = this.layers[layer].width;
  75384. var lh = this.layers[layer].height;
  75385. this.copy(0, 0, lw, lh, layer);
  75386. if (this._results.length < 2)
  75387. {
  75388. return 0;
  75389. }
  75390. var total = 0;
  75391. var sprite;
  75392. for (var i = 1, len = this._results.length; i < len; i++)
  75393. {
  75394. if (tiles.indexOf(this._results[i].index) !== -1)
  75395. {
  75396. sprite = new properties.customClass(this.game, this._results[i].worldX, this._results[i].worldY, key);
  75397. for (var property in properties)
  75398. {
  75399. sprite[property] = properties[property];
  75400. }
  75401. group.add(sprite);
  75402. total++;
  75403. }
  75404. }
  75405. if (replacements.length === 1)
  75406. {
  75407. // Assume 1 replacement for all types of tile given
  75408. for (i = 0; i < tiles.length; i++)
  75409. {
  75410. this.replace(tiles[i], replacements[0], 0, 0, lw, lh, layer);
  75411. }
  75412. }
  75413. else if (replacements.length > 1)
  75414. {
  75415. // Assume 1 for 1 mapping
  75416. for (i = 0; i < tiles.length; i++)
  75417. {
  75418. this.replace(tiles[i], replacements[i], 0, 0, lw, lh, layer);
  75419. }
  75420. }
  75421. return total;
  75422. },
  75423. /**
  75424. * Creates a new TilemapLayer object. By default TilemapLayers are fixed to the camera.
  75425. * The `layer` parameter is important. If you've created your map in Tiled then you can get this by looking in Tiled and looking at the Layer name.
  75426. * Or you can open the JSON file it exports and look at the layers[].name value. Either way it must match.
  75427. * If you wish to create a blank layer to put your own tiles on then see Tilemap.createBlankLayer.
  75428. *
  75429. * @method Phaser.Tilemap#createLayer
  75430. * @param {number|string} layer - The layer array index value, or if a string is given the layer name, within the map data that this TilemapLayer represents.
  75431. * @param {number} [width] - The rendered width of the layer, should never be wider than Game.width. If not given it will be set to Game.width.
  75432. * @param {number} [height] - The rendered height of the layer, should never be wider than Game.height. If not given it will be set to Game.height.
  75433. * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
  75434. * @return {Phaser.TilemapLayer} The TilemapLayer object. This is an extension of Phaser.Sprite and can be moved around the display list accordingly.
  75435. */
  75436. createLayer: function (layer, width, height, group) {
  75437. // Add Buffer support for the left of the canvas
  75438. if (width === undefined) { width = this.game.width; }
  75439. if (height === undefined) { height = this.game.height; }
  75440. if (group === undefined) { group = this.game.world; }
  75441. var index = layer;
  75442. if (typeof layer === 'string')
  75443. {
  75444. index = this.getLayerIndex(layer);
  75445. }
  75446. if (index === null || index > this.layers.length)
  75447. {
  75448. console.warn('Tilemap.createLayer: Invalid layer ID given: ' + index);
  75449. return;
  75450. }
  75451. return group.add(new Phaser.TilemapLayer(this.game, this, index, width, height));
  75452. },
  75453. /**
  75454. * Creates a new and empty layer on this Tilemap. By default TilemapLayers are fixed to the camera.
  75455. *
  75456. * @method Phaser.Tilemap#createBlankLayer
  75457. * @param {string} name - The name of this layer. Must be unique within the map.
  75458. * @param {number} width - The width of the layer in tiles.
  75459. * @param {number} height - The height of the layer in tiles.
  75460. * @param {number} tileWidth - The width of the tiles the layer uses for calculations.
  75461. * @param {number} tileHeight - The height of the tiles the layer uses for calculations.
  75462. * @param {Phaser.Group} [group] - Optional Group to add the layer to. If not specified it will be added to the World group.
  75463. * @return {Phaser.TilemapLayer} The TilemapLayer object. This is an extension of Phaser.Image and can be moved around the display list accordingly.
  75464. */
  75465. createBlankLayer: function (name, width, height, tileWidth, tileHeight, group) {
  75466. if (group === undefined) { group = this.game.world; }
  75467. if (this.getLayerIndex(name) !== null)
  75468. {
  75469. console.warn('Tilemap.createBlankLayer: Layer with matching name already exists');
  75470. return;
  75471. }
  75472. var layer = {
  75473. name: name,
  75474. x: 0,
  75475. y: 0,
  75476. width: width,
  75477. height: height,
  75478. widthInPixels: width * tileWidth,
  75479. heightInPixels: height * tileHeight,
  75480. alpha: 1,
  75481. visible: true,
  75482. properties: {},
  75483. indexes: [],
  75484. callbacks: [],
  75485. bodies: [],
  75486. data: null
  75487. };
  75488. var row;
  75489. var output = [];
  75490. for (var y = 0; y < height; y++)
  75491. {
  75492. row = [];
  75493. for (var x = 0; x < width; x++)
  75494. {
  75495. // row.push(null);
  75496. row.push(new Phaser.Tile(layer, -1, x, y, tileWidth, tileHeight));
  75497. }
  75498. output.push(row);
  75499. }
  75500. layer.data = output;
  75501. this.layers.push(layer);
  75502. this.currentLayer = this.layers.length - 1;
  75503. var w = layer.widthInPixels;
  75504. var h = layer.heightInPixels;
  75505. if (w > this.game.width)
  75506. {
  75507. w = this.game.width;
  75508. }
  75509. if (h > this.game.height)
  75510. {
  75511. h = this.game.height;
  75512. }
  75513. var output = new Phaser.TilemapLayer(this.game, this, this.layers.length - 1, w, h);
  75514. output.name = name;
  75515. return group.add(output);
  75516. },
  75517. /**
  75518. * Gets the layer index based on the layers name.
  75519. *
  75520. * @method Phaser.Tilemap#getIndex
  75521. * @protected
  75522. * @param {array} location - The local array to search.
  75523. * @param {string} name - The name of the array element to get.
  75524. * @return {number} The index of the element in the array, or null if not found.
  75525. */
  75526. getIndex: function (location, name) {
  75527. for (var i = 0; i < location.length; i++)
  75528. {
  75529. if (location[i].name === name)
  75530. {
  75531. return i;
  75532. }
  75533. }
  75534. return null;
  75535. },
  75536. /**
  75537. * Gets the layer index based on its name.
  75538. *
  75539. * @method Phaser.Tilemap#getLayerIndex
  75540. * @param {string} name - The name of the layer to get.
  75541. * @return {number} The index of the layer in this tilemap, or null if not found.
  75542. */
  75543. getLayerIndex: function (name) {
  75544. return this.getIndex(this.layers, name);
  75545. },
  75546. /**
  75547. * Gets the tileset index based on its name.
  75548. *
  75549. * @method Phaser.Tilemap#getTilesetIndex
  75550. * @param {string} name - The name of the tileset to get.
  75551. * @return {number} The index of the tileset in this tilemap, or null if not found.
  75552. */
  75553. getTilesetIndex: function (name) {
  75554. return this.getIndex(this.tilesets, name);
  75555. },
  75556. /**
  75557. * Gets the image index based on its name.
  75558. *
  75559. * @method Phaser.Tilemap#getImageIndex
  75560. * @param {string} name - The name of the image to get.
  75561. * @return {number} The index of the image in this tilemap, or null if not found.
  75562. */
  75563. getImageIndex: function (name) {
  75564. return this.getIndex(this.images, name);
  75565. },
  75566. /**
  75567. * Sets a global collision callback for the given tile index within the layer. This will affect all tiles on this layer that have the same index.
  75568. * If a callback is already set for the tile index it will be replaced. Set the callback to null to remove it.
  75569. * If you want to set a callback for a tile at a specific location on the map then see setTileLocationCallback.
  75570. *
  75571. * @method Phaser.Tilemap#setTileIndexCallback
  75572. * @param {number|array} indexes - Either a single tile index, or an array of tile indexes to have a collision callback set for.
  75573. * @param {function} callback - The callback that will be invoked when the tile is collided with.
  75574. * @param {object} callbackContext - The context under which the callback is called.
  75575. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer.
  75576. */
  75577. setTileIndexCallback: function (indexes, callback, callbackContext, layer) {
  75578. layer = this.getLayer(layer);
  75579. if (typeof indexes === 'number')
  75580. {
  75581. // This may seem a bit wasteful, because it will cause empty array elements to be created, but the look-up cost is much
  75582. // less than having to iterate through the callbacks array hunting down tile indexes each frame, so I'll take the small memory hit.
  75583. this.layers[layer].callbacks[indexes] = { callback: callback, callbackContext: callbackContext };
  75584. }
  75585. else
  75586. {
  75587. for (var i = 0, len = indexes.length; i < len; i++)
  75588. {
  75589. this.layers[layer].callbacks[indexes[i]] = { callback: callback, callbackContext: callbackContext };
  75590. }
  75591. }
  75592. },
  75593. /**
  75594. * Sets a global collision callback for the given map location within the layer. This will affect all tiles on this layer found in the given area.
  75595. * If a callback is already set for the tile index it will be replaced. Set the callback to null to remove it.
  75596. * If you want to set a callback for a tile at a specific location on the map then see setTileLocationCallback.
  75597. *
  75598. * @method Phaser.Tilemap#setTileLocationCallback
  75599. * @param {number} x - X position of the top left of the area to copy (given in tiles, not pixels)
  75600. * @param {number} y - Y position of the top left of the area to copy (given in tiles, not pixels)
  75601. * @param {number} width - The width of the area to copy (given in tiles, not pixels)
  75602. * @param {number} height - The height of the area to copy (given in tiles, not pixels)
  75603. * @param {function} callback - The callback that will be invoked when the tile is collided with.
  75604. * @param {object} callbackContext - The context under which the callback is called.
  75605. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer.
  75606. */
  75607. setTileLocationCallback: function (x, y, width, height, callback, callbackContext, layer) {
  75608. layer = this.getLayer(layer);
  75609. this.copy(x, y, width, height, layer);
  75610. if (this._results.length < 2)
  75611. {
  75612. return;
  75613. }
  75614. for (var i = 1; i < this._results.length; i++)
  75615. {
  75616. this._results[i].setCollisionCallback(callback, callbackContext);
  75617. }
  75618. },
  75619. /**
  75620. * Sets collision the given tile or tiles. You can pass in either a single numeric index or an array of indexes: [ 2, 3, 15, 20].
  75621. * The `collides` parameter controls if collision will be enabled (true) or disabled (false).
  75622. *
  75623. * @method Phaser.Tilemap#setCollision
  75624. * @param {number|array} indexes - Either a single tile index, or an array of tile IDs to be checked for collision.
  75625. * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision.
  75626. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer.
  75627. * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update.
  75628. */
  75629. setCollision: function (indexes, collides, layer, recalculate) {
  75630. if (collides === undefined) { collides = true; }
  75631. if (recalculate === undefined) { recalculate = true; }
  75632. layer = this.getLayer(layer);
  75633. if (typeof indexes === 'number')
  75634. {
  75635. return this.setCollisionByIndex(indexes, collides, layer, true);
  75636. }
  75637. else if (Array.isArray(indexes))
  75638. {
  75639. // Collide all of the IDs given in the indexes array
  75640. for (var i = 0; i < indexes.length; i++)
  75641. {
  75642. this.setCollisionByIndex(indexes[i], collides, layer, false);
  75643. }
  75644. if (recalculate)
  75645. {
  75646. // Now re-calculate interesting faces
  75647. this.calculateFaces(layer);
  75648. }
  75649. }
  75650. },
  75651. /**
  75652. * Sets collision on a range of tiles where the tile IDs increment sequentially.
  75653. * Calling this with a start value of 10 and a stop value of 14 would set collision for tiles 10, 11, 12, 13 and 14.
  75654. * The `collides` parameter controls if collision will be enabled (true) or disabled (false).
  75655. *
  75656. * @method Phaser.Tilemap#setCollisionBetween
  75657. * @param {number} start - The first index of the tile to be set for collision.
  75658. * @param {number} stop - The last index of the tile to be set for collision.
  75659. * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision.
  75660. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer.
  75661. * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update.
  75662. */
  75663. setCollisionBetween: function (start, stop, collides, layer, recalculate) {
  75664. if (collides === undefined) { collides = true; }
  75665. if (recalculate === undefined) { recalculate = true; }
  75666. layer = this.getLayer(layer);
  75667. if (start > stop)
  75668. {
  75669. return;
  75670. }
  75671. for (var index = start; index <= stop; index++)
  75672. {
  75673. this.setCollisionByIndex(index, collides, layer, false);
  75674. }
  75675. if (recalculate)
  75676. {
  75677. // Now re-calculate interesting faces
  75678. this.calculateFaces(layer);
  75679. }
  75680. },
  75681. /**
  75682. * Sets collision on all tiles in the given layer, except for the IDs of those in the given array.
  75683. * The `collides` parameter controls if collision will be enabled (true) or disabled (false).
  75684. *
  75685. * @method Phaser.Tilemap#setCollisionByExclusion
  75686. * @param {array} indexes - An array of the tile IDs to not be counted for collision.
  75687. * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision.
  75688. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer.
  75689. * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update.
  75690. */
  75691. setCollisionByExclusion: function (indexes, collides, layer, recalculate) {
  75692. if (collides === undefined) { collides = true; }
  75693. if (recalculate === undefined) { recalculate = true; }
  75694. layer = this.getLayer(layer);
  75695. // Collide everything, except the IDs given in the indexes array
  75696. for (var i = 0, len = this.tiles.length; i < len; i++)
  75697. {
  75698. if (indexes.indexOf(i) === -1)
  75699. {
  75700. this.setCollisionByIndex(i, collides, layer, false);
  75701. }
  75702. }
  75703. if (recalculate)
  75704. {
  75705. // Now re-calculate interesting faces
  75706. this.calculateFaces(layer);
  75707. }
  75708. },
  75709. /**
  75710. * Sets collision values on a tile in the set.
  75711. * You shouldn't usually call this method directly, instead use setCollision, setCollisionBetween or setCollisionByExclusion.
  75712. *
  75713. * @method Phaser.Tilemap#setCollisionByIndex
  75714. * @protected
  75715. * @param {number} index - The index of the tile on the layer.
  75716. * @param {boolean} [collides=true] - If true it will enable collision on the tile. If false it will clear collision values from the tile.
  75717. * @param {number} [layer] - The layer to operate on. If not given will default to this.currentLayer.
  75718. * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update.
  75719. */
  75720. setCollisionByIndex: function (index, collides, layer, recalculate) {
  75721. if (collides === undefined) { collides = true; }
  75722. if (layer === undefined) { layer = this.currentLayer; }
  75723. if (recalculate === undefined) { recalculate = true; }
  75724. if (collides)
  75725. {
  75726. this.collideIndexes.push(index);
  75727. }
  75728. else
  75729. {
  75730. var i = this.collideIndexes.indexOf(index);
  75731. if (i > -1)
  75732. {
  75733. this.collideIndexes.splice(i, 1);
  75734. }
  75735. }
  75736. for (var y = 0; y < this.layers[layer].height; y++)
  75737. {
  75738. for (var x = 0; x < this.layers[layer].width; x++)
  75739. {
  75740. var tile = this.layers[layer].data[y][x];
  75741. if (tile && tile.index === index)
  75742. {
  75743. if (collides)
  75744. {
  75745. tile.setCollision(true, true, true, true);
  75746. }
  75747. else
  75748. {
  75749. tile.resetCollision();
  75750. }
  75751. tile.faceTop = collides;
  75752. tile.faceBottom = collides;
  75753. tile.faceLeft = collides;
  75754. tile.faceRight = collides;
  75755. }
  75756. }
  75757. }
  75758. if (recalculate)
  75759. {
  75760. // Now re-calculate interesting faces
  75761. this.calculateFaces(layer);
  75762. }
  75763. return layer;
  75764. },
  75765. /**
  75766. * Gets the TilemapLayer index as used in the setCollision calls.
  75767. *
  75768. * @method Phaser.Tilemap#getLayer
  75769. * @protected
  75770. * @param {number|string|Phaser.TilemapLayer} layer - The layer to operate on. If not given will default to this.currentLayer.
  75771. * @return {number} The TilemapLayer index.
  75772. */
  75773. getLayer: function (layer) {
  75774. if (layer === undefined)
  75775. {
  75776. layer = this.currentLayer;
  75777. }
  75778. else if (typeof layer === 'string')
  75779. {
  75780. layer = this.getLayerIndex(layer);
  75781. }
  75782. else if (layer instanceof Phaser.TilemapLayer)
  75783. {
  75784. layer = layer.index;
  75785. }
  75786. return layer;
  75787. },
  75788. /**
  75789. * Turn off/on the recalculation of faces for tile or collision updates.
  75790. * `setPreventRecalculate(true)` puts recalculation on hold while `setPreventRecalculate(false)` recalculates all the changed layers.
  75791. *
  75792. * @method Phaser.Tilemap#setPreventRecalculate
  75793. * @param {boolean} value - If true it will put the recalculation on hold.
  75794. */
  75795. setPreventRecalculate: function (value) {
  75796. if (value === true && this.preventingRecalculate !== true)
  75797. {
  75798. this.preventingRecalculate = true;
  75799. this.needToRecalculate = {};
  75800. }
  75801. if (value === false && this.preventingRecalculate === true)
  75802. {
  75803. this.preventingRecalculate = false;
  75804. for (var i in this.needToRecalculate)
  75805. {
  75806. this.calculateFaces(i);
  75807. }
  75808. this.needToRecalculate = false;
  75809. }
  75810. },
  75811. /**
  75812. * Internal function.
  75813. *
  75814. * @method Phaser.Tilemap#calculateFaces
  75815. * @protected
  75816. * @param {number} layer - The index of the TilemapLayer to operate on.
  75817. */
  75818. calculateFaces: function (layer) {
  75819. if (this.preventingRecalculate)
  75820. {
  75821. this.needToRecalculate[layer] = true;
  75822. return;
  75823. }
  75824. var above = null;
  75825. var below = null;
  75826. var left = null;
  75827. var right = null;
  75828. for (var y = 0, h = this.layers[layer].height; y < h; y++)
  75829. {
  75830. for (var x = 0, w = this.layers[layer].width; x < w; x++)
  75831. {
  75832. var tile = this.layers[layer].data[y][x];
  75833. if (tile)
  75834. {
  75835. above = this.getTileAbove(layer, x, y);
  75836. below = this.getTileBelow(layer, x, y);
  75837. left = this.getTileLeft(layer, x, y);
  75838. right = this.getTileRight(layer, x, y);
  75839. if (tile.collides)
  75840. {
  75841. tile.faceTop = true;
  75842. tile.faceBottom = true;
  75843. tile.faceLeft = true;
  75844. tile.faceRight = true;
  75845. }
  75846. if (above && above.collides)
  75847. {
  75848. // There is a tile above this one that also collides, so the top of this tile is no longer interesting
  75849. tile.faceTop = false;
  75850. }
  75851. if (below && below.collides)
  75852. {
  75853. // There is a tile below this one that also collides, so the bottom of this tile is no longer interesting
  75854. tile.faceBottom = false;
  75855. }
  75856. if (left && left.collides)
  75857. {
  75858. // There is a tile left this one that also collides, so the left of this tile is no longer interesting
  75859. tile.faceLeft = false;
  75860. }
  75861. if (right && right.collides)
  75862. {
  75863. // There is a tile right this one that also collides, so the right of this tile is no longer interesting
  75864. tile.faceRight = false;
  75865. }
  75866. }
  75867. }
  75868. }
  75869. },
  75870. /**
  75871. * Gets the tile above the tile coordinates given.
  75872. * Mostly used as an internal function by calculateFaces.
  75873. *
  75874. * @method Phaser.Tilemap#getTileAbove
  75875. * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer().
  75876. * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels.
  75877. * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels.
  75878. */
  75879. getTileAbove: function (layer, x, y) {
  75880. if (y > 0)
  75881. {
  75882. return this.layers[layer].data[y - 1][x];
  75883. }
  75884. return null;
  75885. },
  75886. /**
  75887. * Gets the tile below the tile coordinates given.
  75888. * Mostly used as an internal function by calculateFaces.
  75889. *
  75890. * @method Phaser.Tilemap#getTileBelow
  75891. * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer().
  75892. * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels.
  75893. * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels.
  75894. */
  75895. getTileBelow: function (layer, x, y) {
  75896. if (y < this.layers[layer].height - 1)
  75897. {
  75898. return this.layers[layer].data[y + 1][x];
  75899. }
  75900. return null;
  75901. },
  75902. /**
  75903. * Gets the tile to the left of the tile coordinates given.
  75904. * Mostly used as an internal function by calculateFaces.
  75905. *
  75906. * @method Phaser.Tilemap#getTileLeft
  75907. * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer().
  75908. * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels.
  75909. * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels.
  75910. */
  75911. getTileLeft: function (layer, x, y) {
  75912. if (x > 0)
  75913. {
  75914. return this.layers[layer].data[y][x - 1];
  75915. }
  75916. return null;
  75917. },
  75918. /**
  75919. * Gets the tile to the right of the tile coordinates given.
  75920. * Mostly used as an internal function by calculateFaces.
  75921. *
  75922. * @method Phaser.Tilemap#getTileRight
  75923. * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer().
  75924. * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels.
  75925. * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels.
  75926. */
  75927. getTileRight: function (layer, x, y) {
  75928. if (x < this.layers[layer].width - 1)
  75929. {
  75930. return this.layers[layer].data[y][x + 1];
  75931. }
  75932. return null;
  75933. },
  75934. /**
  75935. * Sets the current layer to the given index.
  75936. *
  75937. * @method Phaser.Tilemap#setLayer
  75938. * @param {number|string|Phaser.TilemapLayer} layer - The layer to set as current.
  75939. */
  75940. setLayer: function (layer) {
  75941. layer = this.getLayer(layer);
  75942. if (this.layers[layer])
  75943. {
  75944. this.currentLayer = layer;
  75945. }
  75946. },
  75947. /**
  75948. * Checks if there is a tile at the given location.
  75949. *
  75950. * @method Phaser.Tilemap#hasTile
  75951. * @param {number} x - X position to check if a tile exists at (given in tile units, not pixels)
  75952. * @param {number} y - Y position to check if a tile exists at (given in tile units, not pixels)
  75953. * @param {number|string|Phaser.TilemapLayer} layer - The layer to set as current.
  75954. * @return {boolean} True if there is a tile at the given location, otherwise false.
  75955. */
  75956. hasTile: function (x, y, layer) {
  75957. layer = this.getLayer(layer);
  75958. if (this.layers[layer].data[y] === undefined || this.layers[layer].data[y][x] === undefined) {
  75959. return false;
  75960. }
  75961. return (this.layers[layer].data[y][x].index > -1);
  75962. },
  75963. /**
  75964. * Removes the tile located at the given coordinates and updates the collision data.
  75965. *
  75966. * @method Phaser.Tilemap#removeTile
  75967. * @param {number} x - X position to place the tile (given in tile units, not pixels)
  75968. * @param {number} y - Y position to place the tile (given in tile units, not pixels)
  75969. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify.
  75970. * @return {Phaser.Tile} The Tile object that was removed from this map.
  75971. */
  75972. removeTile: function (x, y, layer) {
  75973. layer = this.getLayer(layer);
  75974. if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height)
  75975. {
  75976. if (this.hasTile(x, y, layer))
  75977. {
  75978. var tile = this.layers[layer].data[y][x];
  75979. this.layers[layer].data[y][x] = new Phaser.Tile(this.layers[layer], -1, x, y, this.tileWidth, this.tileHeight);
  75980. this.layers[layer].dirty = true;
  75981. this.calculateFaces(layer);
  75982. return tile;
  75983. }
  75984. }
  75985. },
  75986. /**
  75987. * Removes the tile located at the given coordinates and updates the collision data. The coordinates are given in pixel values.
  75988. *
  75989. * @method Phaser.Tilemap#removeTileWorldXY
  75990. * @param {number} x - X position to insert the tile (given in pixels)
  75991. * @param {number} y - Y position to insert the tile (given in pixels)
  75992. * @param {number} tileWidth - The width of the tile in pixels.
  75993. * @param {number} tileHeight - The height of the tile in pixels.
  75994. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify.
  75995. * @return {Phaser.Tile} The Tile object that was removed from this map.
  75996. */
  75997. removeTileWorldXY: function (x, y, tileWidth, tileHeight, layer) {
  75998. layer = this.getLayer(layer);
  75999. x = this.game.math.snapToFloor(x, tileWidth) / tileWidth;
  76000. y = this.game.math.snapToFloor(y, tileHeight) / tileHeight;
  76001. return this.removeTile(x, y, layer);
  76002. },
  76003. /**
  76004. * Puts a tile of the given index value at the coordinate specified.
  76005. * If you pass `null` as the tile it will pass your call over to Tilemap.removeTile instead.
  76006. *
  76007. * @method Phaser.Tilemap#putTile
  76008. * @param {Phaser.Tile|number|null} tile - The index of this tile to set or a Phaser.Tile object. If null the tile is removed from the map.
  76009. * @param {number} x - X position to place the tile (given in tile units, not pixels)
  76010. * @param {number} y - Y position to place the tile (given in tile units, not pixels)
  76011. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify.
  76012. * @return {Phaser.Tile} The Tile object that was created or added to this map.
  76013. */
  76014. putTile: function (tile, x, y, layer) {
  76015. if (tile === null)
  76016. {
  76017. return this.removeTile(x, y, layer);
  76018. }
  76019. layer = this.getLayer(layer);
  76020. if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height)
  76021. {
  76022. var index;
  76023. if (tile instanceof Phaser.Tile)
  76024. {
  76025. index = tile.index;
  76026. if (this.hasTile(x, y, layer))
  76027. {
  76028. this.layers[layer].data[y][x].copy(tile);
  76029. }
  76030. else
  76031. {
  76032. this.layers[layer].data[y][x] = new Phaser.Tile(layer, index, x, y, tile.width, tile.height);
  76033. }
  76034. }
  76035. else
  76036. {
  76037. index = tile;
  76038. if (this.hasTile(x, y, layer))
  76039. {
  76040. this.layers[layer].data[y][x].index = index;
  76041. }
  76042. else
  76043. {
  76044. this.layers[layer].data[y][x] = new Phaser.Tile(this.layers[layer], index, x, y, this.tileWidth, this.tileHeight);
  76045. }
  76046. }
  76047. if (this.collideIndexes.indexOf(index) > -1)
  76048. {
  76049. this.layers[layer].data[y][x].setCollision(true, true, true, true);
  76050. }
  76051. else
  76052. {
  76053. this.layers[layer].data[y][x].resetCollision();
  76054. }
  76055. this.layers[layer].dirty = true;
  76056. this.calculateFaces(layer);
  76057. return this.layers[layer].data[y][x];
  76058. }
  76059. return null;
  76060. },
  76061. /**
  76062. * Puts a tile into the Tilemap layer. The coordinates are given in pixel values.
  76063. *
  76064. * @method Phaser.Tilemap#putTileWorldXY
  76065. * @param {Phaser.Tile|number} tile - The index of this tile to set or a Phaser.Tile object.
  76066. * @param {number} x - X position to insert the tile (given in pixels)
  76067. * @param {number} y - Y position to insert the tile (given in pixels)
  76068. * @param {number} tileWidth - The width of the tile in pixels.
  76069. * @param {number} tileHeight - The height of the tile in pixels.
  76070. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify.
  76071. * @return {Phaser.Tile} The Tile object that was created or added to this map.
  76072. */
  76073. putTileWorldXY: function (tile, x, y, tileWidth, tileHeight, layer) {
  76074. layer = this.getLayer(layer);
  76075. x = this.game.math.snapToFloor(x, tileWidth) / tileWidth;
  76076. y = this.game.math.snapToFloor(y, tileHeight) / tileHeight;
  76077. return this.putTile(tile, x, y, layer);
  76078. },
  76079. /**
  76080. * Searches the entire map layer for the first tile matching the given index, then returns that Phaser.Tile object.
  76081. * If no match is found it returns null.
  76082. * The search starts from the top-left tile and continues horizontally until it hits the end of the row, then it drops down to the next column.
  76083. * If the reverse boolean is true, it scans starting from the bottom-right corner traveling up to the top-left.
  76084. *
  76085. * @method Phaser.Tilemap#searchTileIndex
  76086. * @param {number} index - The tile index value to search for.
  76087. * @param {number} [skip=0] - The number of times to skip a matching tile before returning.
  76088. * @param {number} [reverse=false] - If true it will scan the layer in reverse, starting at the bottom-right. Otherwise it scans from the top-left.
  76089. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to get the tile from.
  76090. * @return {Phaser.Tile} The first (or n skipped) tile with the matching index.
  76091. */
  76092. searchTileIndex: function (index, skip, reverse, layer) {
  76093. if (skip === undefined) { skip = 0; }
  76094. if (reverse === undefined) { reverse = false; }
  76095. layer = this.getLayer(layer);
  76096. var c = 0;
  76097. if (reverse)
  76098. {
  76099. for (var y = this.layers[layer].height - 1; y >= 0; y--)
  76100. {
  76101. for (var x = this.layers[layer].width - 1; x >= 0; x--)
  76102. {
  76103. if (this.layers[layer].data[y][x].index === index)
  76104. {
  76105. if (c === skip)
  76106. {
  76107. return this.layers[layer].data[y][x];
  76108. }
  76109. else
  76110. {
  76111. c++;
  76112. }
  76113. }
  76114. }
  76115. }
  76116. }
  76117. else
  76118. {
  76119. for (var y = 0; y < this.layers[layer].height; y++)
  76120. {
  76121. for (var x = 0; x < this.layers[layer].width; x++)
  76122. {
  76123. if (this.layers[layer].data[y][x].index === index)
  76124. {
  76125. if (c === skip)
  76126. {
  76127. return this.layers[layer].data[y][x];
  76128. }
  76129. else
  76130. {
  76131. c++;
  76132. }
  76133. }
  76134. }
  76135. }
  76136. }
  76137. return null;
  76138. },
  76139. /**
  76140. * Gets a tile from the Tilemap Layer. The coordinates are given in tile values.
  76141. *
  76142. * @method Phaser.Tilemap#getTile
  76143. * @param {number} x - X position to get the tile from (given in tile units, not pixels)
  76144. * @param {number} y - Y position to get the tile from (given in tile units, not pixels)
  76145. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to get the tile from.
  76146. * @param {boolean} [nonNull=false] - If true getTile won't return null for empty tiles, but a Tile object with an index of -1.
  76147. * @return {Phaser.Tile} The tile at the given coordinates or null if no tile was found or the coordinates were invalid.
  76148. */
  76149. getTile: function (x, y, layer, nonNull) {
  76150. if (nonNull === undefined) { nonNull = false; }
  76151. layer = this.getLayer(layer);
  76152. if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height)
  76153. {
  76154. if (this.layers[layer].data[y][x].index === -1)
  76155. {
  76156. if (nonNull)
  76157. {
  76158. return this.layers[layer].data[y][x];
  76159. }
  76160. else
  76161. {
  76162. return null;
  76163. }
  76164. }
  76165. else
  76166. {
  76167. return this.layers[layer].data[y][x];
  76168. }
  76169. }
  76170. else
  76171. {
  76172. return null;
  76173. }
  76174. },
  76175. /**
  76176. * Gets a tile from the Tilemap layer. The coordinates are given in pixel values.
  76177. *
  76178. * @method Phaser.Tilemap#getTileWorldXY
  76179. * @param {number} x - X position to get the tile from (given in pixels)
  76180. * @param {number} y - Y position to get the tile from (given in pixels)
  76181. * @param {number} [tileWidth] - The width of the tiles. If not given the map default is used.
  76182. * @param {number} [tileHeight] - The height of the tiles. If not given the map default is used.
  76183. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to get the tile from.
  76184. * @param {boolean} [nonNull=false] - If true getTile won't return null for empty tiles, but a Tile object with an index of -1.
  76185. * @return {Phaser.Tile} The tile at the given coordinates.
  76186. */
  76187. getTileWorldXY: function (x, y, tileWidth, tileHeight, layer, nonNull) {
  76188. if (tileWidth === undefined) { tileWidth = this.tileWidth; }
  76189. if (tileHeight === undefined) { tileHeight = this.tileHeight; }
  76190. layer = this.getLayer(layer);
  76191. x = this.game.math.snapToFloor(x, tileWidth) / tileWidth;
  76192. y = this.game.math.snapToFloor(y, tileHeight) / tileHeight;
  76193. return this.getTile(x, y, layer, nonNull);
  76194. },
  76195. /**
  76196. * Copies all of the tiles in the given rectangular block into the tilemap data buffer.
  76197. *
  76198. * @method Phaser.Tilemap#copy
  76199. * @param {integer} x - X position of the top left of the area to copy (given in tiles, not pixels)
  76200. * @param {integer} y - Y position of the top left of the area to copy (given in tiles, not pixels)
  76201. * @param {integer} width - The width of the area to copy (given in tiles, not pixels)
  76202. * @param {integer} height - The height of the area to copy (given in tiles, not pixels)
  76203. * @param {integer|string|Phaser.TilemapLayer} [layer] - The layer to copy the tiles from.
  76204. * @return {array} An array of the tiles that were copied.
  76205. */
  76206. copy: function (x, y, width, height, layer) {
  76207. layer = this.getLayer(layer);
  76208. if (!this.layers[layer])
  76209. {
  76210. this._results.length = 0;
  76211. return;
  76212. }
  76213. if (x === undefined) { x = 0; }
  76214. if (y === undefined) { y = 0; }
  76215. if (width === undefined) { width = this.layers[layer].width; }
  76216. if (height === undefined) { height = this.layers[layer].height; }
  76217. if (x < 0)
  76218. {
  76219. x = 0;
  76220. }
  76221. if (y < 0)
  76222. {
  76223. y = 0;
  76224. }
  76225. if (width > this.layers[layer].width)
  76226. {
  76227. width = this.layers[layer].width;
  76228. }
  76229. if (height > this.layers[layer].height)
  76230. {
  76231. height = this.layers[layer].height;
  76232. }
  76233. this._results.length = 0;
  76234. this._results.push({ x: x, y: y, width: width, height: height, layer: layer });
  76235. for (var ty = y; ty < y + height; ty++)
  76236. {
  76237. for (var tx = x; tx < x + width; tx++)
  76238. {
  76239. this._results.push(this.layers[layer].data[ty][tx]);
  76240. }
  76241. }
  76242. return this._results;
  76243. },
  76244. /**
  76245. * Pastes a previously copied block of tile data into the given x/y coordinates. Data should have been prepared with Tilemap.copy.
  76246. *
  76247. * @method Phaser.Tilemap#paste
  76248. * @param {number} x - X position of the top left of the area to paste to (given in tiles, not pixels)
  76249. * @param {number} y - Y position of the top left of the area to paste to (given in tiles, not pixels)
  76250. * @param {array} tileblock - The block of tiles to paste.
  76251. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to paste the tiles into.
  76252. */
  76253. paste: function (x, y, tileblock, layer) {
  76254. if (x === undefined) { x = 0; }
  76255. if (y === undefined) { y = 0; }
  76256. layer = this.getLayer(layer);
  76257. if (!tileblock || tileblock.length < 2)
  76258. {
  76259. return;
  76260. }
  76261. // 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
  76262. var diffX = x - tileblock[1].x;
  76263. var diffY = y - tileblock[1].y;
  76264. for (var i = 1; i < tileblock.length; i++)
  76265. {
  76266. this.layers[layer].data[ diffY + tileblock[i].y ][ diffX + tileblock[i].x ].copy(tileblock[i]);
  76267. }
  76268. this.layers[layer].dirty = true;
  76269. this.calculateFaces(layer);
  76270. },
  76271. /**
  76272. * Scans the given area for tiles with an index matching tileA and swaps them with tileB.
  76273. *
  76274. * @method Phaser.Tilemap#swap
  76275. * @param {number} tileA - First tile index.
  76276. * @param {number} tileB - Second tile index.
  76277. * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels.
  76278. * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels.
  76279. * @param {number} width - The width in tiles of the area to operate on.
  76280. * @param {number} height - The height in tiles of the area to operate on.
  76281. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on.
  76282. */
  76283. swap: function (tileA, tileB, x, y, width, height, layer) {
  76284. layer = this.getLayer(layer);
  76285. this.copy(x, y, width, height, layer);
  76286. if (this._results.length < 2)
  76287. {
  76288. return;
  76289. }
  76290. this._tempA = tileA;
  76291. this._tempB = tileB;
  76292. this._results.forEach(this.swapHandler, this);
  76293. this.paste(x, y, this._results, layer);
  76294. },
  76295. /**
  76296. * Internal function that handles the swapping of tiles.
  76297. *
  76298. * @method Phaser.Tilemap#swapHandler
  76299. * @private
  76300. * @param {number} value
  76301. */
  76302. swapHandler: function (value) {
  76303. if (value.index === this._tempA)
  76304. {
  76305. // Swap A with B
  76306. value.index = this._tempB;
  76307. }
  76308. else if (value.index === this._tempB)
  76309. {
  76310. // Swap B with A
  76311. value.index = this._tempA;
  76312. }
  76313. },
  76314. /**
  76315. * For each tile in the given area defined by x/y and width/height run the given callback.
  76316. *
  76317. * @method Phaser.Tilemap#forEach
  76318. * @param {number} callback - The callback. Each tile in the given area will be passed to this callback as the first and only parameter.
  76319. * @param {number} context - The context under which the callback should be run.
  76320. * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels.
  76321. * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels.
  76322. * @param {number} width - The width in tiles of the area to operate on.
  76323. * @param {number} height - The height in tiles of the area to operate on.
  76324. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on.
  76325. */
  76326. forEach: function (callback, context, x, y, width, height, layer) {
  76327. layer = this.getLayer(layer);
  76328. this.copy(x, y, width, height, layer);
  76329. if (this._results.length < 2)
  76330. {
  76331. return;
  76332. }
  76333. this._results.forEach(callback, context);
  76334. this.paste(x, y, this._results, layer);
  76335. },
  76336. /**
  76337. * Scans the given area for tiles with an index matching `source` and updates their index to match `dest`.
  76338. *
  76339. * @method Phaser.Tilemap#replace
  76340. * @param {number} source - The tile index value to scan for.
  76341. * @param {number} dest - The tile index value to replace found tiles with.
  76342. * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels.
  76343. * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels.
  76344. * @param {number} width - The width in tiles of the area to operate on.
  76345. * @param {number} height - The height in tiles of the area to operate on.
  76346. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on.
  76347. */
  76348. replace: function (source, dest, x, y, width, height, layer) {
  76349. layer = this.getLayer(layer);
  76350. this.copy(x, y, width, height, layer);
  76351. if (this._results.length < 2)
  76352. {
  76353. return;
  76354. }
  76355. for (var i = 1; i < this._results.length; i++)
  76356. {
  76357. if (this._results[i].index === source)
  76358. {
  76359. this._results[i].index = dest;
  76360. }
  76361. }
  76362. this.paste(x, y, this._results, layer);
  76363. },
  76364. /**
  76365. * Randomises a set of tiles in a given area.
  76366. *
  76367. * @method Phaser.Tilemap#random
  76368. * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels.
  76369. * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels.
  76370. * @param {number} width - The width in tiles of the area to operate on.
  76371. * @param {number} height - The height in tiles of the area to operate on.
  76372. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on.
  76373. */
  76374. random: function (x, y, width, height, layer) {
  76375. layer = this.getLayer(layer);
  76376. this.copy(x, y, width, height, layer);
  76377. if (this._results.length < 2)
  76378. {
  76379. return;
  76380. }
  76381. var indexes = [];
  76382. for (var t = 1; t < this._results.length; t++)
  76383. {
  76384. if (this._results[t].index)
  76385. {
  76386. var idx = this._results[t].index;
  76387. if (indexes.indexOf(idx) === -1)
  76388. {
  76389. indexes.push(idx);
  76390. }
  76391. }
  76392. }
  76393. for (var i = 1; i < this._results.length; i++)
  76394. {
  76395. this._results[i].index = this.game.rnd.pick(indexes);
  76396. }
  76397. this.paste(x, y, this._results, layer);
  76398. },
  76399. /**
  76400. * 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!
  76401. *
  76402. * @method Phaser.Tilemap#shuffle
  76403. * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels.
  76404. * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels.
  76405. * @param {number} width - The width in tiles of the area to operate on.
  76406. * @param {number} height - The height in tiles of the area to operate on.
  76407. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on.
  76408. */
  76409. shuffle: function (x, y, width, height, layer) {
  76410. layer = this.getLayer(layer);
  76411. this.copy(x, y, width, height, layer);
  76412. if (this._results.length < 2)
  76413. {
  76414. return;
  76415. }
  76416. var indexes = [];
  76417. for (var t = 1; t < this._results.length; t++)
  76418. {
  76419. if (this._results[t].index)
  76420. {
  76421. indexes.push(this._results[t].index);
  76422. }
  76423. }
  76424. Phaser.ArrayUtils.shuffle(indexes);
  76425. for (var i = 1; i < this._results.length; i++)
  76426. {
  76427. this._results[i].index = indexes[i - 1];
  76428. }
  76429. this.paste(x, y, this._results, layer);
  76430. },
  76431. /**
  76432. * Fills the given area with the specified tile.
  76433. *
  76434. * @method Phaser.Tilemap#fill
  76435. * @param {number} index - The index of the tile that the area will be filled with.
  76436. * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels.
  76437. * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels.
  76438. * @param {number} width - The width in tiles of the area to operate on.
  76439. * @param {number} height - The height in tiles of the area to operate on.
  76440. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on.
  76441. */
  76442. fill: function (index, x, y, width, height, layer) {
  76443. layer = this.getLayer(layer);
  76444. this.copy(x, y, width, height, layer);
  76445. if (this._results.length < 2)
  76446. {
  76447. return;
  76448. }
  76449. for (var i = 1; i < this._results.length; i++)
  76450. {
  76451. this._results[i].index = index;
  76452. }
  76453. this.paste(x, y, this._results, layer);
  76454. },
  76455. /**
  76456. * Removes all layers from this tile map.
  76457. *
  76458. * @method Phaser.Tilemap#removeAllLayers
  76459. */
  76460. removeAllLayers: function () {
  76461. this.layers.length = 0;
  76462. this.currentLayer = 0;
  76463. },
  76464. /**
  76465. * Dumps the tilemap data out to the console.
  76466. *
  76467. * @method Phaser.Tilemap#dump
  76468. */
  76469. dump: function () {
  76470. var txt = '';
  76471. var args = [''];
  76472. for (var y = 0; y < this.layers[this.currentLayer].height; y++)
  76473. {
  76474. for (var x = 0; x < this.layers[this.currentLayer].width; x++)
  76475. {
  76476. txt += "%c ";
  76477. if (this.layers[this.currentLayer].data[y][x] > 1)
  76478. {
  76479. if (this.debugMap[this.layers[this.currentLayer].data[y][x]])
  76480. {
  76481. args.push("background: " + this.debugMap[this.layers[this.currentLayer].data[y][x]]);
  76482. }
  76483. else
  76484. {
  76485. args.push("background: #ffffff");
  76486. }
  76487. }
  76488. else
  76489. {
  76490. args.push("background: rgb(0, 0, 0)");
  76491. }
  76492. }
  76493. txt += "\n";
  76494. }
  76495. args[0] = txt;
  76496. console.log.apply(console, args);
  76497. },
  76498. /**
  76499. * Removes all layer data from this tile map and nulls the game reference.
  76500. * Note: You are responsible for destroying any TilemapLayer objects you generated yourself, as Tilemap doesn't keep a reference to them.
  76501. *
  76502. * @method Phaser.Tilemap#destroy
  76503. */
  76504. destroy: function () {
  76505. this.removeAllLayers();
  76506. this.data = [];
  76507. this.game = null;
  76508. }
  76509. };
  76510. Phaser.Tilemap.prototype.constructor = Phaser.Tilemap;
  76511. /**
  76512. * @name Phaser.Tilemap#layer
  76513. * @property {number|string|Phaser.TilemapLayer} layer - The current layer object.
  76514. */
  76515. Object.defineProperty(Phaser.Tilemap.prototype, "layer", {
  76516. get: function () {
  76517. return this.layers[this.currentLayer];
  76518. },
  76519. set: function (value) {
  76520. if (value !== this.currentLayer)
  76521. {
  76522. this.setLayer(value);
  76523. }
  76524. }
  76525. });
  76526. /**
  76527. * @author Richard Davey <rich@photonstorm.com>
  76528. * @copyright 2016 Photon Storm Ltd.
  76529. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  76530. */
  76531. /**
  76532. * A TilemapLayer is a Phaser.Image/Sprite that renders a specific TileLayer of a Tilemap.
  76533. *
  76534. * Since a TilemapLayer is a Sprite it can be moved around the display, added to other groups or display objects, etc.
  76535. *
  76536. * By default TilemapLayers have fixedToCamera set to `true`. Changing this will break Camera follow and scrolling behavior.
  76537. *
  76538. * @class Phaser.TilemapLayer
  76539. * @extends Phaser.Sprite
  76540. * @constructor
  76541. * @param {Phaser.Game} game - Game reference to the currently running game.
  76542. * @param {Phaser.Tilemap} tilemap - The tilemap to which this layer belongs.
  76543. * @param {integer} index - The index of the TileLayer to render within the Tilemap.
  76544. * @param {integer} width - Width of the renderable area of the layer (in pixels).
  76545. * @param {integer} height - Height of the renderable area of the layer (in pixels).
  76546. */
  76547. Phaser.TilemapLayer = function (game, tilemap, index, width, height) {
  76548. width |= 0;
  76549. height |= 0;
  76550. Phaser.Sprite.call(this, game, 0, 0);
  76551. /**
  76552. * The Tilemap to which this layer is bound.
  76553. * @property {Phaser.Tilemap} map
  76554. * @protected
  76555. * @readonly
  76556. */
  76557. this.map = tilemap;
  76558. /**
  76559. * The index of this layer within the Tilemap.
  76560. * @property {number} index
  76561. * @protected
  76562. * @readonly
  76563. */
  76564. this.index = index;
  76565. /**
  76566. * The layer object within the Tilemap that this layer represents.
  76567. * @property {object} layer
  76568. * @protected
  76569. * @readonly
  76570. */
  76571. this.layer = tilemap.layers[index];
  76572. /**
  76573. * The canvas to which this TilemapLayer draws.
  76574. * @property {HTMLCanvasElement} canvas
  76575. * @protected
  76576. */
  76577. this.canvas = PIXI.CanvasPool.create(this, width, height);
  76578. /**
  76579. * The 2d context of the canvas.
  76580. * @property {CanvasRenderingContext2D} context
  76581. * @private
  76582. */
  76583. this.context = this.canvas.getContext('2d');
  76584. this.setTexture(new PIXI.Texture(new PIXI.BaseTexture(this.canvas)));
  76585. /**
  76586. * The const type of this object.
  76587. * @property {number} type
  76588. * @readonly
  76589. * @protected
  76590. * @default Phaser.TILEMAPLAYER
  76591. */
  76592. this.type = Phaser.TILEMAPLAYER;
  76593. /**
  76594. * @property {number} physicsType - The const physics body type of this object.
  76595. * @readonly
  76596. */
  76597. this.physicsType = Phaser.TILEMAPLAYER;
  76598. /**
  76599. * Settings that control standard (non-diagnostic) rendering.
  76600. *
  76601. * @property {boolean} [enableScrollDelta=true] - Delta scroll rendering only draws tiles/edges as they come into view.
  76602. * This can greatly improve scrolling rendering performance, especially when there are many small tiles.
  76603. * It should only be disabled in rare cases.
  76604. *
  76605. * @property {?DOMCanvasElement} [copyCanvas=(auto)] - [Internal] If set, force using a separate (shared) copy canvas.
  76606. * Using a canvas bitblt/copy when the source and destinations region overlap produces unexpected behavior
  76607. * in some browsers, notably Safari.
  76608. *
  76609. * @default
  76610. */
  76611. this.renderSettings = {
  76612. enableScrollDelta: false,
  76613. overdrawRatio: 0.20,
  76614. copyCanvas: null
  76615. };
  76616. /**
  76617. * Enable an additional "debug rendering" pass to display collision information.
  76618. *
  76619. * @property {boolean} debug
  76620. * @default
  76621. */
  76622. this.debug = false;
  76623. /**
  76624. * @property {boolean} exists - Controls if the core game loop and physics update this game object or not.
  76625. */
  76626. this.exists = true;
  76627. /**
  76628. * Settings used for debugging and diagnostics.
  76629. *
  76630. * @property {?string} missingImageFill - A tile is rendered as a rectangle using the following fill if a valid tileset/image cannot be found. A value of `null` prevents additional rendering for tiles without a valid tileset image. _This takes effect even when debug rendering for the layer is not enabled._
  76631. *
  76632. * @property {?string} debuggedTileOverfill - If a Tile has `Tile#debug` true then, after normal tile image rendering, a rectangle with the following fill is drawn above/over it. _This takes effect even when debug rendering for the layer is not enabled._
  76633. *
  76634. * @property {boolean} forceFullRedraw - When debug rendering (`debug` is true), and this option is enabled, the a full redraw is forced and rendering optimization is suppressed.
  76635. *
  76636. * @property {number} debugAlpha - When debug rendering (`debug` is true), the tileset is initially rendered with this alpha level. This can make the tile edges clearer.
  76637. *
  76638. * @property {?string} facingEdgeStroke - When debug rendering (`debug` is true), this color/stroke is used to draw "face" edges. A value of `null` disables coloring facing edges.
  76639. *
  76640. * @property {?string} collidingTileOverfill - When debug rendering (`debug` is true), this fill is used for tiles that are collidable. A value of `null` disables applying the additional overfill.
  76641. *
  76642. */
  76643. this.debugSettings = {
  76644. missingImageFill: 'rgb(255,255,255)',
  76645. debuggedTileOverfill: 'rgba(0,255,0,0.4)',
  76646. forceFullRedraw: true,
  76647. debugAlpha: 0.5,
  76648. facingEdgeStroke: 'rgba(0,255,0,1)',
  76649. collidingTileOverfill: 'rgba(0,255,0,0.2)'
  76650. };
  76651. /**
  76652. * Speed at which this layer scrolls horizontally, relative to the camera (e.g. scrollFactorX of 0.5 scrolls half as quickly as the 'normal' camera-locked layers do).
  76653. * @property {number} scrollFactorX
  76654. * @public
  76655. * @default
  76656. */
  76657. this.scrollFactorX = 1;
  76658. /**
  76659. * Speed at which this layer scrolls vertically, relative to the camera (e.g. scrollFactorY of 0.5 scrolls half as quickly as the 'normal' camera-locked layers do)
  76660. * @property {number} scrollFactorY
  76661. * @public
  76662. * @default
  76663. */
  76664. this.scrollFactorY = 1;
  76665. /**
  76666. * If true tiles will be force rendered, even if such is not believed to be required.
  76667. * @property {boolean} dirty
  76668. * @protected
  76669. */
  76670. this.dirty = true;
  76671. /**
  76672. * When ray-casting against tiles this is the number of steps it will jump. For larger tile sizes you can increase this to improve performance.
  76673. * @property {integer} rayStepRate
  76674. * @default
  76675. */
  76676. this.rayStepRate = 4;
  76677. /**
  76678. * Flag controlling if the layer tiles wrap at the edges.
  76679. * @property {boolean} _wrap
  76680. * @private
  76681. */
  76682. this._wrap = false;
  76683. /**
  76684. * Local map data and calculation cache.
  76685. * @property {object} _mc
  76686. * @private
  76687. */
  76688. this._mc = {
  76689. // Used to bypass rendering without reliance on `dirty` and detect changes.
  76690. scrollX: 0,
  76691. scrollY: 0,
  76692. renderWidth: 0,
  76693. renderHeight: 0,
  76694. tileWidth: tilemap.tileWidth,
  76695. tileHeight: tilemap.tileHeight,
  76696. // Collision width/height (pixels)
  76697. // What purpose do these have? Most things use tile width/height directly.
  76698. // This also only extends collisions right and down.
  76699. cw: tilemap.tileWidth,
  76700. ch: tilemap.tileHeight,
  76701. // Cached tilesets from index -> Tileset
  76702. tilesets: []
  76703. };
  76704. /**
  76705. * The current canvas left after scroll is applied.
  76706. * @property {number} _scrollX
  76707. * @private
  76708. */
  76709. this._scrollX = 0;
  76710. /**
  76711. * The current canvas top after scroll is applied.
  76712. * @propety {number} _scrollY
  76713. * @private
  76714. */
  76715. this._scrollY = 0;
  76716. /**
  76717. * Used for caching the tiles / array of tiles.
  76718. * @property {Phaser.Tile[]} _results
  76719. * @private
  76720. */
  76721. this._results = [];
  76722. if (!game.device.canvasBitBltShift)
  76723. {
  76724. this.renderSettings.copyCanvas = Phaser.TilemapLayer.ensureSharedCopyCanvas();
  76725. }
  76726. this.fixedToCamera = true;
  76727. };
  76728. Phaser.TilemapLayer.prototype = Object.create(Phaser.Sprite.prototype);
  76729. Phaser.TilemapLayer.prototype.constructor = Phaser.TilemapLayer;
  76730. Phaser.TilemapLayer.prototype.preUpdateCore = Phaser.Component.Core.preUpdate;
  76731. /**
  76732. * The shared double-copy canvas, created as needed.
  76733. *
  76734. * @private
  76735. * @static
  76736. */
  76737. Phaser.TilemapLayer.sharedCopyCanvas = null;
  76738. /**
  76739. * Create if needed (and return) a shared copy canvas that is shared across all TilemapLayers.
  76740. *
  76741. * Code that uses the canvas is responsible to ensure the dimensions and save/restore state as appropriate.
  76742. *
  76743. * @method Phaser.TilemapLayer#ensureSharedCopyCanvas
  76744. * @protected
  76745. * @static
  76746. */
  76747. Phaser.TilemapLayer.ensureSharedCopyCanvas = function () {
  76748. if (!this.sharedCopyCanvas)
  76749. {
  76750. this.sharedCopyCanvas = Phaser.Canvas.create(2, 2);
  76751. }
  76752. return this.sharedCopyCanvas;
  76753. };
  76754. /**
  76755. * Automatically called by World.preUpdate.
  76756. *
  76757. * @method Phaser.TilemapLayer#preUpdate
  76758. */
  76759. Phaser.TilemapLayer.prototype.preUpdate = function() {
  76760. return this.preUpdateCore();
  76761. };
  76762. /**
  76763. * Automatically called by World.postUpdate. Handles cache updates.
  76764. *
  76765. * @method Phaser.TilemapLayer#postUpdate
  76766. * @protected
  76767. */
  76768. Phaser.TilemapLayer.prototype.postUpdate = function () {
  76769. Phaser.Component.FixedToCamera.postUpdate.call(this);
  76770. // Stops you being able to auto-scroll the camera if it's not following a sprite
  76771. var camera = this.game.camera;
  76772. this.scrollX = camera.x * this.scrollFactorX / this.scale.x;
  76773. this.scrollY = camera.y * this.scrollFactorY / this.scale.y;
  76774. this.render();
  76775. };
  76776. /**
  76777. * Destroys this TilemapLayer.
  76778. *
  76779. * @method Phaser.TilemapLayer#destroy
  76780. */
  76781. Phaser.TilemapLayer.prototype.destroy = function() {
  76782. PIXI.CanvasPool.remove(this);
  76783. Phaser.Component.Destroy.prototype.destroy.call(this);
  76784. };
  76785. /**
  76786. * Resizes the internal canvas and texture frame used by this TilemapLayer.
  76787. *
  76788. * This is an expensive call, so don't bind it to a window resize event! But instead call it at carefully
  76789. * selected times.
  76790. *
  76791. * Be aware that no validation of the new sizes takes place and the current map scroll coordinates are not
  76792. * modified either. You will have to handle both of these things from your game code if required.
  76793. *
  76794. * @method Phaser.TilemapLayer#resize
  76795. * @param {number} width - The new width of the TilemapLayer
  76796. * @param {number} height - The new height of the TilemapLayer
  76797. */
  76798. Phaser.TilemapLayer.prototype.resize = function (width, height) {
  76799. this.canvas.width = width;
  76800. this.canvas.height = height;
  76801. this.texture.frame.resize(width, height);
  76802. this.texture.width = width;
  76803. this.texture.height = height;
  76804. this.texture.crop.width = width;
  76805. this.texture.crop.height = height;
  76806. this.texture.baseTexture.width = width;
  76807. this.texture.baseTexture.height = height;
  76808. this.texture.baseTexture.dirty();
  76809. this.texture.requiresUpdate = true;
  76810. this.texture._updateUvs();
  76811. this.dirty = true;
  76812. };
  76813. /**
  76814. * Sets the world size to match the size of this layer.
  76815. *
  76816. * @method Phaser.TilemapLayer#resizeWorld
  76817. * @public
  76818. */
  76819. Phaser.TilemapLayer.prototype.resizeWorld = function () {
  76820. this.game.world.setBounds(0, 0, this.layer.widthInPixels * this.scale.x, this.layer.heightInPixels * this.scale.y);
  76821. };
  76822. /**
  76823. * Take an x coordinate that doesn't account for scrollFactorX and 'fix' it into a scrolled local space.
  76824. *
  76825. * @method Phaser.TilemapLayer#_fixX
  76826. * @private
  76827. * @param {number} x - x coordinate in camera space
  76828. * @return {number} x coordinate in scrollFactor-adjusted dimensions
  76829. */
  76830. Phaser.TilemapLayer.prototype._fixX = function (x) {
  76831. if (x < 0)
  76832. {
  76833. x = 0;
  76834. }
  76835. if (this.scrollFactorX === 1)
  76836. {
  76837. return x;
  76838. }
  76839. return this._scrollX + (x - (this._scrollX / this.scrollFactorX));
  76840. };
  76841. /**
  76842. * Take an x coordinate that _does_ account for scrollFactorX and 'unfix' it back to camera space.
  76843. *
  76844. * @method Phaser.TilemapLayer#_unfixX
  76845. * @private
  76846. * @param {number} x - x coordinate in scrollFactor-adjusted dimensions
  76847. * @return {number} x coordinate in camera space
  76848. */
  76849. Phaser.TilemapLayer.prototype._unfixX = function (x) {
  76850. if (this.scrollFactorX === 1)
  76851. {
  76852. return x;
  76853. }
  76854. return (this._scrollX / this.scrollFactorX) + (x - this._scrollX);
  76855. };
  76856. /**
  76857. * Take a y coordinate that doesn't account for scrollFactorY and 'fix' it into a scrolled local space.
  76858. *
  76859. * @method Phaser.TilemapLayer#_fixY
  76860. * @private
  76861. * @param {number} y - y coordinate in camera space
  76862. * @return {number} y coordinate in scrollFactor-adjusted dimensions
  76863. */
  76864. Phaser.TilemapLayer.prototype._fixY = function (y) {
  76865. if (y < 0)
  76866. {
  76867. y = 0;
  76868. }
  76869. if (this.scrollFactorY === 1)
  76870. {
  76871. return y;
  76872. }
  76873. return this._scrollY + (y - (this._scrollY / this.scrollFactorY));
  76874. };
  76875. /**
  76876. * Take a y coordinate that _does_ account for scrollFactorY and 'unfix' it back to camera space.
  76877. *
  76878. * @method Phaser.TilemapLayer#_unfixY
  76879. * @private
  76880. * @param {number} y - y coordinate in scrollFactor-adjusted dimensions
  76881. * @return {number} y coordinate in camera space
  76882. */
  76883. Phaser.TilemapLayer.prototype._unfixY = function (y) {
  76884. if (this.scrollFactorY === 1)
  76885. {
  76886. return y;
  76887. }
  76888. return (this._scrollY / this.scrollFactorY) + (y - this._scrollY);
  76889. };
  76890. /**
  76891. * Convert a pixel value to a tile coordinate.
  76892. *
  76893. * @method Phaser.TilemapLayer#getTileX
  76894. * @public
  76895. * @param {number} x - X position of the point in target tile (in pixels).
  76896. * @return {integer} The X map location of the tile.
  76897. */
  76898. Phaser.TilemapLayer.prototype.getTileX = function (x) {
  76899. // var tileWidth = this.tileWidth * this.scale.x;
  76900. return Math.floor(this._fixX(x) / this._mc.tileWidth);
  76901. };
  76902. /**
  76903. * Convert a pixel value to a tile coordinate.
  76904. *
  76905. * @method Phaser.TilemapLayer#getTileY
  76906. * @public
  76907. * @param {number} y - Y position of the point in target tile (in pixels).
  76908. * @return {integer} The Y map location of the tile.
  76909. */
  76910. Phaser.TilemapLayer.prototype.getTileY = function (y) {
  76911. // var tileHeight = this.tileHeight * this.scale.y;
  76912. return Math.floor(this._fixY(y) / this._mc.tileHeight);
  76913. };
  76914. /**
  76915. * Convert a pixel coordinate to a tile coordinate.
  76916. *
  76917. * @method Phaser.TilemapLayer#getTileXY
  76918. * @public
  76919. * @param {number} x - X position of the point in target tile (in pixels).
  76920. * @param {number} y - Y position of the point in target tile (in pixels).
  76921. * @param {(Phaser.Point|object)} point - The Point/object to update.
  76922. * @return {(Phaser.Point|object)} A Point/object with its `x` and `y` properties set.
  76923. */
  76924. Phaser.TilemapLayer.prototype.getTileXY = function (x, y, point) {
  76925. point.x = this.getTileX(x);
  76926. point.y = this.getTileY(y);
  76927. return point;
  76928. };
  76929. /**
  76930. * Gets all tiles that intersect with the given line.
  76931. *
  76932. * @method Phaser.TilemapLayer#getRayCastTiles
  76933. * @public
  76934. * @param {Phaser.Line} line - The line used to determine which tiles to return.
  76935. * @param {integer} [stepRate=(rayStepRate)] - How many steps through the ray will we check? Defaults to `rayStepRate`.
  76936. * @param {boolean} [collides=false] - If true, _only_ return tiles that collide on one or more faces.
  76937. * @param {boolean} [interestingFace=false] - If true, _only_ return tiles that have interesting faces.
  76938. * @return {Phaser.Tile[]} An array of Phaser.Tiles.
  76939. */
  76940. Phaser.TilemapLayer.prototype.getRayCastTiles = function (line, stepRate, collides, interestingFace) {
  76941. if (!stepRate) { stepRate = this.rayStepRate; }
  76942. if (collides === undefined) { collides = false; }
  76943. if (interestingFace === undefined) { interestingFace = false; }
  76944. // First get all tiles that touch the bounds of the line
  76945. var tiles = this.getTiles(line.x, line.y, line.width, line.height, collides, interestingFace);
  76946. if (tiles.length === 0)
  76947. {
  76948. return [];
  76949. }
  76950. // Now we only want the tiles that intersect with the points on this line
  76951. var coords = line.coordinatesOnLine(stepRate);
  76952. var results = [];
  76953. for (var i = 0; i < tiles.length; i++)
  76954. {
  76955. for (var t = 0; t < coords.length; t++)
  76956. {
  76957. var tile = tiles[i];
  76958. var coord = coords[t];
  76959. if (tile.containsPoint(coord[0], coord[1]))
  76960. {
  76961. results.push(tile);
  76962. break;
  76963. }
  76964. }
  76965. }
  76966. return results;
  76967. };
  76968. /**
  76969. * Get all tiles that exist within the given area, defined by the top-left corner, width and height. Values given are in pixels, not tiles.
  76970. *
  76971. * @method Phaser.TilemapLayer#getTiles
  76972. * @public
  76973. * @param {number} x - X position of the top left corner (in pixels).
  76974. * @param {number} y - Y position of the top left corner (in pixels).
  76975. * @param {number} width - Width of the area to get (in pixels).
  76976. * @param {number} height - Height of the area to get (in pixels).
  76977. * @param {boolean} [collides=false] - If true, _only_ return tiles that collide on one or more faces.
  76978. * @param {boolean} [interestingFace=false] - If true, _only_ return tiles that have interesting faces.
  76979. * @return {array<Phaser.Tile>} An array of Tiles.
  76980. */
  76981. Phaser.TilemapLayer.prototype.getTiles = function (x, y, width, height, collides, interestingFace) {
  76982. // Should we only get tiles that have at least one of their collision flags set? (true = yes, false = no just get them all)
  76983. if (collides === undefined) { collides = false; }
  76984. if (interestingFace === undefined) { interestingFace = false; }
  76985. var fetchAll = !(collides || interestingFace);
  76986. // Adjust the x,y coordinates for scrollFactor
  76987. x = this._fixX(x);
  76988. y = this._fixY(y);
  76989. // Convert the pixel values into tile coordinates
  76990. var tx = Math.floor(x / (this._mc.cw * this.scale.x));
  76991. var ty = Math.floor(y / (this._mc.ch * this.scale.y));
  76992. // Don't just use ceil(width/cw) to allow account for x/y diff within cell
  76993. var tw = Math.ceil((x + width) / (this._mc.cw * this.scale.x)) - tx;
  76994. var th = Math.ceil((y + height) / (this._mc.ch * this.scale.y)) - ty;
  76995. while (this._results.length)
  76996. {
  76997. this._results.pop();
  76998. }
  76999. for (var wy = ty; wy < ty + th; wy++)
  77000. {
  77001. for (var wx = tx; wx < tx + tw; wx++)
  77002. {
  77003. var row = this.layer.data[wy];
  77004. if (row && row[wx])
  77005. {
  77006. if (fetchAll || row[wx].isInteresting(collides, interestingFace))
  77007. {
  77008. this._results.push(row[wx]);
  77009. }
  77010. }
  77011. }
  77012. }
  77013. return this._results.slice();
  77014. };
  77015. /**
  77016. * Returns the appropriate tileset for the index, updating the internal cache as required.
  77017. * This should only be called if `tilesets[index]` evaluates to undefined.
  77018. *
  77019. * @method Phaser.TilemapLayer#resolveTileset
  77020. * @private
  77021. * @param {integer} Tile index
  77022. * @return {Phaser.Tileset|null} Returns the associated tileset or null if there is no such mapping.
  77023. */
  77024. Phaser.TilemapLayer.prototype.resolveTileset = function (tileIndex) {
  77025. var tilesets = this._mc.tilesets;
  77026. // Try for dense array if reasonable
  77027. if (tileIndex < 2000)
  77028. {
  77029. while (tilesets.length < tileIndex)
  77030. {
  77031. tilesets.push(undefined);
  77032. }
  77033. }
  77034. var setIndex = this.map.tiles[tileIndex] && this.map.tiles[tileIndex][2];
  77035. if (setIndex != null) // number: not null or undefined
  77036. {
  77037. var tileset = this.map.tilesets[setIndex];
  77038. if (tileset && tileset.containsTileIndex(tileIndex))
  77039. {
  77040. return (tilesets[tileIndex] = tileset);
  77041. }
  77042. }
  77043. return (tilesets[tileIndex] = null);
  77044. };
  77045. /**
  77046. * The TilemapLayer caches tileset look-ups.
  77047. *
  77048. * Call this method of clear the cache if tilesets have been added or updated after the layer has been rendered.
  77049. *
  77050. * @method Phaser.TilemapLayer#resetTilesetCache
  77051. * @public
  77052. */
  77053. Phaser.TilemapLayer.prototype.resetTilesetCache = function () {
  77054. var tilesets = this._mc.tilesets;
  77055. while (tilesets.length)
  77056. {
  77057. tilesets.pop();
  77058. }
  77059. };
  77060. /**
  77061. * This method will set the scale of the tilemap as well as update the underlying block data of this layer.
  77062. *
  77063. * @method Phaser.TilemapLayer#setScale
  77064. * @param {number} [xScale=1] - The scale factor along the X-plane
  77065. * @param {number} [yScale] - The scale factor along the Y-plane
  77066. */
  77067. Phaser.TilemapLayer.prototype.setScale = function (xScale, yScale) {
  77068. xScale = xScale || 1;
  77069. yScale = yScale || xScale;
  77070. for (var y = 0; y < this.layer.data.length; y++)
  77071. {
  77072. var row = this.layer.data[y];
  77073. for (var x = 0; x < row.length; x++)
  77074. {
  77075. var tile = row[x];
  77076. tile.width = this.map.tileWidth * xScale;
  77077. tile.height = this.map.tileHeight * yScale;
  77078. tile.worldX = tile.x * tile.width;
  77079. tile.worldY = tile.y * tile.height;
  77080. }
  77081. }
  77082. this.scale.setTo(xScale, yScale);
  77083. };
  77084. /**
  77085. * Shifts the contents of the canvas - does extra math so that different browsers agree on the result.
  77086. *
  77087. * The specified (x/y) will be shifted to (0,0) after the copy and the newly exposed canvas area will need to be filled in.
  77088. *
  77089. * @method Phaser.TilemapLayer#shiftCanvas
  77090. * @private
  77091. * @param {CanvasRenderingContext2D} context - The context to shift
  77092. * @param {integer} x
  77093. * @param {integer} y
  77094. */
  77095. Phaser.TilemapLayer.prototype.shiftCanvas = function (context, x, y) {
  77096. var canvas = context.canvas;
  77097. var copyW = canvas.width - Math.abs(x);
  77098. var copyH = canvas.height - Math.abs(y);
  77099. // When x/y non-negative
  77100. var dx = 0;
  77101. var dy = 0;
  77102. var sx = x;
  77103. var sy = y;
  77104. if (x < 0)
  77105. {
  77106. dx = -x;
  77107. sx = 0;
  77108. }
  77109. if (y < 0)
  77110. {
  77111. dy = -y;
  77112. sy = 0;
  77113. }
  77114. var copyCanvas = this.renderSettings.copyCanvas;
  77115. if (copyCanvas)
  77116. {
  77117. // Use a second copy buffer, without slice support, for Safari .. again.
  77118. // Ensure copy canvas is large enough
  77119. if (copyCanvas.width < copyW || copyCanvas.height < copyH)
  77120. {
  77121. copyCanvas.width = copyW;
  77122. copyCanvas.height = copyH;
  77123. }
  77124. var copyContext = copyCanvas.getContext('2d');
  77125. copyContext.clearRect(0, 0, copyW, copyH);
  77126. copyContext.drawImage(canvas, dx, dy, copyW, copyH, 0, 0, copyW, copyH);
  77127. // clear allows default 'source-over' semantics
  77128. context.clearRect(sx, sy, copyW, copyH);
  77129. context.drawImage(copyCanvas, 0, 0, copyW, copyH, sx, sy, copyW, copyH);
  77130. }
  77131. else
  77132. {
  77133. // Avoids a second copy but flickers in Safari / Safari Mobile
  77134. // Ref. https://github.com/photonstorm/phaser/issues/1439
  77135. context.save();
  77136. context.globalCompositeOperation = 'copy';
  77137. context.drawImage(canvas, dx, dy, copyW, copyH, sx, sy, copyW, copyH);
  77138. context.restore();
  77139. }
  77140. };
  77141. /**
  77142. * Render tiles in the given area given by the virtual tile coordinates biased by the given scroll factor.
  77143. * This will constrain the tile coordinates based on wrapping but not physical coordinates.
  77144. *
  77145. * @method Phaser.TilemapLayer#renderRegion
  77146. * @private
  77147. * @param {integer} scrollX - Render x offset/scroll.
  77148. * @param {integer} scrollY - Render y offset/scroll.
  77149. * @param {integer} left - Leftmost column to render.
  77150. * @param {integer} top - Topmost row to render.
  77151. * @param {integer} right - Rightmost column to render.
  77152. * @param {integer} bottom - Bottommost row to render.
  77153. */
  77154. Phaser.TilemapLayer.prototype.renderRegion = function (scrollX, scrollY, left, top, right, bottom) {
  77155. var context = this.context;
  77156. var width = this.layer.width;
  77157. var height = this.layer.height;
  77158. var tw = this._mc.tileWidth;
  77159. var th = this._mc.tileHeight;
  77160. var tilesets = this._mc.tilesets;
  77161. var lastAlpha = NaN;
  77162. if (!this._wrap)
  77163. {
  77164. if (left <= right) // Only adjust if going to render
  77165. {
  77166. left = Math.max(0, left);
  77167. right = Math.min(width - 1, right);
  77168. }
  77169. if (top <= bottom)
  77170. {
  77171. top = Math.max(0, top);
  77172. bottom = Math.min(height - 1, bottom);
  77173. }
  77174. }
  77175. // top-left pixel of top-left cell
  77176. var baseX = (left * tw) - scrollX;
  77177. var baseY = (top * th) - scrollY;
  77178. // Fix normStartX/normStartY such it is normalized [0..width/height). This allows a simple conditional and decrement to always keep in range [0..width/height) during the loop. The major offset bias is to take care of negative values.
  77179. var normStartX = (left + ((1 << 20) * width)) % width;
  77180. var normStartY = (top + ((1 << 20) * height)) % height;
  77181. // tx/ty - are pixel coordinates where tile is drawn
  77182. // x/y - is cell location, normalized [0..width/height) in loop
  77183. // xmax/ymax - remaining cells to render on column/row
  77184. var tx, ty, x, y, xmax, ymax;
  77185. context.fillStyle = this.tileColor;
  77186. for (y = normStartY, ymax = bottom - top, ty = baseY;
  77187. ymax >= 0;
  77188. y++, ymax--, ty += th)
  77189. {
  77190. if (y >= height) { y -= height; }
  77191. var row = this.layer.data[y];
  77192. for (x = normStartX, xmax = right - left, tx = baseX;
  77193. xmax >= 0;
  77194. x++, xmax--, tx += tw)
  77195. {
  77196. if (x >= width) { x -= width; }
  77197. var tile = row[x];
  77198. if (!tile || tile.index < 0)
  77199. {
  77200. continue;
  77201. }
  77202. var index = tile.index;
  77203. var set = tilesets[index];
  77204. if (set === undefined)
  77205. {
  77206. set = this.resolveTileset(index);
  77207. }
  77208. // Setting the globalAlpha is "surprisingly expensive" in Chrome (38)
  77209. if (tile.alpha !== lastAlpha && !this.debug)
  77210. {
  77211. context.globalAlpha = tile.alpha;
  77212. lastAlpha = tile.alpha;
  77213. }
  77214. if (set)
  77215. {
  77216. if (tile.rotation || tile.flipped)
  77217. {
  77218. context.save();
  77219. context.translate(tx + tile.centerX, ty + tile.centerY);
  77220. context.rotate(tile.rotation);
  77221. if (tile.flipped)
  77222. {
  77223. context.scale(-1, 1);
  77224. }
  77225. set.draw(context, -tile.centerX, -tile.centerY, index);
  77226. context.restore();
  77227. }
  77228. else
  77229. {
  77230. set.draw(context, tx, ty, index);
  77231. }
  77232. }
  77233. else if (this.debugSettings.missingImageFill)
  77234. {
  77235. context.fillStyle = this.debugSettings.missingImageFill;
  77236. context.fillRect(tx, ty, tw, th);
  77237. }
  77238. if (tile.debug && this.debugSettings.debuggedTileOverfill)
  77239. {
  77240. context.fillStyle = this.debugSettings.debuggedTileOverfill;
  77241. context.fillRect(tx, ty, tw, th);
  77242. }
  77243. }
  77244. }
  77245. };
  77246. /**
  77247. * Shifts the canvas and render damaged edge tiles.
  77248. *
  77249. * @method Phaser.TilemapLayer#renderDeltaScroll
  77250. * @private
  77251. */
  77252. Phaser.TilemapLayer.prototype.renderDeltaScroll = function (shiftX, shiftY) {
  77253. var scrollX = this._mc.scrollX;
  77254. var scrollY = this._mc.scrollY;
  77255. var renderW = this.canvas.width;
  77256. var renderH = this.canvas.height;
  77257. var tw = this._mc.tileWidth;
  77258. var th = this._mc.tileHeight;
  77259. // Only cells with coordinates in the "plus" formed by `left <= x <= right` OR `top <= y <= bottom` are drawn. These coordinates may be outside the layer bounds.
  77260. // Start in pixels
  77261. var left = 0;
  77262. var right = -tw;
  77263. var top = 0;
  77264. var bottom = -th;
  77265. if (shiftX < 0) // layer moving left, damage right
  77266. {
  77267. left = renderW + shiftX; // shiftX neg.
  77268. right = renderW - 1;
  77269. }
  77270. else if (shiftX > 0)
  77271. {
  77272. // left -> 0
  77273. right = shiftX;
  77274. }
  77275. if (shiftY < 0) // layer moving down, damage top
  77276. {
  77277. top = renderH + shiftY; // shiftY neg.
  77278. bottom = renderH - 1;
  77279. }
  77280. else if (shiftY > 0)
  77281. {
  77282. // top -> 0
  77283. bottom = shiftY;
  77284. }
  77285. this.shiftCanvas(this.context, shiftX, shiftY);
  77286. // Transform into tile-space
  77287. left = Math.floor((left + scrollX) / tw);
  77288. right = Math.floor((right + scrollX) / tw);
  77289. top = Math.floor((top + scrollY) / th);
  77290. bottom = Math.floor((bottom + scrollY) / th);
  77291. if (left <= right)
  77292. {
  77293. // Clear left or right edge
  77294. this.context.clearRect(((left * tw) - scrollX), 0, (right - left + 1) * tw, renderH);
  77295. var trueTop = Math.floor((0 + scrollY) / th);
  77296. var trueBottom = Math.floor((renderH - 1 + scrollY) / th);
  77297. this.renderRegion(scrollX, scrollY, left, trueTop, right, trueBottom);
  77298. }
  77299. if (top <= bottom)
  77300. {
  77301. // Clear top or bottom edge
  77302. this.context.clearRect(0, ((top * th) - scrollY), renderW, (bottom - top + 1) * th);
  77303. var trueLeft = Math.floor((0 + scrollX) / tw);
  77304. var trueRight = Math.floor((renderW - 1 + scrollX) / tw);
  77305. this.renderRegion(scrollX, scrollY, trueLeft, top, trueRight, bottom);
  77306. }
  77307. };
  77308. /**
  77309. * Clear and render the entire canvas.
  77310. *
  77311. * @method Phaser.TilemapLayer#renderFull
  77312. * @private
  77313. */
  77314. Phaser.TilemapLayer.prototype.renderFull = function () {
  77315. var scrollX = this._mc.scrollX;
  77316. var scrollY = this._mc.scrollY;
  77317. var renderW = this.canvas.width;
  77318. var renderH = this.canvas.height;
  77319. var tw = this._mc.tileWidth;
  77320. var th = this._mc.tileHeight;
  77321. var left = Math.floor(scrollX / tw);
  77322. var right = Math.floor((renderW - 1 + scrollX) / tw);
  77323. var top = Math.floor(scrollY / th);
  77324. var bottom = Math.floor((renderH - 1 + scrollY) / th);
  77325. this.context.clearRect(0, 0, renderW, renderH);
  77326. this.renderRegion(scrollX, scrollY, left, top, right, bottom);
  77327. };
  77328. /**
  77329. * Renders the tiles to the layer canvas and pushes to the display.
  77330. *
  77331. * @method Phaser.TilemapLayer#render
  77332. * @protected
  77333. */
  77334. Phaser.TilemapLayer.prototype.render = function () {
  77335. var redrawAll = false;
  77336. if (!this.visible)
  77337. {
  77338. return;
  77339. }
  77340. if (this.dirty || this.layer.dirty)
  77341. {
  77342. this.layer.dirty = false;
  77343. redrawAll = true;
  77344. }
  77345. var renderWidth = this.canvas.width; // Use Sprite.width/height?
  77346. var renderHeight = this.canvas.height;
  77347. // Scrolling bias; whole pixels only
  77348. var scrollX = this._scrollX | 0;
  77349. var scrollY = this._scrollY | 0;
  77350. var mc = this._mc;
  77351. var shiftX = mc.scrollX - scrollX; // Negative when scrolling right/down
  77352. var shiftY = mc.scrollY - scrollY;
  77353. if (!redrawAll &&
  77354. shiftX === 0 && shiftY === 0 &&
  77355. mc.renderWidth === renderWidth && mc.renderHeight === renderHeight)
  77356. {
  77357. // No reason to redraw map, looking at same thing and not invalidated.
  77358. return;
  77359. }
  77360. this.context.save();
  77361. mc.scrollX = scrollX;
  77362. mc.scrollY = scrollY;
  77363. if (mc.renderWidth !== renderWidth || mc.renderHeight !== renderHeight)
  77364. {
  77365. // Could support automatic canvas resizing
  77366. mc.renderWidth = renderWidth;
  77367. mc.renderHeight = renderHeight;
  77368. }
  77369. if (this.debug)
  77370. {
  77371. this.context.globalAlpha = this.debugSettings.debugAlpha;
  77372. if (this.debugSettings.forceFullRedraw)
  77373. {
  77374. redrawAll = true;
  77375. }
  77376. }
  77377. if (!redrawAll &&
  77378. this.renderSettings.enableScrollDelta &&
  77379. (Math.abs(shiftX) + Math.abs(shiftY)) < Math.min(renderWidth, renderHeight))
  77380. {
  77381. this.renderDeltaScroll(shiftX, shiftY);
  77382. }
  77383. else
  77384. {
  77385. // Too much change or otherwise requires full render
  77386. this.renderFull();
  77387. }
  77388. if (this.debug)
  77389. {
  77390. this.context.globalAlpha = 1;
  77391. this.renderDebug();
  77392. }
  77393. this.texture.baseTexture.dirty();
  77394. this.dirty = false;
  77395. this.context.restore();
  77396. return true;
  77397. };
  77398. /**
  77399. * Renders a debug overlay on-top of the canvas. Called automatically by render when `debug` is true.
  77400. *
  77401. * See `debugSettings` for assorted configuration options.
  77402. *
  77403. * @method Phaser.TilemapLayer#renderDebug
  77404. * @private
  77405. */
  77406. Phaser.TilemapLayer.prototype.renderDebug = function () {
  77407. var scrollX = this._mc.scrollX;
  77408. var scrollY = this._mc.scrollY;
  77409. var context = this.context;
  77410. var renderW = this.canvas.width;
  77411. var renderH = this.canvas.height;
  77412. var width = this.layer.width;
  77413. var height = this.layer.height;
  77414. var tw = this._mc.tileWidth;
  77415. var th = this._mc.tileHeight;
  77416. var left = Math.floor(scrollX / tw);
  77417. var right = Math.floor((renderW - 1 + scrollX) / tw);
  77418. var top = Math.floor(scrollY / th);
  77419. var bottom = Math.floor((renderH - 1 + scrollY) / th);
  77420. var baseX = (left * tw) - scrollX;
  77421. var baseY = (top * th) - scrollY;
  77422. var normStartX = (left + ((1 << 20) * width)) % width;
  77423. var normStartY = (top + ((1 << 20) * height)) % height;
  77424. var tx, ty, x, y, xmax, ymax;
  77425. context.strokeStyle = this.debugSettings.facingEdgeStroke;
  77426. for (y = normStartY, ymax = bottom - top, ty = baseY;
  77427. ymax >= 0;
  77428. y++, ymax--, ty += th)
  77429. {
  77430. if (y >= height) { y -= height; }
  77431. var row = this.layer.data[y];
  77432. for (x = normStartX, xmax = right - left, tx = baseX;
  77433. xmax >= 0;
  77434. x++, xmax--, tx += tw)
  77435. {
  77436. if (x >= width) { x -= width; }
  77437. var tile = row[x];
  77438. if (!tile || tile.index < 0 || !tile.collides)
  77439. {
  77440. continue;
  77441. }
  77442. if (this.debugSettings.collidingTileOverfill)
  77443. {
  77444. context.fillStyle = this.debugSettings.collidingTileOverfill;
  77445. context.fillRect(tx, ty, this._mc.cw, this._mc.ch);
  77446. }
  77447. if (this.debugSettings.facingEdgeStroke)
  77448. {
  77449. context.beginPath();
  77450. if (tile.faceTop)
  77451. {
  77452. context.moveTo(tx, ty);
  77453. context.lineTo(tx + this._mc.cw, ty);
  77454. }
  77455. if (tile.faceBottom)
  77456. {
  77457. context.moveTo(tx, ty + this._mc.ch);
  77458. context.lineTo(tx + this._mc.cw, ty + this._mc.ch);
  77459. }
  77460. if (tile.faceLeft)
  77461. {
  77462. context.moveTo(tx, ty);
  77463. context.lineTo(tx, ty + this._mc.ch);
  77464. }
  77465. if (tile.faceRight)
  77466. {
  77467. context.moveTo(tx + this._mc.cw, ty);
  77468. context.lineTo(tx + this._mc.cw, ty + this._mc.ch);
  77469. }
  77470. context.stroke();
  77471. }
  77472. }
  77473. }
  77474. };
  77475. /**
  77476. * Flag controlling if the layer tiles wrap at the edges. Only works if the World size matches the Map size.
  77477. *
  77478. * @property {boolean} wrap
  77479. * @memberof Phaser.TilemapLayer
  77480. * @public
  77481. * @default false
  77482. */
  77483. Object.defineProperty(Phaser.TilemapLayer.prototype, "wrap", {
  77484. get: function () {
  77485. return this._wrap;
  77486. },
  77487. set: function (value) {
  77488. this._wrap = value;
  77489. this.dirty = true;
  77490. }
  77491. });
  77492. /**
  77493. * Scrolls the map horizontally or returns the current x position.
  77494. *
  77495. * @property {number} scrollX
  77496. * @memberof Phaser.TilemapLayer
  77497. * @public
  77498. */
  77499. Object.defineProperty(Phaser.TilemapLayer.prototype, "scrollX", {
  77500. get: function () {
  77501. return this._scrollX;
  77502. },
  77503. set: function (value) {
  77504. this._scrollX = value;
  77505. }
  77506. });
  77507. /**
  77508. * Scrolls the map vertically or returns the current y position.
  77509. *
  77510. * @property {number} scrollY
  77511. * @memberof Phaser.TilemapLayer
  77512. * @public
  77513. */
  77514. Object.defineProperty(Phaser.TilemapLayer.prototype, "scrollY", {
  77515. get: function () {
  77516. return this._scrollY;
  77517. },
  77518. set: function (value) {
  77519. this._scrollY = value;
  77520. }
  77521. });
  77522. /**
  77523. * The width of the collision tiles (in pixels).
  77524. *
  77525. * @property {integer} collisionWidth
  77526. * @memberof Phaser.TilemapLayer
  77527. * @public
  77528. */
  77529. Object.defineProperty(Phaser.TilemapLayer.prototype, "collisionWidth", {
  77530. get: function () {
  77531. return this._mc.cw;
  77532. },
  77533. set: function (value) {
  77534. this._mc.cw = value | 0;
  77535. this.dirty = true;
  77536. }
  77537. });
  77538. /**
  77539. * The height of the collision tiles (in pixels).
  77540. *
  77541. * @property {integer} collisionHeight
  77542. * @memberof Phaser.TilemapLayer
  77543. * @public
  77544. */
  77545. Object.defineProperty(Phaser.TilemapLayer.prototype, "collisionHeight", {
  77546. get: function () {
  77547. return this._mc.ch;
  77548. },
  77549. set: function (value) {
  77550. this._mc.ch = value | 0;
  77551. this.dirty = true;
  77552. }
  77553. });
  77554. /**
  77555. * @author Richard Davey <rich@photonstorm.com>
  77556. * @copyright 2016 Photon Storm Ltd.
  77557. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  77558. */
  77559. /**
  77560. * Phaser.TilemapParser parses data objects from Phaser.Loader that need more preparation before they can be inserted into a Tilemap.
  77561. *
  77562. * @class Phaser.TilemapParser
  77563. * @static
  77564. */
  77565. Phaser.TilemapParser = {
  77566. /**
  77567. * When scanning the Tiled map data the TilemapParser can either insert a null value (true) or
  77568. * a Phaser.Tile instance with an index of -1 (false, the default). Depending on your game type
  77569. * depends how this should be configured. If you've a large sparsely populated map and the tile
  77570. * data doesn't need to change then setting this value to `true` will help with memory consumption.
  77571. * However if your map is small, or you need to update the tiles (perhaps the map dynamically changes
  77572. * during the game) then leave the default value set.
  77573. *
  77574. * @constant
  77575. * @type {boolean}
  77576. */
  77577. INSERT_NULL: false,
  77578. /**
  77579. * Parse tilemap data from the cache and creates a Tilemap object.
  77580. *
  77581. * @method Phaser.TilemapParser.parse
  77582. * @param {Phaser.Game} game - Game reference to the currently running game.
  77583. * @param {string} key - The key of the tilemap in the Cache.
  77584. * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
  77585. * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
  77586. * @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this.
  77587. * @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this.
  77588. * @return {object} The parsed map object.
  77589. */
  77590. parse: function (game, key, tileWidth, tileHeight, width, height) {
  77591. if (tileWidth === undefined) { tileWidth = 32; }
  77592. if (tileHeight === undefined) { tileHeight = 32; }
  77593. if (width === undefined) { width = 10; }
  77594. if (height === undefined) { height = 10; }
  77595. if (key === undefined)
  77596. {
  77597. return this.getEmptyData();
  77598. }
  77599. if (key === null)
  77600. {
  77601. return this.getEmptyData(tileWidth, tileHeight, width, height);
  77602. }
  77603. var map = game.cache.getTilemapData(key);
  77604. if (map)
  77605. {
  77606. if (map.format === Phaser.Tilemap.CSV)
  77607. {
  77608. return this.parseCSV(key, map.data, tileWidth, tileHeight);
  77609. }
  77610. else if (!map.format || map.format === Phaser.Tilemap.TILED_JSON)
  77611. {
  77612. return this.parseTiledJSON(map.data);
  77613. }
  77614. }
  77615. else
  77616. {
  77617. console.warn('Phaser.TilemapParser.parse - No map data found for key ' + key);
  77618. }
  77619. },
  77620. /**
  77621. * Parses a CSV file into valid map data.
  77622. *
  77623. * @method Phaser.TilemapParser.parseCSV
  77624. * @param {string} key - The name you want to give the map data.
  77625. * @param {string} data - The CSV file data.
  77626. * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
  77627. * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
  77628. * @return {object} Generated map data.
  77629. */
  77630. parseCSV: function (key, data, tileWidth, tileHeight) {
  77631. var map = this.getEmptyData();
  77632. // Trim any rogue whitespace from the data
  77633. data = data.trim();
  77634. var output = [];
  77635. var rows = data.split("\n");
  77636. var height = rows.length;
  77637. var width = 0;
  77638. for (var y = 0; y < rows.length; y++)
  77639. {
  77640. output[y] = [];
  77641. var column = rows[y].split(",");
  77642. for (var x = 0; x < column.length; x++)
  77643. {
  77644. output[y][x] = new Phaser.Tile(map.layers[0], parseInt(column[x], 10), x, y, tileWidth, tileHeight);
  77645. }
  77646. if (width === 0)
  77647. {
  77648. width = column.length;
  77649. }
  77650. }
  77651. map.format = Phaser.Tilemap.CSV;
  77652. map.name = key;
  77653. map.width = width;
  77654. map.height = height;
  77655. map.tileWidth = tileWidth;
  77656. map.tileHeight = tileHeight;
  77657. map.widthInPixels = width * tileWidth;
  77658. map.heightInPixels = height * tileHeight;
  77659. map.layers[0].width = width;
  77660. map.layers[0].height = height;
  77661. map.layers[0].widthInPixels = map.widthInPixels;
  77662. map.layers[0].heightInPixels = map.heightInPixels;
  77663. map.layers[0].data = output;
  77664. return map;
  77665. },
  77666. /**
  77667. * Returns an empty map data object.
  77668. *
  77669. * @method Phaser.TilemapParser.getEmptyData
  77670. * @return {object} Generated map data.
  77671. */
  77672. getEmptyData: function (tileWidth, tileHeight, width, height) {
  77673. var map = {};
  77674. map.width = 0;
  77675. map.height = 0;
  77676. map.tileWidth = 0;
  77677. map.tileHeight = 0;
  77678. if (typeof tileWidth !== 'undefined' && tileWidth !== null) { map.tileWidth = tileWidth; }
  77679. if (typeof tileHeight !== 'undefined' && tileHeight !== null) { map.tileHeight = tileHeight; }
  77680. if (typeof width !== 'undefined' && width !== null) { map.width = width; }
  77681. if (typeof height !== 'undefined' && height !== null) { map.height = height; }
  77682. map.orientation = 'orthogonal';
  77683. map.version = '1';
  77684. map.properties = {};
  77685. map.widthInPixels = 0;
  77686. map.heightInPixels = 0;
  77687. var layers = [];
  77688. var layer = {
  77689. name: 'layer',
  77690. x: 0,
  77691. y: 0,
  77692. width: 0,
  77693. height: 0,
  77694. widthInPixels: 0,
  77695. heightInPixels: 0,
  77696. alpha: 1,
  77697. visible: true,
  77698. properties: {},
  77699. indexes: [],
  77700. callbacks: [],
  77701. bodies: [],
  77702. data: []
  77703. };
  77704. // fill with nulls?
  77705. layers.push(layer);
  77706. map.layers = layers;
  77707. map.images = [];
  77708. map.objects = {};
  77709. map.collision = {};
  77710. map.tilesets = [];
  77711. map.tiles = [];
  77712. return map;
  77713. },
  77714. /**
  77715. * Parses a Tiled JSON file into valid map data.
  77716. * @method Phaser.TilemapParser.parseJSON
  77717. * @param {object} json - The JSON map data.
  77718. * @return {object} Generated and parsed map data.
  77719. */
  77720. parseTiledJSON: function (json) {
  77721. if (json.orientation !== 'orthogonal')
  77722. {
  77723. console.warn('TilemapParser.parseTiledJSON - Only orthogonal map types are supported in this version of Phaser');
  77724. return null;
  77725. }
  77726. // Map data will consist of: layers, objects, images, tilesets, sizes
  77727. var map = {};
  77728. map.width = json.width;
  77729. map.height = json.height;
  77730. map.tileWidth = json.tilewidth;
  77731. map.tileHeight = json.tileheight;
  77732. map.orientation = json.orientation;
  77733. map.format = Phaser.Tilemap.TILED_JSON;
  77734. map.version = json.version;
  77735. map.properties = json.properties;
  77736. map.widthInPixels = map.width * map.tileWidth;
  77737. map.heightInPixels = map.height * map.tileHeight;
  77738. // Tile Layers
  77739. var layers = [];
  77740. for (var i = 0; i < json.layers.length; i++)
  77741. {
  77742. if (json.layers[i].type !== 'tilelayer')
  77743. {
  77744. continue;
  77745. }
  77746. var curl = json.layers[i];
  77747. // Base64 decode data if necessary
  77748. // NOTE: uncompressed base64 only.
  77749. if (!curl.compression && curl.encoding && curl.encoding === "base64") {
  77750. var binaryString = window.atob(curl.data);
  77751. var len = binaryString.length;
  77752. var bytes = new Array( len );
  77753. // Interpret binaryString as an array of bytes representing
  77754. // little-endian encoded uint32 values.
  77755. for (var j = 0; j < len; j+=4) {
  77756. bytes[j/4] = (binaryString.charCodeAt(j) |
  77757. binaryString.charCodeAt(j+1) << 8 |
  77758. binaryString.charCodeAt(j+2) << 16 |
  77759. binaryString.charCodeAt(j+3) << 24) >>> 0;
  77760. }
  77761. curl.data = bytes;
  77762. delete curl.encoding;
  77763. }
  77764. else if(curl.compression){
  77765. console.warn('TilemapParser.parseTiledJSON - Layer compression is unsupported, skipping layer \'' + curl.name + '\'');
  77766. continue;
  77767. }
  77768. var layer = {
  77769. name: curl.name,
  77770. x: curl.x,
  77771. y: curl.y,
  77772. width: curl.width,
  77773. height: curl.height,
  77774. widthInPixels: curl.width * json.tilewidth,
  77775. heightInPixels: curl.height * json.tileheight,
  77776. alpha: curl.opacity,
  77777. visible: curl.visible,
  77778. properties: {},
  77779. indexes: [],
  77780. callbacks: [],
  77781. bodies: []
  77782. };
  77783. if (curl.properties)
  77784. {
  77785. layer.properties = curl.properties;
  77786. }
  77787. var x = 0;
  77788. var row = [];
  77789. var output = [];
  77790. var rotation, flipped, flippedVal, gid;
  77791. // Loop through the data field in the JSON.
  77792. // This is an array containing the tile indexes, one after the other. -1 = no tile, everything else = the tile index (starting at 1 for Tiled, 0 for CSV)
  77793. // If the map contains multiple tilesets then the indexes are relative to that which the set starts from.
  77794. // Need to set which tileset in the cache = which tileset in the JSON, if you do this manually it means you can use the same map data but a new tileset.
  77795. for (var t = 0, len = curl.data.length; t < len; t++)
  77796. {
  77797. rotation = 0;
  77798. flipped = false;
  77799. gid = curl.data[t];
  77800. // If true the current tile is flipped or rotated (Tiled TMX format)
  77801. if (gid > 0x20000000)
  77802. {
  77803. flippedVal = 0;
  77804. // FlippedX
  77805. if (gid > 0x80000000)
  77806. {
  77807. gid -= 0x80000000;
  77808. flippedVal += 4;
  77809. }
  77810. // FlippedY
  77811. if (gid > 0x40000000)
  77812. {
  77813. gid -= 0x40000000;
  77814. flippedVal += 2;
  77815. }
  77816. // FlippedAD
  77817. if (gid > 0x20000000)
  77818. {
  77819. gid -= 0x20000000;
  77820. flippedVal += 1;
  77821. }
  77822. switch (flippedVal)
  77823. {
  77824. case 5:
  77825. rotation = Math.PI/2;
  77826. break;
  77827. case 6:
  77828. rotation = Math.PI;
  77829. break;
  77830. case 3:
  77831. rotation = 3*Math.PI/2;
  77832. break;
  77833. case 4:
  77834. rotation = 0;
  77835. flipped = true;
  77836. break;
  77837. case 7:
  77838. rotation = Math.PI/2;
  77839. flipped = true;
  77840. break;
  77841. case 2:
  77842. rotation = Math.PI;
  77843. flipped = true;
  77844. break;
  77845. case 1:
  77846. rotation = 3*Math.PI/2;
  77847. flipped = true;
  77848. break;
  77849. }
  77850. }
  77851. // index, x, y, width, height
  77852. if (gid > 0)
  77853. {
  77854. row.push(new Phaser.Tile(layer, gid, x, output.length, json.tilewidth, json.tileheight));
  77855. row[row.length - 1].rotation = rotation;
  77856. row[row.length - 1].flipped = flipped;
  77857. }
  77858. else
  77859. {
  77860. if (Phaser.TilemapParser.INSERT_NULL)
  77861. {
  77862. row.push(null);
  77863. }
  77864. else
  77865. {
  77866. row.push(new Phaser.Tile(layer, -1, x, output.length, json.tilewidth, json.tileheight));
  77867. }
  77868. }
  77869. x++;
  77870. if (x === curl.width)
  77871. {
  77872. output.push(row);
  77873. x = 0;
  77874. row = [];
  77875. }
  77876. }
  77877. layer.data = output;
  77878. layers.push(layer);
  77879. }
  77880. map.layers = layers;
  77881. // Images
  77882. var images = [];
  77883. for (var i = 0; i < json.layers.length; i++)
  77884. {
  77885. if (json.layers[i].type !== 'imagelayer')
  77886. {
  77887. continue;
  77888. }
  77889. var curi = json.layers[i];
  77890. var image = {
  77891. name: curi.name,
  77892. image: curi.image,
  77893. x: curi.x,
  77894. y: curi.y,
  77895. alpha: curi.opacity,
  77896. visible: curi.visible,
  77897. properties: {}
  77898. };
  77899. if (curi.properties)
  77900. {
  77901. image.properties = curi.properties;
  77902. }
  77903. images.push(image);
  77904. }
  77905. map.images = images;
  77906. // Tilesets & Image Collections
  77907. var tilesets = [];
  77908. var imagecollections = [];
  77909. for (var i = 0; i < json.tilesets.length; i++)
  77910. {
  77911. // name, firstgid, width, height, margin, spacing, properties
  77912. var set = json.tilesets[i];
  77913. if (set.image)
  77914. {
  77915. var newSet = new Phaser.Tileset(set.name, set.firstgid, set.tilewidth, set.tileheight, set.margin, set.spacing, set.properties);
  77916. if (set.tileproperties)
  77917. {
  77918. newSet.tileProperties = set.tileproperties;
  77919. }
  77920. // For a normal sliced tileset the row/count/size information is computed when updated.
  77921. // This is done (again) after the image is set.
  77922. newSet.updateTileData(set.imagewidth, set.imageheight);
  77923. tilesets.push(newSet);
  77924. }
  77925. else
  77926. {
  77927. var newCollection = new Phaser.ImageCollection(set.name, set.firstgid, set.tilewidth, set.tileheight, set.margin, set.spacing, set.properties);
  77928. for (var ti in set.tiles)
  77929. {
  77930. var image = set.tiles[ti].image;
  77931. var gid = set.firstgid + parseInt(ti, 10);
  77932. newCollection.addImage(gid, image);
  77933. }
  77934. imagecollections.push(newCollection);
  77935. }
  77936. }
  77937. map.tilesets = tilesets;
  77938. map.imagecollections = imagecollections;
  77939. // Objects & Collision Data (polylines, etc)
  77940. var objects = {};
  77941. var collision = {};
  77942. function slice (obj, fields) {
  77943. var sliced = {};
  77944. for (var k in fields)
  77945. {
  77946. var key = fields[k];
  77947. if (typeof obj[key] !== 'undefined')
  77948. {
  77949. sliced[key] = obj[key];
  77950. }
  77951. }
  77952. return sliced;
  77953. }
  77954. for (var i = 0; i < json.layers.length; i++)
  77955. {
  77956. if (json.layers[i].type !== 'objectgroup')
  77957. {
  77958. continue;
  77959. }
  77960. var curo = json.layers[i];
  77961. objects[curo.name] = [];
  77962. collision[curo.name] = [];
  77963. for (var v = 0, len = curo.objects.length; v < len; v++)
  77964. {
  77965. // Object Tiles
  77966. if (curo.objects[v].gid)
  77967. {
  77968. var object = {
  77969. gid: curo.objects[v].gid,
  77970. name: curo.objects[v].name,
  77971. type: curo.objects[v].hasOwnProperty("type") ? curo.objects[v].type : "",
  77972. x: curo.objects[v].x,
  77973. y: curo.objects[v].y,
  77974. visible: curo.objects[v].visible,
  77975. properties: curo.objects[v].properties
  77976. };
  77977. if (curo.objects[v].rotation)
  77978. {
  77979. object.rotation = curo.objects[v].rotation;
  77980. }
  77981. objects[curo.name].push(object);
  77982. }
  77983. else if (curo.objects[v].polyline)
  77984. {
  77985. var object = {
  77986. name: curo.objects[v].name,
  77987. type: curo.objects[v].type,
  77988. x: curo.objects[v].x,
  77989. y: curo.objects[v].y,
  77990. width: curo.objects[v].width,
  77991. height: curo.objects[v].height,
  77992. visible: curo.objects[v].visible,
  77993. properties: curo.objects[v].properties
  77994. };
  77995. if (curo.objects[v].rotation)
  77996. {
  77997. object.rotation = curo.objects[v].rotation;
  77998. }
  77999. object.polyline = [];
  78000. // Parse the polyline into an array
  78001. for (var p = 0; p < curo.objects[v].polyline.length; p++)
  78002. {
  78003. object.polyline.push([ curo.objects[v].polyline[p].x, curo.objects[v].polyline[p].y ]);
  78004. }
  78005. collision[curo.name].push(object);
  78006. objects[curo.name].push(object);
  78007. }
  78008. // polygon
  78009. else if (curo.objects[v].polygon)
  78010. {
  78011. var object = slice(curo.objects[v],
  78012. ["name", "type", "x", "y", "visible", "rotation", "properties" ]);
  78013. // Parse the polygon into an array
  78014. object.polygon = [];
  78015. for (var p = 0; p < curo.objects[v].polygon.length; p++)
  78016. {
  78017. object.polygon.push([ curo.objects[v].polygon[p].x, curo.objects[v].polygon[p].y ]);
  78018. }
  78019. objects[curo.name].push(object);
  78020. }
  78021. // ellipse
  78022. else if (curo.objects[v].ellipse)
  78023. {
  78024. var object = slice(curo.objects[v],
  78025. ["name", "type", "ellipse", "x", "y", "width", "height", "visible", "rotation", "properties" ]);
  78026. objects[curo.name].push(object);
  78027. }
  78028. // otherwise it's a rectangle
  78029. else
  78030. {
  78031. var object = slice(curo.objects[v],
  78032. ["name", "type", "x", "y", "width", "height", "visible", "rotation", "properties" ]);
  78033. object.rectangle = true;
  78034. objects[curo.name].push(object);
  78035. }
  78036. }
  78037. }
  78038. map.objects = objects;
  78039. map.collision = collision;
  78040. map.tiles = [];
  78041. // Finally lets build our super tileset index
  78042. for (var i = 0; i < map.tilesets.length; i++)
  78043. {
  78044. var set = map.tilesets[i];
  78045. var x = set.tileMargin;
  78046. var y = set.tileMargin;
  78047. var count = 0;
  78048. var countX = 0;
  78049. var countY = 0;
  78050. for (var t = set.firstgid; t < set.firstgid + set.total; t++)
  78051. {
  78052. // Can add extra properties here as needed
  78053. map.tiles[t] = [x, y, i];
  78054. x += set.tileWidth + set.tileSpacing;
  78055. count++;
  78056. if (count === set.total)
  78057. {
  78058. break;
  78059. }
  78060. countX++;
  78061. if (countX === set.columns)
  78062. {
  78063. x = set.tileMargin;
  78064. y += set.tileHeight + set.tileSpacing;
  78065. countX = 0;
  78066. countY++;
  78067. if (countY === set.rows)
  78068. {
  78069. break;
  78070. }
  78071. }
  78072. }
  78073. }
  78074. // assign tile properties
  78075. var layer;
  78076. var tile;
  78077. var sid;
  78078. var set;
  78079. // go through each of the map layers
  78080. for (var i = 0; i < map.layers.length; i++)
  78081. {
  78082. layer = map.layers[i];
  78083. // rows of tiles
  78084. for (var j = 0; j < layer.data.length; j++)
  78085. {
  78086. row = layer.data[j];
  78087. // individual tiles
  78088. for (var k = 0; k < row.length; k++)
  78089. {
  78090. tile = row[k];
  78091. if (tile === null || tile.index < 0)
  78092. {
  78093. continue;
  78094. }
  78095. // find the relevant tileset
  78096. sid = map.tiles[tile.index][2];
  78097. set = map.tilesets[sid];
  78098. // if that tile type has any properties, add them to the tile object
  78099. if (set.tileProperties && set.tileProperties[tile.index - set.firstgid])
  78100. {
  78101. tile.properties = Phaser.Utils.mixin(set.tileProperties[tile.index - set.firstgid], tile.properties);
  78102. }
  78103. }
  78104. }
  78105. }
  78106. return map;
  78107. }
  78108. };
  78109. /**
  78110. * @author Richard Davey <rich@photonstorm.com>
  78111. * @copyright 2016 Photon Storm Ltd.
  78112. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  78113. */
  78114. /**
  78115. * A Tile set is a combination of an image containing the tiles and collision data per tile.
  78116. *
  78117. * Tilesets are normally created automatically when Tiled data is loaded.
  78118. *
  78119. * @class Phaser.Tileset
  78120. * @constructor
  78121. * @param {string} name - The name of the tileset in the map data.
  78122. * @param {integer} firstgid - The first tile index this tileset contains.
  78123. * @param {integer} [width=32] - Width of each tile (in pixels).
  78124. * @param {integer} [height=32] - Height of each tile (in pixels).
  78125. * @param {integer} [margin=0] - The margin around all tiles in the sheet (in pixels).
  78126. * @param {integer} [spacing=0] - The spacing between each tile in the sheet (in pixels).
  78127. * @param {object} [properties={}] - Custom Tileset properties.
  78128. */
  78129. Phaser.Tileset = function (name, firstgid, width, height, margin, spacing, properties) {
  78130. if (width === undefined || width <= 0) { width = 32; }
  78131. if (height === undefined || height <= 0) { height = 32; }
  78132. if (margin === undefined) { margin = 0; }
  78133. if (spacing === undefined) { spacing = 0; }
  78134. /**
  78135. * The name of the Tileset.
  78136. * @property {string} name
  78137. */
  78138. this.name = name;
  78139. /**
  78140. * The Tiled firstgid value.
  78141. * This is the starting index of the first tile index this Tileset contains.
  78142. * @property {integer} firstgid
  78143. */
  78144. this.firstgid = firstgid | 0;
  78145. /**
  78146. * The width of each tile (in pixels).
  78147. * @property {integer} tileWidth
  78148. * @readonly
  78149. */
  78150. this.tileWidth = width | 0;
  78151. /**
  78152. * The height of each tile (in pixels).
  78153. * @property {integer} tileHeight
  78154. * @readonly
  78155. */
  78156. this.tileHeight = height | 0;
  78157. /**
  78158. * The margin around the tiles in the sheet (in pixels).
  78159. * Use `setSpacing` to change.
  78160. * @property {integer} tileMarge
  78161. * @readonly
  78162. */
  78163. // Modified internally
  78164. this.tileMargin = margin | 0;
  78165. /**
  78166. * The spacing between each tile in the sheet (in pixels).
  78167. * Use `setSpacing` to change.
  78168. * @property {integer} tileSpacing
  78169. * @readonly
  78170. */
  78171. this.tileSpacing = spacing | 0;
  78172. /**
  78173. * Tileset-specific properties that are typically defined in the Tiled editor.
  78174. * @property {object} properties
  78175. */
  78176. this.properties = properties || {};
  78177. /**
  78178. * The cached image that contains the individual tiles. Use {@link Phaser.Tileset.setImage setImage} to set.
  78179. * @property {?object} image
  78180. * @readonly
  78181. */
  78182. // Modified internally
  78183. this.image = null;
  78184. /**
  78185. * The number of tile rows in the the tileset.
  78186. * @property {integer}
  78187. * @readonly
  78188. */
  78189. // Modified internally
  78190. this.rows = 0;
  78191. /**
  78192. * The number of tile columns in the tileset.
  78193. * @property {integer} columns
  78194. * @readonly
  78195. */
  78196. // Modified internally
  78197. this.columns = 0;
  78198. /**
  78199. * The total number of tiles in the tileset.
  78200. * @property {integer} total
  78201. * @readonly
  78202. */
  78203. // Modified internally
  78204. this.total = 0;
  78205. /**
  78206. * The look-up table to specific tile image offsets.
  78207. * The coordinates are interlaced such that it is [x0, y0, x1, y1 .. xN, yN] and the tile with the index of firstgid is found at indices 0/1.
  78208. * @property {integer[]} drawCoords
  78209. * @private
  78210. */
  78211. this.drawCoords = [];
  78212. };
  78213. Phaser.Tileset.prototype = {
  78214. /**
  78215. * Draws a tile from this Tileset at the given coordinates on the context.
  78216. *
  78217. * @method Phaser.Tileset#draw
  78218. * @public
  78219. * @param {CanvasRenderingContext2D} context - The context to draw the tile onto.
  78220. * @param {number} x - The x coordinate to draw to.
  78221. * @param {number} y - The y coordinate to draw to.
  78222. * @param {integer} index - The index of the tile within the set to draw.
  78223. */
  78224. draw: function (context, x, y, index) {
  78225. // Correct the tile index for the set and bias for interlacing
  78226. var coordIndex = (index - this.firstgid) << 1;
  78227. if (coordIndex >= 0 && (coordIndex + 1) < this.drawCoords.length)
  78228. {
  78229. context.drawImage(
  78230. this.image,
  78231. this.drawCoords[coordIndex],
  78232. this.drawCoords[coordIndex + 1],
  78233. this.tileWidth,
  78234. this.tileHeight,
  78235. x,
  78236. y,
  78237. this.tileWidth,
  78238. this.tileHeight
  78239. );
  78240. }
  78241. },
  78242. /**
  78243. * Returns true if and only if this tileset contains the given tile index.
  78244. *
  78245. * @method Phaser.Tileset#containsTileIndex
  78246. * @public
  78247. * @return {boolean} True if this tileset contains the given index.
  78248. */
  78249. containsTileIndex: function (tileIndex) {
  78250. return (
  78251. tileIndex >= this.firstgid &&
  78252. tileIndex < (this.firstgid + this.total)
  78253. );
  78254. },
  78255. /**
  78256. * Set the image associated with this Tileset and update the tile data.
  78257. *
  78258. * @method Phaser.Tileset#setImage
  78259. * @public
  78260. * @param {Image} image - The image that contains the tiles.
  78261. */
  78262. setImage: function (image) {
  78263. this.image = image;
  78264. this.updateTileData(image.width, image.height);
  78265. },
  78266. /**
  78267. * Sets tile spacing and margins.
  78268. *
  78269. * @method Phaser.Tileset#setSpacing
  78270. * @public
  78271. * @param {integer} [margin=0] - The margin around the tiles in the sheet (in pixels).
  78272. * @param {integer} [spacing=0] - The spacing between the tiles in the sheet (in pixels).
  78273. */
  78274. setSpacing: function (margin, spacing) {
  78275. this.tileMargin = margin | 0;
  78276. this.tileSpacing = spacing | 0;
  78277. if (this.image)
  78278. {
  78279. this.updateTileData(this.image.width, this.image.height);
  78280. }
  78281. },
  78282. /**
  78283. * Updates tile coordinates and tileset data.
  78284. *
  78285. * @method Phaser.Tileset#updateTileData
  78286. * @private
  78287. * @param {integer} imageWidth - The (expected) width of the image to slice.
  78288. * @param {integer} imageHeight - The (expected) height of the image to slice.
  78289. */
  78290. updateTileData: function (imageWidth, imageHeight) {
  78291. // May be fractional values
  78292. var rowCount = (imageHeight - this.tileMargin * 2 + this.tileSpacing) / (this.tileHeight + this.tileSpacing);
  78293. var colCount = (imageWidth - this.tileMargin * 2 + this.tileSpacing) / (this.tileWidth + this.tileSpacing);
  78294. if (rowCount % 1 !== 0 || colCount % 1 !== 0)
  78295. {
  78296. console.warn("Phaser.Tileset - " + this.name + " image tile area is not an even multiple of tile size");
  78297. }
  78298. // In Tiled a tileset image that is not an even multiple of the tile dimensions
  78299. // is truncated - hence the floor when calculating the rows/columns.
  78300. rowCount = Math.floor(rowCount);
  78301. colCount = Math.floor(colCount);
  78302. if ((this.rows && this.rows !== rowCount) || (this.columns && this.columns !== colCount))
  78303. {
  78304. console.warn("Phaser.Tileset - actual and expected number of tile rows and columns differ");
  78305. }
  78306. this.rows = rowCount;
  78307. this.columns = colCount;
  78308. this.total = rowCount * colCount;
  78309. this.drawCoords.length = 0;
  78310. var tx = this.tileMargin;
  78311. var ty = this.tileMargin;
  78312. for (var y = 0; y < this.rows; y++)
  78313. {
  78314. for (var x = 0; x < this.columns; x++)
  78315. {
  78316. this.drawCoords.push(tx);
  78317. this.drawCoords.push(ty);
  78318. tx += this.tileWidth + this.tileSpacing;
  78319. }
  78320. tx = this.tileMargin;
  78321. ty += this.tileHeight + this.tileSpacing;
  78322. }
  78323. }
  78324. };
  78325. Phaser.Tileset.prototype.constructor = Phaser.Tileset;
  78326. /**
  78327. * @author Richard Davey <rich@photonstorm.com>
  78328. * @copyright 2016 Photon Storm Ltd.
  78329. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  78330. */
  78331. /**
  78332. * Create a new `Particle` object. Particles are extended Sprites that are emitted by a particle emitter such as Phaser.Particles.Arcade.Emitter.
  78333. *
  78334. * @class Phaser.Particle
  78335. * @constructor
  78336. * @extends Phaser.Sprite
  78337. * @param {Phaser.Game} game - A reference to the currently running game.
  78338. * @param {number} x - The x coordinate (in world space) to position the Particle at.
  78339. * @param {number} y - The y coordinate (in world space) to position the Particle at.
  78340. * @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Particle during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture.
  78341. * @param {string|number} frame - If this Particle 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.
  78342. */
  78343. Phaser.Particle = function (game, x, y, key, frame) {
  78344. Phaser.Sprite.call(this, game, x, y, key, frame);
  78345. /**
  78346. * @property {boolean} autoScale - If this Particle automatically scales this is set to true by Particle.setScaleData.
  78347. * @protected
  78348. */
  78349. this.autoScale = false;
  78350. /**
  78351. * @property {array} scaleData - A reference to the scaleData array owned by the Emitter that emitted this Particle.
  78352. * @protected
  78353. */
  78354. this.scaleData = null;
  78355. /**
  78356. * @property {number} _s - Internal cache var for tracking auto scale.
  78357. * @private
  78358. */
  78359. this._s = 0;
  78360. /**
  78361. * @property {boolean} autoAlpha - If this Particle automatically changes alpha this is set to true by Particle.setAlphaData.
  78362. * @protected
  78363. */
  78364. this.autoAlpha = false;
  78365. /**
  78366. * @property {array} alphaData - A reference to the alphaData array owned by the Emitter that emitted this Particle.
  78367. * @protected
  78368. */
  78369. this.alphaData = null;
  78370. /**
  78371. * @property {number} _a - Internal cache var for tracking auto alpha.
  78372. * @private
  78373. */
  78374. this._a = 0;
  78375. };
  78376. Phaser.Particle.prototype = Object.create(Phaser.Sprite.prototype);
  78377. Phaser.Particle.prototype.constructor = Phaser.Particle;
  78378. /**
  78379. * Updates the Particle scale or alpha if autoScale and autoAlpha are set.
  78380. *
  78381. * @method Phaser.Particle#update
  78382. * @memberof Phaser.Particle
  78383. */
  78384. Phaser.Particle.prototype.update = function() {
  78385. if (this.autoScale)
  78386. {
  78387. this._s--;
  78388. if (this._s)
  78389. {
  78390. this.scale.set(this.scaleData[this._s].x, this.scaleData[this._s].y);
  78391. }
  78392. else
  78393. {
  78394. this.autoScale = false;
  78395. }
  78396. }
  78397. if (this.autoAlpha)
  78398. {
  78399. this._a--;
  78400. if (this._a)
  78401. {
  78402. this.alpha = this.alphaData[this._a].v;
  78403. }
  78404. else
  78405. {
  78406. this.autoAlpha = false;
  78407. }
  78408. }
  78409. };
  78410. /**
  78411. * Called by the Emitter when this particle is emitted. Left empty for you to over-ride as required.
  78412. *
  78413. * @method Phaser.Particle#onEmit
  78414. * @memberof Phaser.Particle
  78415. */
  78416. Phaser.Particle.prototype.onEmit = function() {
  78417. };
  78418. /**
  78419. * Called by the Emitter if autoAlpha has been enabled. Passes over the alpha ease data and resets the alpha counter.
  78420. *
  78421. * @method Phaser.Particle#setAlphaData
  78422. * @memberof Phaser.Particle
  78423. */
  78424. Phaser.Particle.prototype.setAlphaData = function(data) {
  78425. this.alphaData = data;
  78426. this._a = data.length - 1;
  78427. this.alpha = this.alphaData[this._a].v;
  78428. this.autoAlpha = true;
  78429. };
  78430. /**
  78431. * Called by the Emitter if autoScale has been enabled. Passes over the scale ease data and resets the scale counter.
  78432. *
  78433. * @method Phaser.Particle#setScaleData
  78434. * @memberof Phaser.Particle
  78435. */
  78436. Phaser.Particle.prototype.setScaleData = function(data) {
  78437. this.scaleData = data;
  78438. this._s = data.length - 1;
  78439. this.scale.set(this.scaleData[this._s].x, this.scaleData[this._s].y);
  78440. this.autoScale = true;
  78441. };
  78442. /**
  78443. * Resets the Particle. This places the Particle at the given x/y world coordinates and then
  78444. * sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state and health values.
  78445. * If the Particle has a physics body that too is reset.
  78446. *
  78447. * @method Phaser.Particle#reset
  78448. * @memberof Phaser.Particle
  78449. * @param {number} x - The x coordinate (in world space) to position the Particle at.
  78450. * @param {number} y - The y coordinate (in world space) to position the Particle at.
  78451. * @param {number} [health=1] - The health to give the Particle.
  78452. * @return {Phaser.Particle} This instance.
  78453. */
  78454. Phaser.Particle.prototype.reset = function(x, y, health) {
  78455. Phaser.Component.Reset.prototype.reset.call(this, x, y, health);
  78456. this.alpha = 1;
  78457. this.scale.set(1);
  78458. this.autoScale = false;
  78459. this.autoAlpha = false;
  78460. return this;
  78461. };
  78462. /**
  78463. * @author Richard Davey <rich@photonstorm.com>
  78464. * @copyright 2016 Photon Storm Ltd.
  78465. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  78466. */
  78467. /**
  78468. * 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.
  78469. *
  78470. * @class Phaser.Particles
  78471. * @constructor
  78472. * @param {Phaser.Game} game - A reference to the currently running game.
  78473. */
  78474. Phaser.Particles = function (game) {
  78475. /**
  78476. * @property {Phaser.Game} game - A reference to the currently running Game.
  78477. */
  78478. this.game = game;
  78479. /**
  78480. * @property {object} emitters - Internal emitters store.
  78481. */
  78482. this.emitters = {};
  78483. /**
  78484. * @property {number} ID -
  78485. * @default
  78486. */
  78487. this.ID = 0;
  78488. };
  78489. Phaser.Particles.prototype = {
  78490. /**
  78491. * Adds a new Particle Emitter to the Particle Manager.
  78492. * @method Phaser.Particles#add
  78493. * @param {Phaser.Emitter} emitter - The emitter to be added to the particle manager.
  78494. * @return {Phaser.Emitter} The emitter that was added.
  78495. */
  78496. add: function (emitter) {
  78497. this.emitters[emitter.name] = emitter;
  78498. return emitter;
  78499. },
  78500. /**
  78501. * Removes an existing Particle Emitter from the Particle Manager.
  78502. * @method Phaser.Particles#remove
  78503. * @param {Phaser.Emitter} emitter - The emitter to remove.
  78504. */
  78505. remove: function (emitter) {
  78506. delete this.emitters[emitter.name];
  78507. },
  78508. /**
  78509. * Called by the core game loop. Updates all Emitters who have their exists value set to true.
  78510. * @method Phaser.Particles#update
  78511. * @protected
  78512. */
  78513. update: function () {
  78514. for (var key in this.emitters)
  78515. {
  78516. if (this.emitters[key].exists)
  78517. {
  78518. this.emitters[key].update();
  78519. }
  78520. }
  78521. }
  78522. };
  78523. Phaser.Particles.prototype.constructor = Phaser.Particles;
  78524. /**
  78525. * @author Richard Davey <rich@photonstorm.com>
  78526. * @copyright 2016 Photon Storm Ltd.
  78527. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  78528. */
  78529. /**
  78530. * Arcade Particles is a Particle System integrated with Arcade Physics.
  78531. *
  78532. * @class Phaser.Particles.Arcade
  78533. */
  78534. Phaser.Particles.Arcade = {};
  78535. /**
  78536. * @author Richard Davey <rich@photonstorm.com>
  78537. * @copyright 2016 Photon Storm Ltd.
  78538. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  78539. */
  78540. /**
  78541. * Emitter is a lightweight particle emitter that uses Arcade Physics.
  78542. * It can be used for one-time explosions or for continuous effects like rain and fire.
  78543. * All it really does is launch Particle objects out at set intervals, and fixes their positions and velocities accordingly.
  78544. *
  78545. * @class Phaser.Particles.Arcade.Emitter
  78546. * @constructor
  78547. * @extends Phaser.Group
  78548. * @param {Phaser.Game} game - Current game instance.
  78549. * @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from.
  78550. * @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from.
  78551. * @param {number} [maxParticles=50] - The total number of particles in this emitter.
  78552. */
  78553. Phaser.Particles.Arcade.Emitter = function (game, x, y, maxParticles) {
  78554. /**
  78555. * @property {number} maxParticles - The total number of particles in this emitter.
  78556. * @default
  78557. */
  78558. this.maxParticles = maxParticles || 50;
  78559. Phaser.Group.call(this, game);
  78560. /**
  78561. * @property {string} name - A handy string name for this emitter. Can be set to anything.
  78562. */
  78563. this.name = 'emitter' + this.game.particles.ID++;
  78564. /**
  78565. * @property {number} type - Internal Phaser Type value.
  78566. * @protected
  78567. */
  78568. this.type = Phaser.EMITTER;
  78569. /**
  78570. * @property {number} physicsType - The const physics body type of this object.
  78571. * @readonly
  78572. */
  78573. this.physicsType = Phaser.GROUP;
  78574. /**
  78575. * @property {Phaser.Rectangle} area - The area of the emitter. Particles can be randomly generated from anywhere within this rectangle.
  78576. * @default
  78577. */
  78578. this.area = new Phaser.Rectangle(x, y, 1, 1);
  78579. /**
  78580. * @property {Phaser.Point} minParticleSpeed - The minimum possible velocity of a particle.
  78581. * @default
  78582. */
  78583. this.minParticleSpeed = new Phaser.Point(-100, -100);
  78584. /**
  78585. * @property {Phaser.Point} maxParticleSpeed - The maximum possible velocity of a particle.
  78586. * @default
  78587. */
  78588. this.maxParticleSpeed = new Phaser.Point(100, 100);
  78589. /**
  78590. * @property {number} minParticleScale - The minimum possible scale of a particle. This is applied to the X and Y axis. If you need to control each axis see minParticleScaleX.
  78591. * @default
  78592. */
  78593. this.minParticleScale = 1;
  78594. /**
  78595. * @property {number} maxParticleScale - The maximum possible scale of a particle. This is applied to the X and Y axis. If you need to control each axis see maxParticleScaleX.
  78596. * @default
  78597. */
  78598. this.maxParticleScale = 1;
  78599. /**
  78600. * @property {array} scaleData - An array of the calculated scale easing data applied to particles with scaleRates > 0.
  78601. */
  78602. this.scaleData = null;
  78603. /**
  78604. * @property {number} minRotation - The minimum possible angular velocity of a particle.
  78605. * @default
  78606. */
  78607. this.minRotation = -360;
  78608. /**
  78609. * @property {number} maxRotation - The maximum possible angular velocity of a particle.
  78610. * @default
  78611. */
  78612. this.maxRotation = 360;
  78613. /**
  78614. * @property {number} minParticleAlpha - The minimum possible alpha value of a particle.
  78615. * @default
  78616. */
  78617. this.minParticleAlpha = 1;
  78618. /**
  78619. * @property {number} maxParticleAlpha - The maximum possible alpha value of a particle.
  78620. * @default
  78621. */
  78622. this.maxParticleAlpha = 1;
  78623. /**
  78624. * @property {array} alphaData - An array of the calculated alpha easing data applied to particles with alphaRates > 0.
  78625. */
  78626. this.alphaData = null;
  78627. /**
  78628. * @property {number} gravity - Sets the `body.gravity.y` of each particle sprite to this value on launch.
  78629. * @default
  78630. */
  78631. this.gravity = 100;
  78632. /**
  78633. * @property {any} particleClass - For emitting your own particle class types. They must extend Phaser.Particle.
  78634. * @default
  78635. */
  78636. this.particleClass = Phaser.Particle;
  78637. /**
  78638. * @property {Phaser.Point} particleDrag - The X and Y drag component of particles launched from the emitter.
  78639. */
  78640. this.particleDrag = new Phaser.Point();
  78641. /**
  78642. * @property {number} angularDrag - The angular drag component of particles launched from the emitter if they are rotating.
  78643. * @default
  78644. */
  78645. this.angularDrag = 0;
  78646. /**
  78647. * @property {number} frequency - How often a particle is emitted in ms (if emitter is started with Explode === false).
  78648. * @default
  78649. */
  78650. this.frequency = 100;
  78651. /**
  78652. * @property {number} lifespan - How long each particle lives once it is emitted in ms. Default is 2 seconds. Set lifespan to 'zero' for particles to live forever.
  78653. * @default
  78654. */
  78655. this.lifespan = 2000;
  78656. /**
  78657. * @property {Phaser.Point} bounce - How much each particle should bounce on each axis. 1 = full bounce, 0 = no bounce.
  78658. */
  78659. this.bounce = new Phaser.Point();
  78660. /**
  78661. * @property {boolean} on - Determines whether the emitter is currently emitting particles. It is totally safe to directly toggle this.
  78662. * @default
  78663. */
  78664. this.on = false;
  78665. /**
  78666. * @property {Phaser.Point} particleAnchor - When a particle is created its anchor will be set to match this Point object (defaults to x/y: 0.5 to aid in rotation)
  78667. * @default
  78668. */
  78669. this.particleAnchor = new Phaser.Point(0.5, 0.5);
  78670. /**
  78671. * @property {number} blendMode - The blendMode as set on the particle when emitted from the Emitter. Defaults to NORMAL. Needs browser capable of supporting canvas blend-modes (most not available in WebGL)
  78672. * @default
  78673. */
  78674. this.blendMode = Phaser.blendModes.NORMAL;
  78675. /**
  78676. * The point the particles are emitted from.
  78677. * Emitter.x and Emitter.y control the containers location, which updates all current particles
  78678. * Emitter.emitX and Emitter.emitY control the emission location relative to the x/y position.
  78679. * @property {number} emitX
  78680. */
  78681. this.emitX = x;
  78682. /**
  78683. * The point the particles are emitted from.
  78684. * Emitter.x and Emitter.y control the containers location, which updates all current particles
  78685. * Emitter.emitX and Emitter.emitY control the emission location relative to the x/y position.
  78686. * @property {number} emitY
  78687. */
  78688. this.emitY = y;
  78689. /**
  78690. * @property {boolean} autoScale - When a new Particle is emitted this controls if it will automatically scale in size. Use Emitter.setScale to configure.
  78691. */
  78692. this.autoScale = false;
  78693. /**
  78694. * @property {boolean} autoAlpha - When a new Particle is emitted this controls if it will automatically change alpha. Use Emitter.setAlpha to configure.
  78695. */
  78696. this.autoAlpha = false;
  78697. /**
  78698. * @property {boolean} particleBringToTop - If this is `true` then when the Particle is emitted it will be bought to the top of the Emitters display list.
  78699. * @default
  78700. */
  78701. this.particleBringToTop = false;
  78702. /**
  78703. * @property {boolean} particleSendToBack - If this is `true` then when the Particle is emitted it will be sent to the back of the Emitters display list.
  78704. * @default
  78705. */
  78706. this.particleSendToBack = false;
  78707. /**
  78708. * @property {Phaser.Point} _minParticleScale - Internal particle scale var.
  78709. * @private
  78710. */
  78711. this._minParticleScale = new Phaser.Point(1, 1);
  78712. /**
  78713. * @property {Phaser.Point} _maxParticleScale - Internal particle scale var.
  78714. * @private
  78715. */
  78716. this._maxParticleScale = new Phaser.Point(1, 1);
  78717. /**
  78718. * @property {number} _quantity - Internal helper for deciding how many particles to launch.
  78719. * @private
  78720. */
  78721. this._quantity = 0;
  78722. /**
  78723. * @property {number} _timer - Internal helper for deciding when to launch particles or kill them.
  78724. * @private
  78725. */
  78726. this._timer = 0;
  78727. /**
  78728. * @property {number} _counter - Internal counter for figuring out how many particles to launch.
  78729. * @private
  78730. */
  78731. this._counter = 0;
  78732. /**
  78733. * @property {number} _flowQuantity - Internal counter for figuring out how many particles to launch per flow update.
  78734. * @private
  78735. */
  78736. this._flowQuantity = 0;
  78737. /**
  78738. * @property {number} _flowTotal - Internal counter for figuring out how many particles to launch in total.
  78739. * @private
  78740. */
  78741. this._flowTotal = 0;
  78742. /**
  78743. * @property {boolean} _explode - Internal helper for the style of particle emission (all at once, or one at a time).
  78744. * @private
  78745. */
  78746. this._explode = true;
  78747. /**
  78748. * @property {any} _frames - Internal helper for the particle frame.
  78749. * @private
  78750. */
  78751. this._frames = null;
  78752. };
  78753. Phaser.Particles.Arcade.Emitter.prototype = Object.create(Phaser.Group.prototype);
  78754. Phaser.Particles.Arcade.Emitter.prototype.constructor = Phaser.Particles.Arcade.Emitter;
  78755. /**
  78756. * Called automatically by the game loop, decides when to launch particles and when to "die".
  78757. *
  78758. * @method Phaser.Particles.Arcade.Emitter#update
  78759. */
  78760. Phaser.Particles.Arcade.Emitter.prototype.update = function () {
  78761. if (this.on && this.game.time.time >= this._timer)
  78762. {
  78763. this._timer = this.game.time.time + this.frequency * this.game.time.slowMotion;
  78764. if (this._flowTotal !== 0)
  78765. {
  78766. if (this._flowQuantity > 0)
  78767. {
  78768. for (var i = 0; i < this._flowQuantity; i++)
  78769. {
  78770. if (this.emitParticle())
  78771. {
  78772. this._counter++;
  78773. if (this._flowTotal !== -1 && this._counter >= this._flowTotal)
  78774. {
  78775. this.on = false;
  78776. break;
  78777. }
  78778. }
  78779. }
  78780. }
  78781. else
  78782. {
  78783. if (this.emitParticle())
  78784. {
  78785. this._counter++;
  78786. if (this._flowTotal !== -1 && this._counter >= this._flowTotal)
  78787. {
  78788. this.on = false;
  78789. }
  78790. }
  78791. }
  78792. }
  78793. else
  78794. {
  78795. if (this.emitParticle())
  78796. {
  78797. this._counter++;
  78798. if (this._quantity > 0 && this._counter >= this._quantity)
  78799. {
  78800. this.on = false;
  78801. }
  78802. }
  78803. }
  78804. }
  78805. var i = this.children.length;
  78806. while (i--)
  78807. {
  78808. if (this.children[i].exists)
  78809. {
  78810. this.children[i].update();
  78811. }
  78812. }
  78813. };
  78814. /**
  78815. * This function generates a new set of particles for use by this emitter.
  78816. * The particles are stored internally waiting to be emitted via Emitter.start.
  78817. *
  78818. * @method Phaser.Particles.Arcade.Emitter#makeParticles
  78819. * @param {array|string} keys - A string or an array of strings that the particle sprites will use as their texture. If an array one is picked at random.
  78820. * @param {array|number} [frames=0] - A frame number, or array of frames that the sprite will use. If an array one is picked at random.
  78821. * @param {number} [quantity] - The number of particles to generate. If not given it will use the value of Emitter.maxParticles. If the value is greater than Emitter.maxParticles it will use Emitter.maxParticles as the quantity.
  78822. * @param {boolean} [collide=false] - If you want the particles to be able to collide with other Arcade Physics bodies then set this to true.
  78823. * @param {boolean} [collideWorldBounds=false] - A particle 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.
  78824. * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance.
  78825. */
  78826. Phaser.Particles.Arcade.Emitter.prototype.makeParticles = function (keys, frames, quantity, collide, collideWorldBounds) {
  78827. if (frames === undefined) { frames = 0; }
  78828. if (quantity === undefined) { quantity = this.maxParticles; }
  78829. if (collide === undefined) { collide = false; }
  78830. if (collideWorldBounds === undefined) { collideWorldBounds = false; }
  78831. var particle;
  78832. var i = 0;
  78833. var rndKey = keys;
  78834. var rndFrame = frames;
  78835. this._frames = frames;
  78836. if (quantity > this.maxParticles)
  78837. {
  78838. this.maxParticles = quantity;
  78839. }
  78840. while (i < quantity)
  78841. {
  78842. if (Array.isArray(keys))
  78843. {
  78844. rndKey = this.game.rnd.pick(keys);
  78845. }
  78846. if (Array.isArray(frames))
  78847. {
  78848. rndFrame = this.game.rnd.pick(frames);
  78849. }
  78850. particle = new this.particleClass(this.game, 0, 0, rndKey, rndFrame);
  78851. this.game.physics.arcade.enable(particle, false);
  78852. if (collide)
  78853. {
  78854. particle.body.checkCollision.any = true;
  78855. particle.body.checkCollision.none = false;
  78856. }
  78857. else
  78858. {
  78859. particle.body.checkCollision.none = true;
  78860. }
  78861. particle.body.collideWorldBounds = collideWorldBounds;
  78862. particle.body.skipQuadTree = true;
  78863. particle.exists = false;
  78864. particle.visible = false;
  78865. particle.anchor.copyFrom(this.particleAnchor);
  78866. this.add(particle);
  78867. i++;
  78868. }
  78869. return this;
  78870. };
  78871. /**
  78872. * Call this function to turn off all the particles and the emitter.
  78873. *
  78874. * @method Phaser.Particles.Arcade.Emitter#kill
  78875. * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance.
  78876. */
  78877. Phaser.Particles.Arcade.Emitter.prototype.kill = function () {
  78878. this.on = false;
  78879. this.alive = false;
  78880. this.exists = false;
  78881. return this;
  78882. };
  78883. /**
  78884. * Handy for bringing game objects "back to life". Just sets alive and exists back to true.
  78885. *
  78886. * @method Phaser.Particles.Arcade.Emitter#revive
  78887. * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance.
  78888. */
  78889. Phaser.Particles.Arcade.Emitter.prototype.revive = function () {
  78890. this.alive = true;
  78891. this.exists = true;
  78892. return this;
  78893. };
  78894. /**
  78895. * Call this function to emit the given quantity of particles at all once (an explosion)
  78896. *
  78897. * @method Phaser.Particles.Arcade.Emitter#explode
  78898. * @param {number} [lifespan=0] - How long each particle lives once emitted in ms. 0 = forever.
  78899. * @param {number} [quantity=0] - How many particles to launch.
  78900. * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance.
  78901. */
  78902. Phaser.Particles.Arcade.Emitter.prototype.explode = function (lifespan, quantity) {
  78903. this._flowTotal = 0;
  78904. this.start(true, lifespan, 0, quantity, false);
  78905. return this;
  78906. };
  78907. /**
  78908. * Call this function to start emitting a flow of particles at the given frequency.
  78909. * It will carry on going until the total given is reached.
  78910. * Each time the flow is run the quantity number of particles will be emitted together.
  78911. * If you set the total to be 20 and quantity to be 5 then flow will emit 4 times in total (4 x 5 = 20 total)
  78912. * If you set the total to be -1 then no quantity cap is used and it will keep emitting.
  78913. *
  78914. * @method Phaser.Particles.Arcade.Emitter#flow
  78915. * @param {number} [lifespan=0] - How long each particle lives once emitted in ms. 0 = forever.
  78916. * @param {number} [frequency=250] - Frequency is how often to emit the particles, given in ms.
  78917. * @param {number} [quantity=1] - How many particles to launch each time the frequency is met. Can never be > Emitter.maxParticles.
  78918. * @param {number} [total=-1] - How many particles to launch in total. If -1 it will carry on indefinitely.
  78919. * @param {boolean} [immediate=true] - Should the flow start immediately (true) or wait until the first frequency event? (false)
  78920. * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance.
  78921. */
  78922. Phaser.Particles.Arcade.Emitter.prototype.flow = function (lifespan, frequency, quantity, total, immediate) {
  78923. if (quantity === undefined || quantity === 0) { quantity = 1; }
  78924. if (total === undefined) { total = -1; }
  78925. if (immediate === undefined) { immediate = true; }
  78926. if (quantity > this.maxParticles)
  78927. {
  78928. quantity = this.maxParticles;
  78929. }
  78930. this._counter = 0;
  78931. this._flowQuantity = quantity;
  78932. this._flowTotal = total;
  78933. if (immediate)
  78934. {
  78935. this.start(true, lifespan, frequency, quantity);
  78936. this._counter += quantity;
  78937. this.on = true;
  78938. this._timer = this.game.time.time + frequency * this.game.time.slowMotion;
  78939. }
  78940. else
  78941. {
  78942. this.start(false, lifespan, frequency, quantity);
  78943. }
  78944. return this;
  78945. };
  78946. /**
  78947. * Call this function to start emitting particles.
  78948. *
  78949. * @method Phaser.Particles.Arcade.Emitter#start
  78950. * @param {boolean} [explode=true] - Whether the particles should all burst out at once (true) or at the frequency given (false).
  78951. * @param {number} [lifespan=0] - How long each particle lives once emitted in ms. 0 = forever.
  78952. * @param {number} [frequency=250] - Ignored if Explode is set to true. Frequency is how often to emit 1 particle. Value given in ms.
  78953. * @param {number} [quantity=0] - How many particles to launch. 0 = "all of the particles" which will keep emitting until Emitter.maxParticles is reached.
  78954. * @param {number} [forceQuantity=false] - If `true` and creating a particle flow, the quantity emitted will be forced to the be quantity given in this call. This can never exceed Emitter.maxParticles.
  78955. * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance.
  78956. */
  78957. Phaser.Particles.Arcade.Emitter.prototype.start = function (explode, lifespan, frequency, quantity, forceQuantity) {
  78958. if (explode === undefined) { explode = true; }
  78959. if (lifespan === undefined) { lifespan = 0; }
  78960. if (frequency === undefined || frequency === null) { frequency = 250; }
  78961. if (quantity === undefined) { quantity = 0; }
  78962. if (forceQuantity === undefined) { forceQuantity = false; }
  78963. if (quantity > this.maxParticles)
  78964. {
  78965. quantity = this.maxParticles;
  78966. }
  78967. this.revive();
  78968. this.visible = true;
  78969. this.lifespan = lifespan;
  78970. this.frequency = frequency;
  78971. if (explode || forceQuantity)
  78972. {
  78973. for (var i = 0; i < quantity; i++)
  78974. {
  78975. this.emitParticle();
  78976. }
  78977. }
  78978. else
  78979. {
  78980. this.on = true;
  78981. this._quantity = quantity;
  78982. this._counter = 0;
  78983. this._timer = this.game.time.time + frequency * this.game.time.slowMotion;
  78984. }
  78985. return this;
  78986. };
  78987. /**
  78988. * This function is used internally to emit the next particle in the queue.
  78989. *
  78990. * However it can also be called externally to emit a particle.
  78991. *
  78992. * When called externally you can use the arguments to override any defaults the Emitter has set.
  78993. *
  78994. * @method Phaser.Particles.Arcade.Emitter#emitParticle
  78995. * @param {number} [x] - The x coordinate to emit the particle from. If `null` or `undefined` it will use `Emitter.emitX` or if the Emitter has a width > 1 a random value between `Emitter.left` and `Emitter.right`.
  78996. * @param {number} [y] - The y coordinate to emit the particle from. If `null` or `undefined` it will use `Emitter.emitY` or if the Emitter has a height > 1 a random value between `Emitter.top` and `Emitter.bottom`.
  78997. * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Particle during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture.
  78998. * @param {string|number} [frame] - If this Particle 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.
  78999. * @return {boolean} True if a particle was emitted, otherwise false.
  79000. */
  79001. Phaser.Particles.Arcade.Emitter.prototype.emitParticle = function (x, y, key, frame) {
  79002. if (x === undefined) { x = null; }
  79003. if (y === undefined) { y = null; }
  79004. var particle = this.getFirstExists(false);
  79005. if (particle === null)
  79006. {
  79007. return false;
  79008. }
  79009. var rnd = this.game.rnd;
  79010. if (key !== undefined && frame !== undefined)
  79011. {
  79012. particle.loadTexture(key, frame);
  79013. }
  79014. else if (key !== undefined)
  79015. {
  79016. particle.loadTexture(key);
  79017. }
  79018. var emitX = this.emitX;
  79019. var emitY = this.emitY;
  79020. if (x !== null)
  79021. {
  79022. emitX = x;
  79023. }
  79024. else if (this.width > 1)
  79025. {
  79026. emitX = rnd.between(this.left, this.right);
  79027. }
  79028. if (y !== null)
  79029. {
  79030. emitY = y;
  79031. }
  79032. else if (this.height > 1)
  79033. {
  79034. emitY = rnd.between(this.top, this.bottom);
  79035. }
  79036. particle.reset(emitX, emitY);
  79037. particle.angle = 0;
  79038. particle.lifespan = this.lifespan;
  79039. if (this.particleBringToTop)
  79040. {
  79041. this.bringToTop(particle);
  79042. }
  79043. else if (this.particleSendToBack)
  79044. {
  79045. this.sendToBack(particle);
  79046. }
  79047. if (this.autoScale)
  79048. {
  79049. particle.setScaleData(this.scaleData);
  79050. }
  79051. else if (this.minParticleScale !== 1 || this.maxParticleScale !== 1)
  79052. {
  79053. particle.scale.set(rnd.realInRange(this.minParticleScale, this.maxParticleScale));
  79054. }
  79055. else if ((this._minParticleScale.x !== this._maxParticleScale.x) || (this._minParticleScale.y !== this._maxParticleScale.y))
  79056. {
  79057. particle.scale.set(rnd.realInRange(this._minParticleScale.x, this._maxParticleScale.x), rnd.realInRange(this._minParticleScale.y, this._maxParticleScale.y));
  79058. }
  79059. if (frame === undefined)
  79060. {
  79061. if (Array.isArray(this._frames))
  79062. {
  79063. particle.frame = this.game.rnd.pick(this._frames);
  79064. }
  79065. else
  79066. {
  79067. particle.frame = this._frames;
  79068. }
  79069. }
  79070. if (this.autoAlpha)
  79071. {
  79072. particle.setAlphaData(this.alphaData);
  79073. }
  79074. else
  79075. {
  79076. particle.alpha = rnd.realInRange(this.minParticleAlpha, this.maxParticleAlpha);
  79077. }
  79078. particle.blendMode = this.blendMode;
  79079. var body = particle.body;
  79080. body.updateBounds();
  79081. body.bounce.copyFrom(this.bounce);
  79082. body.drag.copyFrom(this.particleDrag);
  79083. body.velocity.x = rnd.between(this.minParticleSpeed.x, this.maxParticleSpeed.x);
  79084. body.velocity.y = rnd.between(this.minParticleSpeed.y, this.maxParticleSpeed.y);
  79085. body.angularVelocity = rnd.between(this.minRotation, this.maxRotation);
  79086. body.gravity.y = this.gravity;
  79087. body.angularDrag = this.angularDrag;
  79088. particle.onEmit();
  79089. return true;
  79090. };
  79091. /**
  79092. * Destroys this Emitter, all associated child Particles and then removes itself from the Particle Manager.
  79093. *
  79094. * @method Phaser.Particles.Arcade.Emitter#destroy
  79095. */
  79096. Phaser.Particles.Arcade.Emitter.prototype.destroy = function () {
  79097. this.game.particles.remove(this);
  79098. Phaser.Group.prototype.destroy.call(this, true, false);
  79099. };
  79100. /**
  79101. * A more compact way of setting the width and height of the emitter.
  79102. *
  79103. * @method Phaser.Particles.Arcade.Emitter#setSize
  79104. * @param {number} width - The desired width of the emitter (particles are spawned randomly within these dimensions).
  79105. * @param {number} height - The desired height of the emitter.
  79106. * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance.
  79107. */
  79108. Phaser.Particles.Arcade.Emitter.prototype.setSize = function (width, height) {
  79109. this.area.width = width;
  79110. this.area.height = height;
  79111. return this;
  79112. };
  79113. /**
  79114. * A more compact way of setting the X velocity range of the emitter.
  79115. * @method Phaser.Particles.Arcade.Emitter#setXSpeed
  79116. * @param {number} [min=0] - The minimum value for this range.
  79117. * @param {number} [max=0] - The maximum value for this range.
  79118. * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance.
  79119. */
  79120. Phaser.Particles.Arcade.Emitter.prototype.setXSpeed = function (min, max) {
  79121. min = min || 0;
  79122. max = max || 0;
  79123. this.minParticleSpeed.x = min;
  79124. this.maxParticleSpeed.x = max;
  79125. return this;
  79126. };
  79127. /**
  79128. * A more compact way of setting the Y velocity range of the emitter.
  79129. * @method Phaser.Particles.Arcade.Emitter#setYSpeed
  79130. * @param {number} [min=0] - The minimum value for this range.
  79131. * @param {number} [max=0] - The maximum value for this range.
  79132. * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance.
  79133. */
  79134. Phaser.Particles.Arcade.Emitter.prototype.setYSpeed = function (min, max) {
  79135. min = min || 0;
  79136. max = max || 0;
  79137. this.minParticleSpeed.y = min;
  79138. this.maxParticleSpeed.y = max;
  79139. return this;
  79140. };
  79141. /**
  79142. * A more compact way of setting the angular velocity constraints of the particles.
  79143. *
  79144. * @method Phaser.Particles.Arcade.Emitter#setRotation
  79145. * @param {number} [min=0] - The minimum value for this range.
  79146. * @param {number} [max=0] - The maximum value for this range.
  79147. * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance.
  79148. */
  79149. Phaser.Particles.Arcade.Emitter.prototype.setRotation = function (min, max) {
  79150. min = min || 0;
  79151. max = max || 0;
  79152. this.minRotation = min;
  79153. this.maxRotation = max;
  79154. return this;
  79155. };
  79156. /**
  79157. * A more compact way of setting the alpha constraints of the particles.
  79158. * The rate parameter, if set to a value above zero, lets you set the speed at which the Particle change in alpha from min to max.
  79159. * If rate is zero, which is the default, the particle won't change alpha - instead it will pick a random alpha between min and max on emit.
  79160. *
  79161. * @method Phaser.Particles.Arcade.Emitter#setAlpha
  79162. * @param {number} [min=1] - The minimum value for this range.
  79163. * @param {number} [max=1] - The maximum value for this range.
  79164. * @param {number} [rate=0] - The rate (in ms) at which the particles will change in alpha from min to max, or set to zero to pick a random alpha between the two.
  79165. * @param {function} [ease=Phaser.Easing.Linear.None] - If you've set a rate > 0 this is the easing formula applied between the min and max values.
  79166. * @param {boolean} [yoyo=false] - If you've set a rate > 0 you can set if the ease will yoyo or not (i.e. ease back to its original values)
  79167. * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance.
  79168. */
  79169. Phaser.Particles.Arcade.Emitter.prototype.setAlpha = function (min, max, rate, ease, yoyo) {
  79170. if (min === undefined) { min = 1; }
  79171. if (max === undefined) { max = 1; }
  79172. if (rate === undefined) { rate = 0; }
  79173. if (ease === undefined) { ease = Phaser.Easing.Linear.None; }
  79174. if (yoyo === undefined) { yoyo = false; }
  79175. this.minParticleAlpha = min;
  79176. this.maxParticleAlpha = max;
  79177. this.autoAlpha = false;
  79178. if (rate > 0 && min !== max)
  79179. {
  79180. var tweenData = { v: min };
  79181. var tween = this.game.make.tween(tweenData).to( { v: max }, rate, ease);
  79182. tween.yoyo(yoyo);
  79183. this.alphaData = tween.generateData(60);
  79184. // Inverse it so we don't have to do array length look-ups in Particle update loops
  79185. this.alphaData.reverse();
  79186. this.autoAlpha = true;
  79187. }
  79188. return this;
  79189. };
  79190. /**
  79191. * A more compact way of setting the scale constraints of the particles.
  79192. * The rate parameter, if set to a value above zero, lets you set the speed and ease which the Particle uses to change in scale from min to max across both axis.
  79193. * If rate is zero, which is the default, the particle won't change scale during update, instead it will pick a random scale between min and max on emit.
  79194. *
  79195. * @method Phaser.Particles.Arcade.Emitter#setScale
  79196. * @param {number} [minX=1] - The minimum value of Particle.scale.x.
  79197. * @param {number} [maxX=1] - The maximum value of Particle.scale.x.
  79198. * @param {number} [minY=1] - The minimum value of Particle.scale.y.
  79199. * @param {number} [maxY=1] - The maximum value of Particle.scale.y.
  79200. * @param {number} [rate=0] - The rate (in ms) at which the particles will change in scale from min to max, or set to zero to pick a random size between the two.
  79201. * @param {function} [ease=Phaser.Easing.Linear.None] - If you've set a rate > 0 this is the easing formula applied between the min and max values.
  79202. * @param {boolean} [yoyo=false] - If you've set a rate > 0 you can set if the ease will yoyo or not (i.e. ease back to its original values)
  79203. * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance.
  79204. */
  79205. Phaser.Particles.Arcade.Emitter.prototype.setScale = function (minX, maxX, minY, maxY, rate, ease, yoyo) {
  79206. if (minX === undefined) { minX = 1; }
  79207. if (maxX === undefined) { maxX = 1; }
  79208. if (minY === undefined) { minY = 1; }
  79209. if (maxY === undefined) { maxY = 1; }
  79210. if (rate === undefined) { rate = 0; }
  79211. if (ease === undefined) { ease = Phaser.Easing.Linear.None; }
  79212. if (yoyo === undefined) { yoyo = false; }
  79213. // Reset these
  79214. this.minParticleScale = 1;
  79215. this.maxParticleScale = 1;
  79216. this._minParticleScale.set(minX, minY);
  79217. this._maxParticleScale.set(maxX, maxY);
  79218. this.autoScale = false;
  79219. if (rate > 0 && ((minX !== maxX) || (minY !== maxY)))
  79220. {
  79221. var tweenData = { x: minX, y: minY };
  79222. var tween = this.game.make.tween(tweenData).to( { x: maxX, y: maxY }, rate, ease);
  79223. tween.yoyo(yoyo);
  79224. this.scaleData = tween.generateData(60);
  79225. // Inverse it so we don't have to do array length look-ups in Particle update loops
  79226. this.scaleData.reverse();
  79227. this.autoScale = true;
  79228. }
  79229. return this;
  79230. };
  79231. /**
  79232. * Change the emitters center to match the center of any object with a `center` property, such as a Sprite.
  79233. * If the object doesn't have a center property it will be set to object.x + object.width / 2
  79234. *
  79235. * @method Phaser.Particles.Arcade.Emitter#at
  79236. * @param {object|Phaser.Sprite|Phaser.Image|Phaser.TileSprite|Phaser.Text|PIXI.DisplayObject} object - The object that you wish to match the center with.
  79237. * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance.
  79238. */
  79239. Phaser.Particles.Arcade.Emitter.prototype.at = function (object) {
  79240. if (object.center)
  79241. {
  79242. this.emitX = object.center.x;
  79243. this.emitY = object.center.y;
  79244. }
  79245. else
  79246. {
  79247. this.emitX = object.world.x + (object.anchor.x * object.width);
  79248. this.emitY = object.world.y + (object.anchor.y * object.height);
  79249. }
  79250. return this;
  79251. };
  79252. /**
  79253. * @name Phaser.Particles.Arcade.Emitter#width
  79254. * @property {number} width - Gets or sets the width of the Emitter. This is the region in which a particle can be emitted.
  79255. */
  79256. Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "width", {
  79257. get: function () {
  79258. return this.area.width;
  79259. },
  79260. set: function (value) {
  79261. this.area.width = value;
  79262. }
  79263. });
  79264. /**
  79265. * @name Phaser.Particles.Arcade.Emitter#height
  79266. * @property {number} height - Gets or sets the height of the Emitter. This is the region in which a particle can be emitted.
  79267. */
  79268. Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "height", {
  79269. get: function () {
  79270. return this.area.height;
  79271. },
  79272. set: function (value) {
  79273. this.area.height = value;
  79274. }
  79275. });
  79276. /**
  79277. * @name Phaser.Particles.Arcade.Emitter#x
  79278. * @property {number} x - Gets or sets the x position of the Emitter.
  79279. */
  79280. Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "x", {
  79281. get: function () {
  79282. return this.emitX;
  79283. },
  79284. set: function (value) {
  79285. this.emitX = value;
  79286. }
  79287. });
  79288. /**
  79289. * @name Phaser.Particles.Arcade.Emitter#y
  79290. * @property {number} y - Gets or sets the y position of the Emitter.
  79291. */
  79292. Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "y", {
  79293. get: function () {
  79294. return this.emitY;
  79295. },
  79296. set: function (value) {
  79297. this.emitY = value;
  79298. }
  79299. });
  79300. /**
  79301. * @name Phaser.Particles.Arcade.Emitter#left
  79302. * @property {number} left - Gets the left position of the Emitter.
  79303. * @readonly
  79304. */
  79305. Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "left", {
  79306. get: function () {
  79307. return Math.floor(this.x - (this.area.width / 2));
  79308. }
  79309. });
  79310. /**
  79311. * @name Phaser.Particles.Arcade.Emitter#right
  79312. * @property {number} right - Gets the right position of the Emitter.
  79313. * @readonly
  79314. */
  79315. Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "right", {
  79316. get: function () {
  79317. return Math.floor(this.x + (this.area.width / 2));
  79318. }
  79319. });
  79320. /**
  79321. * @name Phaser.Particles.Arcade.Emitter#top
  79322. * @property {number} top - Gets the top position of the Emitter.
  79323. * @readonly
  79324. */
  79325. Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "top", {
  79326. get: function () {
  79327. return Math.floor(this.y - (this.area.height / 2));
  79328. }
  79329. });
  79330. /**
  79331. * @name Phaser.Particles.Arcade.Emitter#bottom
  79332. * @property {number} bottom - Gets the bottom position of the Emitter.
  79333. * @readonly
  79334. */
  79335. Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "bottom", {
  79336. get: function () {
  79337. return Math.floor(this.y + (this.area.height / 2));
  79338. }
  79339. });
  79340. /**
  79341. * @author Richard Davey <rich@photonstorm.com>
  79342. * @copyright 2016 Photon Storm Ltd.
  79343. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  79344. */
  79345. /**
  79346. * A Video object that takes a previously loaded Video from the Phaser Cache and handles playback of it.
  79347. *
  79348. * Alternatively it takes a getUserMedia feed from an active webcam and streams the contents of that to
  79349. * the Video instead (see `startMediaStream` method)
  79350. *
  79351. * The video can then be applied to a Sprite as a texture. If multiple Sprites share the same Video texture and playback
  79352. * changes (i.e. you pause the video, or seek to a new time) then this change will be seen across all Sprites simultaneously.
  79353. *
  79354. * Due to a bug in IE11 you cannot play a video texture to a Sprite in WebGL. For IE11 force Canvas mode.
  79355. *
  79356. * If you need each Sprite to be able to play a video fully independently then you will need one Video object per Sprite.
  79357. * Please understand the obvious performance implications of doing this, and the memory required to hold videos in RAM.
  79358. *
  79359. * On some mobile browsers such as iOS Safari, you cannot play a video until the user has explicitly touched the screen.
  79360. * This works in the same way as audio unlocking. Phaser will handle the touch unlocking for you, however unlike with audio
  79361. * it's worth noting that every single Video needs to be touch unlocked, not just the first one. You can use the `changeSource`
  79362. * method to try and work around this limitation, but see the method help for details.
  79363. *
  79364. * Small screen devices, especially iPod and iPhone will launch the video in its own native video player,
  79365. * outside of the Safari browser. There is no way to avoid this, it's a device imposed limitation.
  79366. *
  79367. * @class Phaser.Video
  79368. * @constructor
  79369. * @param {Phaser.Game} game - A reference to the currently running game.
  79370. * @param {string|null} [key=null] - The key of the video file in the Phaser.Cache that this Video object will play. Set to `null` or leave undefined if you wish to use a webcam as the source. See `startMediaStream` to start webcam capture.
  79371. * @param {string|null} [url=null] - If the video hasn't been loaded then you can provide a full URL to the file here (make sure to set key to null)
  79372. */
  79373. Phaser.Video = function (game, key, url) {
  79374. if (key === undefined) { key = null; }
  79375. if (url === undefined) { url = null; }
  79376. /**
  79377. * @property {Phaser.Game} game - A reference to the currently running game.
  79378. */
  79379. this.game = game;
  79380. /**
  79381. * @property {string} key - The key of the Video in the Cache, if stored there. Will be `null` if this Video is using the webcam instead.
  79382. * @default null
  79383. */
  79384. this.key = key;
  79385. /**
  79386. * @property {number} width - The width of the video in pixels.
  79387. * @default
  79388. */
  79389. this.width = 0;
  79390. /**
  79391. * @property {number} height - The height of the video in pixels.
  79392. * @default
  79393. */
  79394. this.height = 0;
  79395. /**
  79396. * @property {number} type - The const type of this object.
  79397. * @default
  79398. */
  79399. this.type = Phaser.VIDEO;
  79400. /**
  79401. * @property {boolean} disableTextureUpload - If true this video will never send its image data to the GPU when its dirty flag is true. This only applies in WebGL.
  79402. */
  79403. this.disableTextureUpload = false;
  79404. /**
  79405. * @property {boolean} touchLocked - true if this video is currently locked awaiting a touch event. This happens on some mobile devices, such as iOS.
  79406. * @default
  79407. */
  79408. this.touchLocked = false;
  79409. /**
  79410. * @property {Phaser.Signal} onPlay - This signal is dispatched when the Video starts to play. It sends 3 parameters: a reference to the Video object, if the video is set to loop or not and the playback rate.
  79411. */
  79412. this.onPlay = new Phaser.Signal();
  79413. /**
  79414. * @property {Phaser.Signal} onChangeSource - This signal is dispatched if the Video source is changed. It sends 3 parameters: a reference to the Video object and the new width and height of the new video source.
  79415. */
  79416. this.onChangeSource = new Phaser.Signal();
  79417. /**
  79418. * @property {Phaser.Signal} onComplete - This signal is dispatched when the Video completes playback, i.e. enters an 'ended' state. Videos set to loop will never dispatch this signal.
  79419. */
  79420. this.onComplete = new Phaser.Signal();
  79421. /**
  79422. * @property {Phaser.Signal} onAccess - This signal is dispatched if the user allows access to their webcam.
  79423. */
  79424. this.onAccess = new Phaser.Signal();
  79425. /**
  79426. * @property {Phaser.Signal} onError - This signal is dispatched if an error occurs either getting permission to use the webcam (for a Video Stream) or when trying to play back a video file.
  79427. */
  79428. this.onError = new Phaser.Signal();
  79429. /**
  79430. * This signal is dispatched if when asking for permission to use the webcam no response is given within a the Video.timeout limit.
  79431. * This may be because the user has picked `Not now` in the permissions window, or there is a delay in establishing the LocalMediaStream.
  79432. * @property {Phaser.Signal} onTimeout
  79433. */
  79434. this.onTimeout = new Phaser.Signal();
  79435. /**
  79436. * @property {integer} timeout - The amount of ms allowed to elapsed before the Video.onTimeout signal is dispatched while waiting for webcam access.
  79437. * @default
  79438. */
  79439. this.timeout = 15000;
  79440. /**
  79441. * @property {integer} _timeOutID - setTimeout ID.
  79442. * @private
  79443. */
  79444. this._timeOutID = null;
  79445. /**
  79446. * @property {HTMLVideoElement} video - The HTML Video Element that is added to the document.
  79447. */
  79448. this.video = null;
  79449. /**
  79450. * @property {MediaStream} videoStream - The Video Stream data. Only set if this Video is streaming from the webcam via `startMediaStream`.
  79451. */
  79452. this.videoStream = null;
  79453. /**
  79454. * @property {boolean} isStreaming - Is there a streaming video source? I.e. from a webcam.
  79455. */
  79456. this.isStreaming = false;
  79457. /**
  79458. * When starting playback of a video Phaser will monitor its readyState using a setTimeout call.
  79459. * The setTimeout happens once every `Video.retryInterval` ms. It will carry on monitoring the video
  79460. * state in this manner until the `retryLimit` is reached and then abort.
  79461. * @property {integer} retryLimit
  79462. * @default
  79463. */
  79464. this.retryLimit = 20;
  79465. /**
  79466. * @property {integer} retry - The current retry attempt.
  79467. * @default
  79468. */
  79469. this.retry = 0;
  79470. /**
  79471. * @property {integer} retryInterval - The number of ms between each retry at monitoring the status of a downloading video.
  79472. * @default
  79473. */
  79474. this.retryInterval = 500;
  79475. /**
  79476. * @property {integer} _retryID - The callback ID of the retry setTimeout.
  79477. * @private
  79478. */
  79479. this._retryID = null;
  79480. /**
  79481. * @property {boolean} _codeMuted - Internal mute tracking var.
  79482. * @private
  79483. * @default
  79484. */
  79485. this._codeMuted = false;
  79486. /**
  79487. * @property {boolean} _muted - Internal mute tracking var.
  79488. * @private
  79489. * @default
  79490. */
  79491. this._muted = false;
  79492. /**
  79493. * @property {boolean} _codePaused - Internal paused tracking var.
  79494. * @private
  79495. * @default
  79496. */
  79497. this._codePaused = false;
  79498. /**
  79499. * @property {boolean} _paused - Internal paused tracking var.
  79500. * @private
  79501. * @default
  79502. */
  79503. this._paused = false;
  79504. /**
  79505. * @property {boolean} _pending - Internal var tracking play pending.
  79506. * @private
  79507. * @default
  79508. */
  79509. this._pending = false;
  79510. /**
  79511. * @property {boolean} _autoplay - Internal var tracking autoplay when changing source.
  79512. * @private
  79513. * @default
  79514. */
  79515. this._autoplay = false;
  79516. /**
  79517. * @property {function} _endCallback - The addEventListener ended function.
  79518. * @private
  79519. */
  79520. this._endCallback = null;
  79521. /**
  79522. * @property {function} _playCallback - The addEventListener playing function.
  79523. * @private
  79524. */
  79525. this._playCallback = null;
  79526. if (key && this.game.cache.checkVideoKey(key))
  79527. {
  79528. var _video = this.game.cache.getVideo(key);
  79529. if (_video.isBlob)
  79530. {
  79531. this.createVideoFromBlob(_video.data);
  79532. }
  79533. else
  79534. {
  79535. this.video = _video.data;
  79536. }
  79537. this.width = this.video.videoWidth;
  79538. this.height = this.video.videoHeight;
  79539. }
  79540. else if (url)
  79541. {
  79542. this.createVideoFromURL(url, false);
  79543. }
  79544. /**
  79545. * @property {PIXI.BaseTexture} baseTexture - The PIXI.BaseTexture.
  79546. * @default
  79547. */
  79548. if (this.video && !url)
  79549. {
  79550. this.baseTexture = new PIXI.BaseTexture(this.video);
  79551. this.baseTexture.forceLoaded(this.width, this.height);
  79552. }
  79553. else
  79554. {
  79555. this.baseTexture = new PIXI.BaseTexture(PIXI.TextureCache['__default'].baseTexture.source);
  79556. this.baseTexture.forceLoaded(this.width, this.height);
  79557. }
  79558. /**
  79559. * @property {PIXI.Texture} texture - The PIXI.Texture.
  79560. * @default
  79561. */
  79562. this.texture = new PIXI.Texture(this.baseTexture);
  79563. /**
  79564. * @property {Phaser.Frame} textureFrame - The Frame this video uses for rendering.
  79565. * @default
  79566. */
  79567. this.textureFrame = new Phaser.Frame(0, 0, 0, this.width, this.height, 'video');
  79568. this.texture.setFrame(this.textureFrame);
  79569. this.texture.valid = false;
  79570. if (key !== null && this.video)
  79571. {
  79572. this.texture.valid = this.video.canplay;
  79573. }
  79574. /**
  79575. * A snapshot grabbed from the video. This is initially black. Populate it by calling Video.grab().
  79576. * When called the BitmapData is updated with a grab taken from the current video playing or active video stream.
  79577. * If Phaser has been compiled without BitmapData support this property will always be `null`.
  79578. *
  79579. * @property {Phaser.BitmapData} snapshot
  79580. * @readOnly
  79581. */
  79582. this.snapshot = null;
  79583. if (Phaser.BitmapData)
  79584. {
  79585. this.snapshot = new Phaser.BitmapData(this.game, '', this.width, this.height);
  79586. }
  79587. if (!this.game.device.cocoonJS && (this.game.device.iOS || this.game.device.android) || (window['PhaserGlobal'] && window['PhaserGlobal'].fakeiOSTouchLock))
  79588. {
  79589. this.setTouchLock();
  79590. }
  79591. else
  79592. {
  79593. if (_video)
  79594. {
  79595. _video.locked = false;
  79596. }
  79597. }
  79598. };
  79599. Phaser.Video.prototype = {
  79600. /**
  79601. * Connects to an external media stream for the webcam, rather than using a local one.
  79602. *
  79603. * @method Phaser.Video#connectToMediaStream
  79604. * @param {HTMLVideoElement} video - The HTML Video Element that the stream uses.
  79605. * @param {MediaStream} stream - The Video Stream data.
  79606. * @return {Phaser.Video} This Video object for method chaining.
  79607. */
  79608. connectToMediaStream: function (video, stream) {
  79609. if (video && stream)
  79610. {
  79611. this.video = video;
  79612. this.videoStream = stream;
  79613. this.isStreaming = true;
  79614. this.baseTexture.source = this.video;
  79615. this.updateTexture(null, this.video.videoWidth, this.video.videoHeight);
  79616. this.onAccess.dispatch(this);
  79617. }
  79618. return this;
  79619. },
  79620. /**
  79621. * Instead of playing a video file this method allows you to stream video data from an attached webcam.
  79622. *
  79623. * As soon as this method is called the user will be prompted by their browser to "Allow" access to the webcam.
  79624. * If they allow it the webcam feed is directed to this Video. Call `Video.play` to start the stream.
  79625. *
  79626. * If they block the webcam the onError signal will be dispatched containing the NavigatorUserMediaError
  79627. * or MediaStreamError event.
  79628. *
  79629. * You can optionally set a width and height for the stream. If set the input will be cropped to these dimensions.
  79630. * If not given then as soon as the stream has enough data the video dimensions will be changed to match the webcam device.
  79631. * You can listen for this with the onChangeSource signal.
  79632. *
  79633. * @method Phaser.Video#startMediaStream
  79634. * @param {boolean} [captureAudio=false] - Controls if audio should be captured along with video in the video stream.
  79635. * @param {integer} [width] - The width is used to create the video stream. If not provided the video width will be set to the width of the webcam input source.
  79636. * @param {integer} [height] - The height is used to create the video stream. If not provided the video height will be set to the height of the webcam input source.
  79637. * @return {Phaser.Video} This Video object for method chaining or false if the device doesn't support getUserMedia.
  79638. */
  79639. startMediaStream: function (captureAudio, width, height) {
  79640. if (captureAudio === undefined) { captureAudio = false; }
  79641. if (width === undefined) { width = null; }
  79642. if (height === undefined) { height = null; }
  79643. if (!this.game.device.getUserMedia)
  79644. {
  79645. this.onError.dispatch(this, 'No getUserMedia');
  79646. return false;
  79647. }
  79648. if (this.videoStream !== null)
  79649. {
  79650. if (this.videoStream['active'])
  79651. {
  79652. this.videoStream.active = false;
  79653. }
  79654. else
  79655. {
  79656. this.videoStream.stop();
  79657. }
  79658. }
  79659. this.removeVideoElement();
  79660. this.video = document.createElement("video");
  79661. this.video.setAttribute('autoplay', 'autoplay');
  79662. if (width !== null)
  79663. {
  79664. this.video.width = width;
  79665. }
  79666. if (height !== null)
  79667. {
  79668. this.video.height = height;
  79669. }
  79670. // Request access to the webcam
  79671. this._timeOutID = window.setTimeout(this.getUserMediaTimeout.bind(this), this.timeout);
  79672. try {
  79673. navigator.getUserMedia(
  79674. { "audio": captureAudio, "video": true },
  79675. this.getUserMediaSuccess.bind(this),
  79676. this.getUserMediaError.bind(this)
  79677. );
  79678. }
  79679. catch (error)
  79680. {
  79681. this.getUserMediaError(error);
  79682. }
  79683. return this;
  79684. },
  79685. /**
  79686. * @method Phaser.Video#getUserMediaTimeout
  79687. * @private
  79688. */
  79689. getUserMediaTimeout: function () {
  79690. clearTimeout(this._timeOutID);
  79691. this.onTimeout.dispatch(this);
  79692. },
  79693. /**
  79694. * @method Phaser.Video#getUserMediaError
  79695. * @private
  79696. */
  79697. getUserMediaError: function (event) {
  79698. clearTimeout(this._timeOutID);
  79699. this.onError.dispatch(this, event);
  79700. },
  79701. /**
  79702. * @method Phaser.Video#getUserMediaSuccess
  79703. * @private
  79704. */
  79705. getUserMediaSuccess: function (stream) {
  79706. clearTimeout(this._timeOutID);
  79707. // Attach the stream to the video
  79708. this.videoStream = stream;
  79709. // Set the source of the video element with the stream from the camera
  79710. if (this.video.mozSrcObject !== undefined)
  79711. {
  79712. this.video.mozSrcObject = stream;
  79713. }
  79714. else
  79715. {
  79716. this.video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  79717. }
  79718. var self = this;
  79719. this.video.onloadeddata = function () {
  79720. var retry = 10;
  79721. function checkStream () {
  79722. if (retry > 0)
  79723. {
  79724. if (self.video.videoWidth > 0)
  79725. {
  79726. // Patch for Firefox bug where the height can't be read from the video
  79727. var width = self.video.videoWidth;
  79728. var height = self.video.videoHeight;
  79729. if (isNaN(self.video.videoHeight))
  79730. {
  79731. height = width / (4/3);
  79732. }
  79733. self.video.play();
  79734. self.isStreaming = true;
  79735. self.baseTexture.source = self.video;
  79736. self.updateTexture(null, width, height);
  79737. self.onAccess.dispatch(self);
  79738. }
  79739. else
  79740. {
  79741. window.setTimeout(checkStream, 500);
  79742. }
  79743. }
  79744. else
  79745. {
  79746. console.warn('Unable to connect to video stream. Webcam error?');
  79747. }
  79748. retry--;
  79749. }
  79750. checkStream();
  79751. };
  79752. },
  79753. /**
  79754. * Creates a new Video element from the given Blob. The Blob must contain the video data in the correct encoded format.
  79755. * This method is typically called by the Phaser.Loader and Phaser.Cache for you, but is exposed publicly for convenience.
  79756. *
  79757. * @method Phaser.Video#createVideoFromBlob
  79758. * @param {Blob} blob - The Blob containing the video data: `Blob([new Uint8Array(data)])`
  79759. * @return {Phaser.Video} This Video object for method chaining.
  79760. */
  79761. createVideoFromBlob: function (blob) {
  79762. var _this = this;
  79763. this.video = document.createElement("video");
  79764. this.video.controls = false;
  79765. this.video.setAttribute('autoplay', 'autoplay');
  79766. this.video.addEventListener('loadeddata', function (event) { _this.updateTexture(event); }, true);
  79767. this.video.src = window.URL.createObjectURL(blob);
  79768. this.video.canplay = true;
  79769. return this;
  79770. },
  79771. /**
  79772. * Creates a new Video element from the given URL.
  79773. *
  79774. * @method Phaser.Video#createVideoFromURL
  79775. * @param {string} url - The URL of the video.
  79776. * @param {boolean} [autoplay=false] - Automatically start the video?
  79777. * @return {Phaser.Video} This Video object for method chaining.
  79778. */
  79779. createVideoFromURL: function (url, autoplay) {
  79780. if (autoplay === undefined) { autoplay = false; }
  79781. // Invalidate the texture while we wait for the new one to load (crashes IE11 otherwise)
  79782. if (this.texture)
  79783. {
  79784. this.texture.valid = false;
  79785. }
  79786. this.video = document.createElement("video");
  79787. this.video.controls = false;
  79788. if (autoplay)
  79789. {
  79790. this.video.setAttribute('autoplay', 'autoplay');
  79791. }
  79792. this.video.src = url;
  79793. this.video.canplay = true;
  79794. this.video.load();
  79795. this.retry = this.retryLimit;
  79796. this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval);
  79797. this.key = url;
  79798. return this;
  79799. },
  79800. /**
  79801. * Called automatically if the video source changes and updates the internal texture dimensions.
  79802. * Then dispatches the onChangeSource signal.
  79803. *
  79804. * @method Phaser.Video#updateTexture
  79805. * @param {object} [event] - The event which triggered the texture update.
  79806. * @param {integer} [width] - The new width of the video. If undefined `video.videoWidth` is used.
  79807. * @param {integer} [height] - The new height of the video. If undefined `video.videoHeight` is used.
  79808. */
  79809. updateTexture: function (event, width, height) {
  79810. var change = false;
  79811. if (width === undefined || width === null) { width = this.video.videoWidth; change = true; }
  79812. if (height === undefined || height === null) { height = this.video.videoHeight; }
  79813. this.width = width;
  79814. this.height = height;
  79815. if (this.baseTexture.source !== this.video)
  79816. {
  79817. this.baseTexture.source = this.video;
  79818. }
  79819. this.baseTexture.forceLoaded(width, height);
  79820. this.texture.frame.resize(width, height);
  79821. this.texture.width = width;
  79822. this.texture.height = height;
  79823. this.texture.valid = true;
  79824. if (this.snapshot)
  79825. {
  79826. this.snapshot.resize(width, height);
  79827. }
  79828. if (change && this.key !== null)
  79829. {
  79830. this.onChangeSource.dispatch(this, width, height);
  79831. if (this._autoplay)
  79832. {
  79833. this.video.play();
  79834. this.onPlay.dispatch(this, this.loop, this.playbackRate);
  79835. }
  79836. }
  79837. },
  79838. /**
  79839. * Called when the video completes playback (reaches and ended state).
  79840. * Dispatches the Video.onComplete signal.
  79841. *
  79842. * @method Phaser.Video#complete
  79843. */
  79844. complete: function () {
  79845. this.onComplete.dispatch(this);
  79846. },
  79847. /**
  79848. * Starts this video playing if it's not already doing so.
  79849. *
  79850. * @method Phaser.Video#play
  79851. * @param {boolean} [loop=false] - Should the video loop automatically when it reaches the end? Please note that at present some browsers (i.e. Chrome) do not support *seamless* video looping.
  79852. * @param {number} [playbackRate=1] - The playback rate of the video. 1 is normal speed, 2 is x2 speed, and so on. You cannot set a negative playback rate.
  79853. * @return {Phaser.Video} This Video object for method chaining.
  79854. */
  79855. play: function (loop, playbackRate) {
  79856. if (loop === undefined) { loop = false; }
  79857. if (playbackRate === undefined) { playbackRate = 1; }
  79858. if (this.game.sound.onMute)
  79859. {
  79860. this.game.sound.onMute.add(this.setMute, this);
  79861. this.game.sound.onUnMute.add(this.unsetMute, this);
  79862. if (this.game.sound.mute)
  79863. {
  79864. this.setMute();
  79865. }
  79866. }
  79867. this.game.onPause.add(this.setPause, this);
  79868. this.game.onResume.add(this.setResume, this);
  79869. this._endCallback = this.complete.bind(this);
  79870. this.video.addEventListener('ended', this._endCallback, true);
  79871. if (loop)
  79872. {
  79873. this.video.loop = 'loop';
  79874. }
  79875. else
  79876. {
  79877. this.video.loop = '';
  79878. }
  79879. this.video.playbackRate = playbackRate;
  79880. if (this.touchLocked)
  79881. {
  79882. this._pending = true;
  79883. }
  79884. else
  79885. {
  79886. this._pending = false;
  79887. if (this.key !== null)
  79888. {
  79889. if (this.video.readyState !== 4)
  79890. {
  79891. this.retry = this.retryLimit;
  79892. this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval);
  79893. }
  79894. else
  79895. {
  79896. this._playCallback = this.playHandler.bind(this);
  79897. this.video.addEventListener('playing', this._playCallback, true);
  79898. }
  79899. }
  79900. this.video.play();
  79901. this.onPlay.dispatch(this, loop, playbackRate);
  79902. }
  79903. return this;
  79904. },
  79905. /**
  79906. * Called when the video starts to play. Updates the texture.
  79907. *
  79908. * @method Phaser.Video#playHandler
  79909. * @private
  79910. */
  79911. playHandler: function () {
  79912. this.video.removeEventListener('playing', this._playCallback, true);
  79913. this.updateTexture();
  79914. },
  79915. /**
  79916. * Stops the video playing.
  79917. *
  79918. * This removes all locally set signals.
  79919. *
  79920. * If you only wish to pause playback of the video, to resume at a later time, use `Video.paused = true` instead.
  79921. * If the video hasn't finished downloading calling `Video.stop` will not abort the download. To do that you need to
  79922. * call `Video.destroy` instead.
  79923. *
  79924. * If you are using a video stream from a webcam then calling Stop will disconnect the MediaStream session and disable the webcam.
  79925. *
  79926. * @method Phaser.Video#stop
  79927. * @return {Phaser.Video} This Video object for method chaining.
  79928. */
  79929. stop: function () {
  79930. if (this.game.sound.onMute)
  79931. {
  79932. this.game.sound.onMute.remove(this.setMute, this);
  79933. this.game.sound.onUnMute.remove(this.unsetMute, this);
  79934. }
  79935. this.game.onPause.remove(this.setPause, this);
  79936. this.game.onResume.remove(this.setResume, this);
  79937. // Stream or file?
  79938. if (this.isStreaming)
  79939. {
  79940. if (this.video.mozSrcObject)
  79941. {
  79942. this.video.mozSrcObject.stop();
  79943. this.video.src = null;
  79944. }
  79945. else
  79946. {
  79947. this.video.src = "";
  79948. if (this.videoStream['active'])
  79949. {
  79950. this.videoStream.active = false;
  79951. }
  79952. else
  79953. {
  79954. if (this.videoStream.getTracks)
  79955. {
  79956. this.videoStream.getTracks().forEach(function (track) {
  79957. track.stop();
  79958. });
  79959. }
  79960. else
  79961. {
  79962. this.videoStream.stop();
  79963. }
  79964. }
  79965. }
  79966. this.videoStream = null;
  79967. this.isStreaming = false;
  79968. }
  79969. else
  79970. {
  79971. this.video.removeEventListener('ended', this._endCallback, true);
  79972. this.video.removeEventListener('playing', this._playCallback, true);
  79973. if (this.touchLocked)
  79974. {
  79975. this._pending = false;
  79976. }
  79977. else
  79978. {
  79979. this.video.pause();
  79980. }
  79981. }
  79982. return this;
  79983. },
  79984. /**
  79985. * Updates the given Display Objects so they use this Video as their texture.
  79986. * This will replace any texture they will currently have set.
  79987. *
  79988. * @method Phaser.Video#add
  79989. * @param {Phaser.Sprite|Phaser.Sprite[]|Phaser.Image|Phaser.Image[]} object - Either a single Sprite/Image or an Array of Sprites/Images.
  79990. * @return {Phaser.Video} This Video object for method chaining.
  79991. */
  79992. add: function (object) {
  79993. if (Array.isArray(object))
  79994. {
  79995. for (var i = 0; i < object.length; i++)
  79996. {
  79997. if (object[i]['loadTexture'])
  79998. {
  79999. object[i].loadTexture(this);
  80000. }
  80001. }
  80002. }
  80003. else
  80004. {
  80005. object.loadTexture(this);
  80006. }
  80007. return this;
  80008. },
  80009. /**
  80010. * Creates a new Phaser.Image object, assigns this Video to be its texture, adds it to the world then returns it.
  80011. *
  80012. * @method Phaser.Video#addToWorld
  80013. * @param {number} [x=0] - The x coordinate to place the Image at.
  80014. * @param {number} [y=0] - The y coordinate to place the Image at.
  80015. * @param {number} [anchorX=0] - Set the x anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right.
  80016. * @param {number} [anchorY=0] - Set the y anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right.
  80017. * @param {number} [scaleX=1] - The horizontal scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on.
  80018. * @param {number} [scaleY=1] - The vertical scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on.
  80019. * @return {Phaser.Image} The newly added Image object.
  80020. */
  80021. addToWorld: function (x, y, anchorX, anchorY, scaleX, scaleY) {
  80022. scaleX = scaleX || 1;
  80023. scaleY = scaleY || 1;
  80024. var image = this.game.add.image(x, y, this);
  80025. image.anchor.set(anchorX, anchorY);
  80026. image.scale.set(scaleX, scaleY);
  80027. return image;
  80028. },
  80029. /**
  80030. * If the game is running in WebGL this will push the texture up to the GPU if it's dirty.
  80031. * This is called automatically if the Video is being used by a Sprite, otherwise you need to remember to call it in your render function.
  80032. * If you wish to suppress this functionality set Video.disableTextureUpload to `true`.
  80033. *
  80034. * @method Phaser.Video#render
  80035. */
  80036. render: function () {
  80037. if (!this.disableTextureUpload && this.playing)
  80038. {
  80039. this.baseTexture.dirty();
  80040. }
  80041. },
  80042. /**
  80043. * Internal handler called automatically by the Video.mute setter.
  80044. *
  80045. * @method Phaser.Video#setMute
  80046. * @private
  80047. */
  80048. setMute: function () {
  80049. if (this._muted)
  80050. {
  80051. return;
  80052. }
  80053. this._muted = true;
  80054. this.video.muted = true;
  80055. },
  80056. /**
  80057. * Internal handler called automatically by the Video.mute setter.
  80058. *
  80059. * @method Phaser.Video#unsetMute
  80060. * @private
  80061. */
  80062. unsetMute: function () {
  80063. if (!this._muted || this._codeMuted)
  80064. {
  80065. return;
  80066. }
  80067. this._muted = false;
  80068. this.video.muted = false;
  80069. },
  80070. /**
  80071. * Internal handler called automatically by the Video.paused setter.
  80072. *
  80073. * @method Phaser.Video#setPause
  80074. * @private
  80075. */
  80076. setPause: function () {
  80077. if (this._paused || this.touchLocked)
  80078. {
  80079. return;
  80080. }
  80081. this._paused = true;
  80082. this.video.pause();
  80083. },
  80084. /**
  80085. * Internal handler called automatically by the Video.paused setter.
  80086. *
  80087. * @method Phaser.Video#setResume
  80088. * @private
  80089. */
  80090. setResume: function () {
  80091. if (!this._paused || this._codePaused || this.touchLocked)
  80092. {
  80093. return;
  80094. }
  80095. this._paused = false;
  80096. if (!this.video.ended)
  80097. {
  80098. this.video.play();
  80099. }
  80100. },
  80101. /**
  80102. * On some mobile browsers you cannot play a video until the user has explicitly touched the video to allow it.
  80103. * Phaser handles this via the `setTouchLock` method. However if you have 3 different videos, maybe an "Intro", "Start" and "Game Over"
  80104. * split into three different Video objects, then you will need the user to touch-unlock every single one of them.
  80105. *
  80106. * You can avoid this by using just one Video object and simply changing the video source. Once a Video element is unlocked it remains
  80107. * unlocked, even if the source changes. So you can use this to your benefit to avoid forcing the user to 'touch' the video yet again.
  80108. *
  80109. * As you'd expect there are limitations. So far we've found that the videos need to be in the same encoding format and bitrate.
  80110. * This method will automatically handle a change in video dimensions, but if you try swapping to a different bitrate we've found it
  80111. * cannot render the new video on iOS (desktop browsers cope better).
  80112. *
  80113. * When the video source is changed the video file is requested over the network. Listen for the `onChangeSource` signal to know
  80114. * when the new video has downloaded enough content to be able to be played. Previous settings such as the volume and loop state
  80115. * are adopted automatically by the new video.
  80116. *
  80117. * @method Phaser.Video#changeSource
  80118. * @param {string} src - The new URL to change the video.src to.
  80119. * @param {boolean} [autoplay=true] - Should the video play automatically after the source has been updated?
  80120. * @return {Phaser.Video} This Video object for method chaining.
  80121. */
  80122. changeSource: function (src, autoplay) {
  80123. if (autoplay === undefined) { autoplay = true; }
  80124. // Invalidate the texture while we wait for the new one to load (crashes IE11 otherwise)
  80125. this.texture.valid = false;
  80126. this.video.pause();
  80127. this.retry = this.retryLimit;
  80128. this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval);
  80129. this.video.src = src;
  80130. this.video.load();
  80131. this._autoplay = autoplay;
  80132. if (!autoplay)
  80133. {
  80134. this.paused = true;
  80135. }
  80136. return this;
  80137. },
  80138. /**
  80139. * Internal callback that monitors the download progress of a video after changing its source.
  80140. *
  80141. * @method Phaser.Video#checkVideoProgress
  80142. * @private
  80143. */
  80144. checkVideoProgress: function () {
  80145. // if (this.video.readyState === 2 || this.video.readyState === 4)
  80146. if (this.video.readyState === 4)
  80147. {
  80148. // We've got enough data to update the texture for playback
  80149. this.updateTexture();
  80150. }
  80151. else
  80152. {
  80153. this.retry--;
  80154. if (this.retry > 0)
  80155. {
  80156. this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval);
  80157. }
  80158. else
  80159. {
  80160. console.warn('Phaser.Video: Unable to start downloading video in time', this.isStreaming);
  80161. }
  80162. }
  80163. },
  80164. /**
  80165. * Sets the Input Manager touch callback to be Video.unlock.
  80166. * Required for mobile video unlocking. Mostly just used internally.
  80167. *
  80168. * @method Phaser.Video#setTouchLock
  80169. */
  80170. setTouchLock: function () {
  80171. this.game.input.touch.addTouchLockCallback(this.unlock, this);
  80172. this.touchLocked = true;
  80173. },
  80174. /**
  80175. * Enables the video on mobile devices, usually after the first touch.
  80176. * If the SoundManager hasn't been unlocked then this will automatically unlock that as well.
  80177. * Only one video can be pending unlock at any one time.
  80178. *
  80179. * @method Phaser.Video#unlock
  80180. */
  80181. unlock: function () {
  80182. this.touchLocked = false;
  80183. this.video.play();
  80184. this.onPlay.dispatch(this, this.loop, this.playbackRate);
  80185. if (this.key)
  80186. {
  80187. var _video = this.game.cache.getVideo(this.key);
  80188. if (_video && !_video.isBlob)
  80189. {
  80190. _video.locked = false;
  80191. }
  80192. }
  80193. return true;
  80194. },
  80195. /**
  80196. * Grabs the current frame from the Video or Video Stream and renders it to the Video.snapshot BitmapData.
  80197. *
  80198. * You can optionally set if the BitmapData should be cleared or not, the alpha and the blend mode of the draw.
  80199. *
  80200. * If you need more advanced control over the grabbing them call `Video.snapshot.copy` directly with the same parameters as BitmapData.copy.
  80201. *
  80202. * @method Phaser.Video#grab
  80203. * @param {boolean} [clear=false] - Should the BitmapData be cleared before the Video is grabbed? Unless you are using alpha or a blend mode you can usually leave this set to false.
  80204. * @param {number} [alpha=1] - The alpha that will be set on the video before drawing. A value between 0 (fully transparent) and 1, opaque.
  80205. * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'.
  80206. * @return {Phaser.BitmapData} A reference to the Video.snapshot BitmapData object for further method chaining.
  80207. */
  80208. grab: function (clear, alpha, blendMode) {
  80209. if (clear === undefined) { clear = false; }
  80210. if (alpha === undefined) { alpha = 1; }
  80211. if (blendMode === undefined) { blendMode = null; }
  80212. if (this.snapshot === null)
  80213. {
  80214. console.warn('Video.grab cannot run because Phaser.BitmapData is unavailable');
  80215. return;
  80216. }
  80217. if (clear)
  80218. {
  80219. this.snapshot.cls();
  80220. }
  80221. this.snapshot.copy(this.video, 0, 0, this.width, this.height, 0, 0, this.width, this.height, 0, 0, 0, 1, 1, alpha, blendMode);
  80222. return this.snapshot;
  80223. },
  80224. /**
  80225. * Removes the Video element from the DOM by calling parentNode.removeChild on itself.
  80226. * Also removes the autoplay and src attributes and nulls the reference.
  80227. *
  80228. * @method Phaser.Video#removeVideoElement
  80229. */
  80230. removeVideoElement: function () {
  80231. if (!this.video)
  80232. {
  80233. return;
  80234. }
  80235. if (this.video.parentNode)
  80236. {
  80237. this.video.parentNode.removeChild(this.video);
  80238. }
  80239. while (this.video.hasChildNodes())
  80240. {
  80241. this.video.removeChild(this.video.firstChild);
  80242. }
  80243. this.video.removeAttribute('autoplay');
  80244. this.video.removeAttribute('src');
  80245. this.video = null;
  80246. },
  80247. /**
  80248. * Destroys the Video object. This calls `Video.stop` and then `Video.removeVideoElement`.
  80249. * If any Sprites are using this Video as their texture it is up to you to manage those.
  80250. *
  80251. * @method Phaser.Video#destroy
  80252. */
  80253. destroy: function () {
  80254. this.stop();
  80255. this.removeVideoElement();
  80256. if (this.touchLocked)
  80257. {
  80258. this.game.input.touch.removeTouchLockCallback(this.unlock, this);
  80259. }
  80260. if (this._retryID)
  80261. {
  80262. window.clearTimeout(this._retryID);
  80263. }
  80264. }
  80265. };
  80266. /**
  80267. * @name Phaser.Video#currentTime
  80268. * @property {number} currentTime - The current time of the video in seconds. If set the video will attempt to seek to that point in time.
  80269. */
  80270. Object.defineProperty(Phaser.Video.prototype, "currentTime", {
  80271. get: function () {
  80272. return (this.video) ? this.video.currentTime : 0;
  80273. },
  80274. set: function (value) {
  80275. this.video.currentTime = value;
  80276. }
  80277. });
  80278. /**
  80279. * @name Phaser.Video#duration
  80280. * @property {number} duration - The duration of the video in seconds.
  80281. * @readOnly
  80282. */
  80283. Object.defineProperty(Phaser.Video.prototype, "duration", {
  80284. get: function () {
  80285. return (this.video) ? this.video.duration : 0;
  80286. }
  80287. });
  80288. /**
  80289. * @name Phaser.Video#progress
  80290. * @property {number} progress - The progress of this video. This is a value between 0 and 1, where 0 is the start and 1 is the end of the video.
  80291. * @readOnly
  80292. */
  80293. Object.defineProperty(Phaser.Video.prototype, "progress", {
  80294. get: function () {
  80295. return (this.video) ? (this.video.currentTime / this.video.duration) : 0;
  80296. }
  80297. });
  80298. /**
  80299. * @name Phaser.Video#mute
  80300. * @property {boolean} mute - Gets or sets the muted state of the Video.
  80301. */
  80302. Object.defineProperty(Phaser.Video.prototype, "mute", {
  80303. get: function () {
  80304. return this._muted;
  80305. },
  80306. set: function (value) {
  80307. value = value || null;
  80308. if (value)
  80309. {
  80310. if (this._muted)
  80311. {
  80312. return;
  80313. }
  80314. this._codeMuted = true;
  80315. this.setMute();
  80316. }
  80317. else
  80318. {
  80319. if (!this._muted)
  80320. {
  80321. return;
  80322. }
  80323. this._codeMuted = false;
  80324. this.unsetMute();
  80325. }
  80326. }
  80327. });
  80328. /**
  80329. * Gets or sets the paused state of the Video.
  80330. * If the video is still touch locked (such as on iOS devices) this call has no effect.
  80331. *
  80332. * @name Phaser.Video#paused
  80333. * @property {boolean} paused
  80334. */
  80335. Object.defineProperty(Phaser.Video.prototype, "paused", {
  80336. get: function () {
  80337. return this._paused;
  80338. },
  80339. set: function (value) {
  80340. value = value || null;
  80341. if (this.touchLocked)
  80342. {
  80343. return;
  80344. }
  80345. if (value)
  80346. {
  80347. if (this._paused)
  80348. {
  80349. return;
  80350. }
  80351. this._codePaused = true;
  80352. this.setPause();
  80353. }
  80354. else
  80355. {
  80356. if (!this._paused)
  80357. {
  80358. return;
  80359. }
  80360. this._codePaused = false;
  80361. this.setResume();
  80362. }
  80363. }
  80364. });
  80365. /**
  80366. * @name Phaser.Video#volume
  80367. * @property {number} volume - Gets or sets the volume of the Video, a value between 0 and 1. The value given is clamped to the range 0 to 1.
  80368. */
  80369. Object.defineProperty(Phaser.Video.prototype, "volume", {
  80370. get: function () {
  80371. return (this.video) ? this.video.volume : 1;
  80372. },
  80373. set: function (value) {
  80374. if (value < 0)
  80375. {
  80376. value = 0;
  80377. }
  80378. else if (value > 1)
  80379. {
  80380. value = 1;
  80381. }
  80382. if (this.video)
  80383. {
  80384. this.video.volume = value;
  80385. }
  80386. }
  80387. });
  80388. /**
  80389. * @name Phaser.Video#playbackRate
  80390. * @property {number} playbackRate - Gets or sets the playback rate of the Video. This is the speed at which the video is playing.
  80391. */
  80392. Object.defineProperty(Phaser.Video.prototype, "playbackRate", {
  80393. get: function () {
  80394. return (this.video) ? this.video.playbackRate : 1;
  80395. },
  80396. set: function (value) {
  80397. if (this.video)
  80398. {
  80399. this.video.playbackRate = value;
  80400. }
  80401. }
  80402. });
  80403. /**
  80404. * Gets or sets if the Video is set to loop.
  80405. * Please note that at present some browsers (i.e. Chrome) do not support *seamless* video looping.
  80406. * If the video isn't yet set this will always return false.
  80407. *
  80408. * @name Phaser.Video#loop
  80409. * @property {boolean} loop
  80410. */
  80411. Object.defineProperty(Phaser.Video.prototype, "loop", {
  80412. get: function () {
  80413. return (this.video) ? this.video.loop : false;
  80414. },
  80415. set: function (value) {
  80416. if (value && this.video)
  80417. {
  80418. this.video.loop = 'loop';
  80419. }
  80420. else if (this.video)
  80421. {
  80422. this.video.loop = '';
  80423. }
  80424. }
  80425. });
  80426. /**
  80427. * @name Phaser.Video#playing
  80428. * @property {boolean} playing - True if the video is currently playing (and not paused or ended), otherwise false.
  80429. * @readOnly
  80430. */
  80431. Object.defineProperty(Phaser.Video.prototype, "playing", {
  80432. get: function () {
  80433. return !(this.video.paused && this.video.ended);
  80434. }
  80435. });
  80436. Phaser.Video.prototype.constructor = Phaser.Video;
  80437. /* global Phaser:true */
  80438. /**
  80439. * @author Richard Davey <rich@photonstorm.com>
  80440. * @copyright 2016 Photon Storm Ltd.
  80441. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  80442. */
  80443. // Pixi expects these globals to exist
  80444. if (PIXI.blendModes === undefined)
  80445. {
  80446. PIXI.blendModes = Phaser.blendModes;
  80447. }
  80448. if (PIXI.scaleModes === undefined)
  80449. {
  80450. PIXI.scaleModes = Phaser.scaleModes;
  80451. }
  80452. if (PIXI.Texture.emptyTexture === undefined)
  80453. {
  80454. PIXI.Texture.emptyTexture = new PIXI.Texture(new PIXI.BaseTexture());
  80455. }
  80456. if (PIXI.DisplayObject._tempMatrix === undefined)
  80457. {
  80458. PIXI.DisplayObject._tempMatrix = new PIXI.Matrix();
  80459. }
  80460. if (PIXI.RenderTexture.tempMatrix === undefined)
  80461. {
  80462. PIXI.RenderTexture.tempMatrix = new PIXI.Matrix();
  80463. }
  80464. if (PIXI.Graphics && PIXI.Graphics.POLY === undefined)
  80465. {
  80466. PIXI.Graphics.POLY = Phaser.POLYGON;
  80467. PIXI.Graphics.RECT = Phaser.RECTANGLE;
  80468. PIXI.Graphics.CIRC = Phaser.CIRCLE;
  80469. PIXI.Graphics.ELIP = Phaser.ELLIPSE;
  80470. PIXI.Graphics.RREC = Phaser.ROUNDEDRECTANGLE;
  80471. }
  80472. PIXI.TextureSilentFail = true;
  80473. /**
  80474. * @author Richard Davey <rich@photonstorm.com>
  80475. * @copyright 2016 Photon Storm Ltd.
  80476. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  80477. */
  80478. if (typeof exports !== 'undefined') {
  80479. if (typeof module !== 'undefined' && module.exports) {
  80480. exports = module.exports = Phaser;
  80481. }
  80482. exports.Phaser = Phaser;
  80483. } else if (typeof define !== 'undefined' && define.amd) {
  80484. define('Phaser', (function() { return root.Phaser = Phaser; })() );
  80485. } else {
  80486. root.Phaser = Phaser;
  80487. }
  80488. return Phaser;
  80489. }).call(this);
  80490. /*
  80491. * "What matters in this life is not what we do but what we do for others, the legacy we leave and the imprint we make." - Eric Meyer
  80492. */