cocos2d-js-v3.13-lite.js 740 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703
  1. var cc = cc || {};
  2. cc._tmp = cc._tmp || {};
  3. cc._LogInfos = {};
  4. var _p = window;
  5. _p.gl;
  6. _p.WebGLRenderingContext;
  7. _p.DeviceOrientationEvent;
  8. _p.DeviceMotionEvent;
  9. _p.AudioContext;
  10. if (!_p.AudioContext) {
  11. _p.webkitAudioContext;
  12. }
  13. _p.mozAudioContext;
  14. _p = Object.prototype;
  15. _p._super;
  16. _p.ctor;
  17. _p = null;
  18. cc.ORIENTATION_PORTRAIT = 0;
  19. cc.ORIENTATION_PORTRAIT_UPSIDE_DOWN = 1;
  20. cc.ORIENTATION_LANDSCAPE_LEFT = 2;
  21. cc.ORIENTATION_LANDSCAPE_RIGHT = 3;
  22. cc._drawingUtil = null;
  23. cc._renderContext = null;
  24. cc._supportRender = false;
  25. cc._canvas = null;
  26. cc.container = null;
  27. cc._gameDiv = null;
  28. cc.newElement = function (x) {
  29. return document.createElement(x);
  30. };
  31. cc.each = function (obj, iterator, context) {
  32. if (!obj)
  33. return;
  34. if (obj instanceof Array) {
  35. for (var i = 0, li = obj.length; i < li; i++) {
  36. if (iterator.call(context, obj[i], i) === false)
  37. return;
  38. }
  39. } else {
  40. for (var key in obj) {
  41. if (iterator.call(context, obj[key], key) === false)
  42. return;
  43. }
  44. }
  45. };
  46. cc.extend = function(target) {
  47. var sources = arguments.length >= 2 ? Array.prototype.slice.call(arguments, 1) : [];
  48. cc.each(sources, function(src) {
  49. for(var key in src) {
  50. if (src.hasOwnProperty(key)) {
  51. target[key] = src[key];
  52. }
  53. }
  54. });
  55. return target;
  56. };
  57. cc.isFunction = function(obj) {
  58. return typeof obj === 'function';
  59. };
  60. cc.isNumber = function(obj) {
  61. return typeof obj === 'number' || Object.prototype.toString.call(obj) === '[object Number]';
  62. };
  63. cc.isString = function(obj) {
  64. return typeof obj === 'string' || Object.prototype.toString.call(obj) === '[object String]';
  65. };
  66. cc.isArray = function(obj) {
  67. return Array.isArray(obj) ||
  68. (typeof obj === 'object' && Object.prototype.toString.call(obj) === '[object Array]');
  69. };
  70. cc.isUndefined = function(obj) {
  71. return typeof obj === 'undefined';
  72. };
  73. cc.isObject = function(obj) {
  74. return typeof obj === "object" && Object.prototype.toString.call(obj) === '[object Object]';
  75. };
  76. cc.isCrossOrigin = function (url) {
  77. if (!url) {
  78. cc.log("invalid URL");
  79. return false;
  80. }
  81. var startIndex = url.indexOf("://");
  82. if (startIndex === -1)
  83. return false;
  84. var endIndex = url.indexOf("/", startIndex + 3);
  85. var urlOrigin = (endIndex === -1) ? url : url.substring(0, endIndex);
  86. return urlOrigin !== location.origin;
  87. };
  88. cc.AsyncPool = function(srcObj, limit, iterator, onEnd, target){
  89. var self = this;
  90. self._srcObj = srcObj;
  91. self._limit = limit;
  92. self._pool = [];
  93. self._iterator = iterator;
  94. self._iteratorTarget = target;
  95. self._onEnd = onEnd;
  96. self._onEndTarget = target;
  97. self._results = srcObj instanceof Array ? [] : {};
  98. self._errors = srcObj instanceof Array ? [] : {};
  99. cc.each(srcObj, function(value, index){
  100. self._pool.push({index : index, value : value});
  101. });
  102. self.size = self._pool.length;
  103. self.finishedSize = 0;
  104. self._workingSize = 0;
  105. self._limit = self._limit || self.size;
  106. self.onIterator = function(iterator, target){
  107. self._iterator = iterator;
  108. self._iteratorTarget = target;
  109. };
  110. self.onEnd = function(endCb, endCbTarget){
  111. self._onEnd = endCb;
  112. self._onEndTarget = endCbTarget;
  113. };
  114. self._handleItem = function(){
  115. var self = this;
  116. if(self._pool.length === 0 || self._workingSize >= self._limit)
  117. return;
  118. var item = self._pool.shift();
  119. var value = item.value, index = item.index;
  120. self._workingSize++;
  121. self._iterator.call(self._iteratorTarget, value, index,
  122. function(err, result) {
  123. self.finishedSize++;
  124. self._workingSize--;
  125. if (err) {
  126. self._errors[this.index] = err;
  127. }
  128. else {
  129. self._results[this.index] = result;
  130. }
  131. if (self.finishedSize === self.size) {
  132. if (self._onEnd) {
  133. var errors = self._errors.length === 0 ? null : self._errors;
  134. self._onEnd.call(self._onEndTarget, errors, self._results);
  135. }
  136. return;
  137. }
  138. self._handleItem();
  139. }.bind(item),
  140. self);
  141. };
  142. self.flow = function(){
  143. var self = this;
  144. if(self._pool.length === 0) {
  145. if(self._onEnd)
  146. self._onEnd.call(self._onEndTarget, null, []);
  147. return;
  148. }
  149. for(var i = 0; i < self._limit; i++)
  150. self._handleItem();
  151. };
  152. };
  153. cc.async = {
  154. series : function(tasks, cb, target){
  155. var asyncPool = new cc.AsyncPool(tasks, 1, function(func, index, cb1){
  156. func.call(target, cb1);
  157. }, cb, target);
  158. asyncPool.flow();
  159. return asyncPool;
  160. },
  161. parallel : function(tasks, cb, target){
  162. var asyncPool = new cc.AsyncPool(tasks, 0, function(func, index, cb1){
  163. func.call(target, cb1);
  164. }, cb, target);
  165. asyncPool.flow();
  166. return asyncPool;
  167. },
  168. waterfall : function(tasks, cb, target){
  169. var args = [];
  170. var lastResults = [null];//the array to store the last results
  171. var asyncPool = new cc.AsyncPool(tasks, 1,
  172. function (func, index, cb1) {
  173. args.push(function (err) {
  174. args = Array.prototype.slice.call(arguments, 1);
  175. if(tasks.length - 1 === index) lastResults = lastResults.concat(args);//while the last task
  176. cb1.apply(null, arguments);
  177. });
  178. func.apply(target, args);
  179. }, function (err) {
  180. if (!cb)
  181. return;
  182. if (err)
  183. return cb.call(target, err);
  184. cb.apply(target, lastResults);
  185. });
  186. asyncPool.flow();
  187. return asyncPool;
  188. },
  189. map : function(tasks, iterator, callback, target){
  190. var locIterator = iterator;
  191. if(typeof(iterator) === "object"){
  192. callback = iterator.cb;
  193. target = iterator.iteratorTarget;
  194. locIterator = iterator.iterator;
  195. }
  196. var asyncPool = new cc.AsyncPool(tasks, 0, locIterator, callback, target);
  197. asyncPool.flow();
  198. return asyncPool;
  199. },
  200. mapLimit : function(tasks, limit, iterator, cb, target){
  201. var asyncPool = new cc.AsyncPool(tasks, limit, iterator, cb, target);
  202. asyncPool.flow();
  203. return asyncPool;
  204. }
  205. };
  206. cc.path = {
  207. normalizeRE: /[^\.\/]+\/\.\.\//,
  208. join: function () {
  209. var l = arguments.length;
  210. var result = "";
  211. for (var i = 0; i < l; i++) {
  212. result = (result + (result === "" ? "" : "/") + arguments[i]).replace(/(\/|\\\\)$/, "");
  213. }
  214. return result;
  215. },
  216. extname: function (pathStr) {
  217. var temp = /(\.[^\.\/\?\\]*)(\?.*)?$/.exec(pathStr);
  218. return temp ? temp[1] : null;
  219. },
  220. mainFileName: function(fileName){
  221. if(fileName){
  222. var idx = fileName.lastIndexOf(".");
  223. if(idx !== -1)
  224. return fileName.substring(0,idx);
  225. }
  226. return fileName;
  227. },
  228. basename: function (pathStr, extname) {
  229. var index = pathStr.indexOf("?");
  230. if (index > 0) pathStr = pathStr.substring(0, index);
  231. var reg = /(\/|\\\\)([^(\/|\\\\)]+)$/g;
  232. var result = reg.exec(pathStr.replace(/(\/|\\\\)$/, ""));
  233. if (!result) return null;
  234. var baseName = result[2];
  235. if (extname && pathStr.substring(pathStr.length - extname.length).toLowerCase() === extname.toLowerCase())
  236. return baseName.substring(0, baseName.length - extname.length);
  237. return baseName;
  238. },
  239. dirname: function (pathStr) {
  240. return pathStr.replace(/((.*)(\/|\\|\\\\))?(.*?\..*$)?/, '$2');
  241. },
  242. changeExtname: function (pathStr, extname) {
  243. extname = extname || "";
  244. var index = pathStr.indexOf("?");
  245. var tempStr = "";
  246. if (index > 0) {
  247. tempStr = pathStr.substring(index);
  248. pathStr = pathStr.substring(0, index);
  249. }
  250. index = pathStr.lastIndexOf(".");
  251. if (index < 0) return pathStr + extname + tempStr;
  252. return pathStr.substring(0, index) + extname + tempStr;
  253. },
  254. changeBasename: function (pathStr, basename, isSameExt) {
  255. if (basename.indexOf(".") === 0) return this.changeExtname(pathStr, basename);
  256. var index = pathStr.indexOf("?");
  257. var tempStr = "";
  258. var ext = isSameExt ? this.extname(pathStr) : "";
  259. if (index > 0) {
  260. tempStr = pathStr.substring(index);
  261. pathStr = pathStr.substring(0, index);
  262. }
  263. index = pathStr.lastIndexOf("/");
  264. index = index <= 0 ? 0 : index + 1;
  265. return pathStr.substring(0, index) + basename + ext + tempStr;
  266. },
  267. _normalize: function(url){
  268. var oldUrl = url = String(url);
  269. do {
  270. oldUrl = url;
  271. url = url.replace(this.normalizeRE, "");
  272. } while(oldUrl.length !== url.length);
  273. return url;
  274. }
  275. };
  276. cc.loader = (function () {
  277. var _jsCache = {},
  278. _register = {},
  279. _langPathCache = {},
  280. _aliases = {},
  281. _queue = {},
  282. _urlRegExp = new RegExp(
  283. "^" +
  284. "(?:(?:https?|ftp)://)" +
  285. "(?:\\S+(?::\\S*)?@)?" +
  286. "(?:" +
  287. "(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" +
  288. "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" +
  289. "(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" +
  290. "|" +
  291. "(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)" +
  292. "(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*" +
  293. "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))" +
  294. "|" +
  295. "(?:localhost)" +
  296. ")" +
  297. "(?::\\d{2,5})?" +
  298. "(?:/\\S*)?" +
  299. "$", "i"
  300. );
  301. return {
  302. resPath: "",
  303. audioPath: "",
  304. cache: {},
  305. getXMLHttpRequest: function () {
  306. return window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP");
  307. },
  308. _getArgs4Js: function (args) {
  309. var a0 = args[0], a1 = args[1], a2 = args[2], results = ["", null, null];
  310. if (args.length === 1) {
  311. results[1] = a0 instanceof Array ? a0 : [a0];
  312. } else if (args.length === 2) {
  313. if (typeof a1 === "function") {
  314. results[1] = a0 instanceof Array ? a0 : [a0];
  315. results[2] = a1;
  316. } else {
  317. results[0] = a0 || "";
  318. results[1] = a1 instanceof Array ? a1 : [a1];
  319. }
  320. } else if (args.length === 3) {
  321. results[0] = a0 || "";
  322. results[1] = a1 instanceof Array ? a1 : [a1];
  323. results[2] = a2;
  324. } else throw new Error("arguments error to load js!");
  325. return results;
  326. },
  327. isLoading: function (url) {
  328. return (_queue[url] !== undefined);
  329. },
  330. loadJs: function (baseDir, jsList, cb) {
  331. var self = this,
  332. args = self._getArgs4Js(arguments);
  333. var preDir = args[0], list = args[1], callback = args[2];
  334. if (navigator.userAgent.indexOf("Trident/5") > -1) {
  335. self._loadJs4Dependency(preDir, list, 0, callback);
  336. } else {
  337. cc.async.map(list, function (item, index, cb1) {
  338. var jsPath = cc.path.join(preDir, item);
  339. if (_jsCache[jsPath]) return cb1(null);
  340. self._createScript(jsPath, false, cb1);
  341. }, callback);
  342. }
  343. },
  344. loadJsWithImg: function (baseDir, jsList, cb) {
  345. var self = this, jsLoadingImg = self._loadJsImg(),
  346. args = self._getArgs4Js(arguments);
  347. this.loadJs(args[0], args[1], function (err) {
  348. if (err) throw new Error(err);
  349. jsLoadingImg.parentNode.removeChild(jsLoadingImg);//remove loading gif
  350. if (args[2]) args[2]();
  351. });
  352. },
  353. _createScript: function (jsPath, isAsync, cb) {
  354. var d = document, self = this, s = document.createElement('script');
  355. s.async = isAsync;
  356. _jsCache[jsPath] = true;
  357. if(cc.game.config["noCache"] && typeof jsPath === "string"){
  358. if(self._noCacheRex.test(jsPath))
  359. s.src = jsPath + "&_t=" + (new Date() - 0);
  360. else
  361. s.src = jsPath + "?_t=" + (new Date() - 0);
  362. }else{
  363. s.src = jsPath;
  364. }
  365. s.addEventListener('load', function () {
  366. s.parentNode.removeChild(s);
  367. this.removeEventListener('load', arguments.callee, false);
  368. cb();
  369. }, false);
  370. s.addEventListener('error', function () {
  371. s.parentNode.removeChild(s);
  372. cb("Load " + jsPath + " failed!");
  373. }, false);
  374. d.body.appendChild(s);
  375. },
  376. _loadJs4Dependency: function (baseDir, jsList, index, cb) {
  377. if (index >= jsList.length) {
  378. if (cb) cb();
  379. return;
  380. }
  381. var self = this;
  382. self._createScript(cc.path.join(baseDir, jsList[index]), false, function (err) {
  383. if (err) return cb(err);
  384. self._loadJs4Dependency(baseDir, jsList, index + 1, cb);
  385. });
  386. },
  387. _loadJsImg: function () {
  388. var d = document, jsLoadingImg = d.getElementById("cocos2d_loadJsImg");
  389. if (!jsLoadingImg) {
  390. jsLoadingImg = document.createElement('img');
  391. if (cc._loadingImage)
  392. jsLoadingImg.src = cc._loadingImage;
  393. var canvasNode = d.getElementById(cc.game.config["id"]);
  394. canvasNode.style.backgroundColor = "transparent";
  395. canvasNode.parentNode.appendChild(jsLoadingImg);
  396. var canvasStyle = getComputedStyle ? getComputedStyle(canvasNode) : canvasNode.currentStyle;
  397. if (!canvasStyle)
  398. canvasStyle = {width: canvasNode.width, height: canvasNode.height};
  399. jsLoadingImg.style.left = canvasNode.offsetLeft + (parseFloat(canvasStyle.width) - jsLoadingImg.width) / 2 + "px";
  400. jsLoadingImg.style.top = canvasNode.offsetTop + (parseFloat(canvasStyle.height) - jsLoadingImg.height) / 2 + "px";
  401. jsLoadingImg.style.position = "absolute";
  402. }
  403. return jsLoadingImg;
  404. },
  405. loadTxt: function (url, cb) {
  406. if (!cc._isNodeJs) {
  407. var xhr = this.getXMLHttpRequest(),
  408. errInfo = "load " + url + " failed!";
  409. xhr.open("GET", url, true);
  410. if (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)) {
  411. xhr.setRequestHeader("Accept-Charset", "utf-8");
  412. xhr.onreadystatechange = function () {
  413. if(xhr.readyState === 4)
  414. xhr.status === 200 ? cb(null, xhr.responseText) : cb({status:xhr.status, errorMessage:errInfo}, null);
  415. };
  416. } else {
  417. if (xhr.overrideMimeType) xhr.overrideMimeType("text\/plain; charset=utf-8");
  418. xhr.onload = function () {
  419. if(xhr.readyState === 4)
  420. xhr.status === 200 ? cb(null, xhr.responseText) : cb({status:xhr.status, errorMessage:errInfo}, null);
  421. };
  422. xhr.onerror = function(){
  423. cb({status:xhr.status, errorMessage:errInfo}, null);
  424. };
  425. }
  426. xhr.send(null);
  427. } else {
  428. var fs = require("fs");
  429. fs.readFile(url, function (err, data) {
  430. err ? cb(err) : cb(null, data.toString());
  431. });
  432. }
  433. },
  434. _loadTxtSync: function (url) {
  435. if (!cc._isNodeJs) {
  436. var xhr = this.getXMLHttpRequest();
  437. xhr.open("GET", url, false);
  438. if (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)) {
  439. xhr.setRequestHeader("Accept-Charset", "utf-8");
  440. } else {
  441. if (xhr.overrideMimeType) xhr.overrideMimeType("text\/plain; charset=utf-8");
  442. }
  443. xhr.send(null);
  444. if (!xhr.readyState === 4 || xhr.status !== 200) {
  445. return null;
  446. }
  447. return xhr.responseText;
  448. } else {
  449. var fs = require("fs");
  450. return fs.readFileSync(url).toString();
  451. }
  452. },
  453. loadCsb: function(url, cb){
  454. var xhr = new XMLHttpRequest(),
  455. errInfo = "load " + url + " failed!";
  456. xhr.open("GET", url, true);
  457. xhr.responseType = "arraybuffer";
  458. xhr.onload = function () {
  459. var arrayBuffer = xhr.response;
  460. if (arrayBuffer) {
  461. window.msg = arrayBuffer;
  462. }
  463. if(xhr.readyState === 4)
  464. xhr.status === 200 ? cb(null, xhr.response) : cb({status:xhr.status, errorMessage:errInfo}, null);
  465. };
  466. xhr.onerror = function(){
  467. cb({status:xhr.status, errorMessage:errInfo}, null);
  468. };
  469. xhr.send(null);
  470. },
  471. loadJson: function (url, cb) {
  472. this.loadTxt(url, function (err, txt) {
  473. if (err) {
  474. cb(err);
  475. }
  476. else {
  477. try {
  478. var result = JSON.parse(txt);
  479. }
  480. catch (e) {
  481. throw new Error("parse json [" + url + "] failed : " + e);
  482. return;
  483. }
  484. cb(null, result);
  485. }
  486. });
  487. },
  488. _checkIsImageURL: function (url) {
  489. var ext = /(\.png)|(\.jpg)|(\.bmp)|(\.jpeg)|(\.gif)/.exec(url);
  490. return (ext != null);
  491. },
  492. loadImg: function (url, option, callback) {
  493. var opt = {
  494. isCrossOrigin: true
  495. };
  496. if (callback !== undefined)
  497. opt.isCrossOrigin = option.isCrossOrigin === undefined ? opt.isCrossOrigin : option.isCrossOrigin;
  498. else if (option !== undefined)
  499. callback = option;
  500. var img = this.getRes(url);
  501. if (img) {
  502. callback && callback(null, img);
  503. return img;
  504. }
  505. var queue = _queue[url];
  506. if (queue) {
  507. queue.callbacks.push(callback);
  508. return queue.img;
  509. }
  510. img = new Image();
  511. if (opt.isCrossOrigin && location.origin !== "file://")
  512. img.crossOrigin = "Anonymous";
  513. var loadCallback = function () {
  514. this.removeEventListener('load', loadCallback, false);
  515. this.removeEventListener('error', errorCallback, false);
  516. if (!_urlRegExp.test(url)) {
  517. cc.loader.cache[url] = img;
  518. }
  519. var queue = _queue[url];
  520. if (queue) {
  521. var callbacks = queue.callbacks;
  522. for (var i = 0; i < callbacks.length; ++i) {
  523. var cb = callbacks[i];
  524. if (cb) {
  525. cb(null, img);
  526. }
  527. }
  528. queue.img = null;
  529. delete _queue[url];
  530. }
  531. };
  532. var self = this;
  533. var errorCallback = function () {
  534. this.removeEventListener('error', errorCallback, false);
  535. if (img.crossOrigin && img.crossOrigin.toLowerCase() === "anonymous") {
  536. opt.isCrossOrigin = false;
  537. self.release(url);
  538. cc.loader.loadImg(url, opt, callback);
  539. } else {
  540. var queue = _queue[url];
  541. if (queue) {
  542. var callbacks = queue.callbacks;
  543. for (var i = 0; i < callbacks.length; ++i) {
  544. var cb = callbacks[i];
  545. if (cb) {
  546. cb("load image failed");
  547. }
  548. }
  549. queue.img = null;
  550. delete _queue[url];
  551. }
  552. }
  553. };
  554. _queue[url] = {
  555. img: img,
  556. callbacks: callback ? [callback] : []
  557. };
  558. img.addEventListener("load", loadCallback);
  559. img.addEventListener("error", errorCallback);
  560. img.src = url;
  561. return img;
  562. },
  563. _loadResIterator: function (item, index, cb) {
  564. var self = this, url = null;
  565. var type = item.type;
  566. if (type) {
  567. type = "." + type.toLowerCase();
  568. url = item.src ? item.src : item.name + type;
  569. } else {
  570. url = item;
  571. type = cc.path.extname(url);
  572. }
  573. var obj = self.getRes(url);
  574. if (obj)
  575. return cb(null, obj);
  576. var loader = null;
  577. if (type) {
  578. loader = _register[type.toLowerCase()];
  579. }
  580. if (!loader) {
  581. cc.error("loader for [" + type + "] not exists!");
  582. return cb();
  583. }
  584. var realUrl = url;
  585. if (!_urlRegExp.test(url))
  586. {
  587. var basePath = loader.getBasePath ? loader.getBasePath() : self.resPath;
  588. realUrl = self.getUrl(basePath, url);
  589. }
  590. if(cc.game.config["noCache"] && typeof realUrl === "string"){
  591. if(self._noCacheRex.test(realUrl))
  592. realUrl += "&_t=" + (new Date() - 0);
  593. else
  594. realUrl += "?_t=" + (new Date() - 0);
  595. }
  596. loader.load(realUrl, url, item, function (err, data) {
  597. if (err) {
  598. cc.log(err);
  599. self.cache[url] = null;
  600. delete self.cache[url];
  601. cb({status:520, errorMessage:err}, null);
  602. } else {
  603. self.cache[url] = data;
  604. cb(null, data);
  605. }
  606. });
  607. },
  608. _noCacheRex: /\?/,
  609. getUrl: function (basePath, url) {
  610. var self = this, path = cc.path;
  611. if (basePath !== undefined && url === undefined) {
  612. url = basePath;
  613. var type = path.extname(url);
  614. type = type ? type.toLowerCase() : "";
  615. var loader = _register[type];
  616. if (!loader)
  617. basePath = self.resPath;
  618. else
  619. basePath = loader.getBasePath ? loader.getBasePath() : self.resPath;
  620. }
  621. url = cc.path.join(basePath || "", url);
  622. if (url.match(/[\/(\\\\)]lang[\/(\\\\)]/i)) {
  623. if (_langPathCache[url])
  624. return _langPathCache[url];
  625. var extname = path.extname(url) || "";
  626. url = _langPathCache[url] = url.substring(0, url.length - extname.length) + "_" + cc.sys.language + extname;
  627. }
  628. return url;
  629. },
  630. load : function(resources, option, loadCallback){
  631. var self = this;
  632. var len = arguments.length;
  633. if(len === 0)
  634. throw new Error("arguments error!");
  635. if(len === 3){
  636. if(typeof option === "function"){
  637. if(typeof loadCallback === "function")
  638. option = {trigger : option, cb : loadCallback };
  639. else
  640. option = { cb : option, cbTarget : loadCallback};
  641. }
  642. }else if(len === 2){
  643. if(typeof option === "function")
  644. option = {cb : option};
  645. }else if(len === 1){
  646. option = {};
  647. }
  648. if(!(resources instanceof Array))
  649. resources = [resources];
  650. var asyncPool = new cc.AsyncPool(
  651. resources, 0,
  652. function (value, index, AsyncPoolCallback, aPool) {
  653. self._loadResIterator(value, index, function (err) {
  654. var arr = Array.prototype.slice.call(arguments, 1);
  655. if (option.trigger)
  656. option.trigger.call(option.triggerTarget, arr[0], aPool.size, aPool.finishedSize);
  657. AsyncPoolCallback(err, arr[0]);
  658. });
  659. },
  660. option.cb, option.cbTarget);
  661. asyncPool.flow();
  662. return asyncPool;
  663. },
  664. _handleAliases: function (fileNames, cb) {
  665. var self = this;
  666. var resList = [];
  667. for (var key in fileNames) {
  668. var value = fileNames[key];
  669. _aliases[key] = value;
  670. resList.push(value);
  671. }
  672. this.load(resList, cb);
  673. },
  674. loadAliases: function (url, callback) {
  675. var self = this, dict = self.getRes(url);
  676. if (!dict) {
  677. self.load(url, function (err, results) {
  678. self._handleAliases(results[0]["filenames"], callback);
  679. });
  680. } else
  681. self._handleAliases(dict["filenames"], callback);
  682. },
  683. register: function (extNames, loader) {
  684. if (!extNames || !loader) return;
  685. var self = this;
  686. if (typeof extNames === "string")
  687. return _register[extNames.trim().toLowerCase()] = loader;
  688. for (var i = 0, li = extNames.length; i < li; i++) {
  689. _register["." + extNames[i].trim().toLowerCase()] = loader;
  690. }
  691. },
  692. getRes: function (url) {
  693. return this.cache[url] || this.cache[_aliases[url]];
  694. },
  695. _getAliase: function (url) {
  696. return _aliases[url];
  697. },
  698. release: function (url) {
  699. var cache = this.cache;
  700. var queue = _queue[url];
  701. if (queue) {
  702. queue.img = null;
  703. delete _queue[url];
  704. }
  705. delete cache[url];
  706. delete cache[_aliases[url]];
  707. delete _aliases[url];
  708. },
  709. releaseAll: function () {
  710. var locCache = this.cache;
  711. for (var key in locCache)
  712. delete locCache[key];
  713. for (var key in _aliases)
  714. delete _aliases[key];
  715. }
  716. };
  717. })();
  718. cc.formatStr = function(){
  719. var args = arguments;
  720. var l = args.length;
  721. if(l < 1)
  722. return "";
  723. var str = args[0];
  724. var needToFormat = true;
  725. if(typeof str === "object"){
  726. needToFormat = false;
  727. }
  728. for(var i = 1; i < l; ++i){
  729. var arg = args[i];
  730. if(needToFormat){
  731. while(true){
  732. var result = null;
  733. if(typeof arg === "number"){
  734. result = str.match(/(%d)|(%s)/);
  735. if(result){
  736. str = str.replace(/(%d)|(%s)/, arg);
  737. break;
  738. }
  739. }
  740. result = str.match(/%s/);
  741. if(result)
  742. str = str.replace(/%s/, arg);
  743. else
  744. str += " " + arg;
  745. break;
  746. }
  747. }else
  748. str += " " + arg;
  749. }
  750. return str;
  751. };
  752. (function () {
  753. var _tmpCanvas1 = document.createElement("canvas"),
  754. _tmpCanvas2 = document.createElement("canvas");
  755. cc.create3DContext = function (canvas, opt_attribs) {
  756. var names = ["webgl", "experimental-webgl", "webkit-3d", "moz-webgl"];
  757. var context = null;
  758. for (var ii = 0; ii < names.length; ++ii) {
  759. try {
  760. context = canvas.getContext(names[ii], opt_attribs);
  761. } catch (e) {
  762. }
  763. if (context) {
  764. break;
  765. }
  766. }
  767. return context;
  768. };
  769. var _initSys = function () {
  770. cc.sys = {};
  771. var sys = cc.sys;
  772. sys.LANGUAGE_ENGLISH = "en";
  773. sys.LANGUAGE_CHINESE = "zh";
  774. sys.LANGUAGE_FRENCH = "fr";
  775. sys.LANGUAGE_ITALIAN = "it";
  776. sys.LANGUAGE_GERMAN = "de";
  777. sys.LANGUAGE_SPANISH = "es";
  778. sys.LANGUAGE_DUTCH = "du";
  779. sys.LANGUAGE_RUSSIAN = "ru";
  780. sys.LANGUAGE_KOREAN = "ko";
  781. sys.LANGUAGE_JAPANESE = "ja";
  782. sys.LANGUAGE_HUNGARIAN = "hu";
  783. sys.LANGUAGE_PORTUGUESE = "pt";
  784. sys.LANGUAGE_ARABIC = "ar";
  785. sys.LANGUAGE_NORWEGIAN = "no";
  786. sys.LANGUAGE_POLISH = "pl";
  787. sys.LANGUAGE_UNKNOWN = "unkonwn";
  788. sys.OS_IOS = "iOS";
  789. sys.OS_ANDROID = "Android";
  790. sys.OS_WINDOWS = "Windows";
  791. sys.OS_MARMALADE = "Marmalade";
  792. sys.OS_LINUX = "Linux";
  793. sys.OS_BADA = "Bada";
  794. sys.OS_BLACKBERRY = "Blackberry";
  795. sys.OS_OSX = "OS X";
  796. sys.OS_WP8 = "WP8";
  797. sys.OS_WINRT = "WINRT";
  798. sys.OS_UNKNOWN = "Unknown";
  799. sys.UNKNOWN = -1;
  800. sys.WIN32 = 0;
  801. sys.LINUX = 1;
  802. sys.MACOS = 2;
  803. sys.ANDROID = 3;
  804. sys.IPHONE = 4;
  805. sys.IPAD = 5;
  806. sys.BLACKBERRY = 6;
  807. sys.NACL = 7;
  808. sys.EMSCRIPTEN = 8;
  809. sys.TIZEN = 9;
  810. sys.WINRT = 10;
  811. sys.WP8 = 11;
  812. sys.MOBILE_BROWSER = 100;
  813. sys.DESKTOP_BROWSER = 101;
  814. sys.BROWSER_TYPE_WECHAT = "wechat";
  815. sys.BROWSER_TYPE_ANDROID = "androidbrowser";
  816. sys.BROWSER_TYPE_IE = "ie";
  817. sys.BROWSER_TYPE_QQ = "qqbrowser";
  818. sys.BROWSER_TYPE_MOBILE_QQ = "mqqbrowser";
  819. sys.BROWSER_TYPE_UC = "ucbrowser";
  820. sys.BROWSER_TYPE_360 = "360browser";
  821. sys.BROWSER_TYPE_BAIDU_APP = "baiduboxapp";
  822. sys.BROWSER_TYPE_BAIDU = "baidubrowser";
  823. sys.BROWSER_TYPE_MAXTHON = "maxthon";
  824. sys.BROWSER_TYPE_OPERA = "opera";
  825. sys.BROWSER_TYPE_OUPENG = "oupeng";
  826. sys.BROWSER_TYPE_MIUI = "miuibrowser";
  827. sys.BROWSER_TYPE_FIREFOX = "firefox";
  828. sys.BROWSER_TYPE_SAFARI = "safari";
  829. sys.BROWSER_TYPE_CHROME = "chrome";
  830. sys.BROWSER_TYPE_LIEBAO = "liebao";
  831. sys.BROWSER_TYPE_QZONE = "qzone";
  832. sys.BROWSER_TYPE_SOUGOU = "sogou";
  833. sys.BROWSER_TYPE_UNKNOWN = "unknown";
  834. sys.isNative = false;
  835. var win = window, nav = win.navigator, doc = document, docEle = doc.documentElement;
  836. var ua = nav.userAgent.toLowerCase();
  837. sys.isMobile = ua.indexOf('mobile') !== -1 || ua.indexOf('android') !== -1;
  838. sys.platform = sys.isMobile ? sys.MOBILE_BROWSER : sys.DESKTOP_BROWSER;
  839. var currLanguage = nav.language;
  840. currLanguage = currLanguage ? currLanguage : nav.browserLanguage;
  841. currLanguage = currLanguage ? currLanguage.split("-")[0] : sys.LANGUAGE_ENGLISH;
  842. sys.language = currLanguage;
  843. var isAndroid = false, iOS = false, osVersion = '', osMainVersion = 0;
  844. var uaResult = /android (\d+(?:\.\d+)+)/i.exec(ua) || /android (\d+(?:\.\d+)+)/i.exec(nav.platform);
  845. if (uaResult) {
  846. isAndroid = true;
  847. osVersion = uaResult[1] || '';
  848. osMainVersion = parseInt(osVersion) || 0;
  849. }
  850. uaResult = /(iPad|iPhone|iPod).*OS ((\d+_?){2,3})/i.exec(ua);
  851. if (uaResult) {
  852. iOS = true;
  853. osVersion = uaResult[2] || '';
  854. osMainVersion = parseInt(osVersion) || 0;
  855. }
  856. var osName = sys.OS_UNKNOWN;
  857. if (nav.appVersion.indexOf("Win") !== -1) osName = sys.OS_WINDOWS;
  858. else if (iOS) osName = sys.OS_IOS;
  859. else if (nav.appVersion.indexOf("Mac") !== -1) osName = sys.OS_OSX;
  860. else if (nav.appVersion.indexOf("X11") !== -1 && nav.appVersion.indexOf("Linux") === -1) osName = sys.OS_UNIX;
  861. else if (isAndroid) osName = sys.OS_ANDROID;
  862. else if (nav.appVersion.indexOf("Linux") !== -1) osName = sys.OS_LINUX;
  863. sys.os = osName;
  864. sys.osVersion = osVersion;
  865. sys.osMainVersion = osMainVersion;
  866. sys.browserType = sys.BROWSER_TYPE_UNKNOWN;
  867. (function(){
  868. var typeReg1 = /mqqbrowser|sogou|qzone|liebao|micromessenger|ucbrowser|360 aphone|360browser|baiduboxapp|baidubrowser|maxthon|mxbrowser|trident|miuibrowser/i;
  869. var typeReg2 = /qqbrowser|chrome|safari|firefox|opr|oupeng|opera/i;
  870. var browserTypes = typeReg1.exec(ua);
  871. if(!browserTypes) browserTypes = typeReg2.exec(ua);
  872. var browserType = browserTypes ? browserTypes[0] : sys.BROWSER_TYPE_UNKNOWN;
  873. if (browserType === 'micromessenger')
  874. browserType = sys.BROWSER_TYPE_WECHAT;
  875. else if (browserType === "safari" && (ua.match(/android.*applewebkit/)))
  876. browserType = sys.BROWSER_TYPE_ANDROID;
  877. else if (browserType === "trident")
  878. browserType = sys.BROWSER_TYPE_IE;
  879. else if (browserType === "360 aphone")
  880. browserType = sys.BROWSER_TYPE_360;
  881. else if (browserType === "mxbrowser")
  882. browserType = sys.BROWSER_TYPE_MAXTHON;
  883. else if (browserType === "opr")
  884. browserType = sys.BROWSER_TYPE_OPERA;
  885. sys.browserType = browserType;
  886. })();
  887. sys.browserVersion = "";
  888. (function(){
  889. var versionReg1 = /(micromessenger|qq|mx|maxthon|baidu|sogou)(mobile)?(browser)?\/?([\d.]+)/i;
  890. var versionReg2 = /(msie |rv:|firefox|chrome|ucbrowser|oupeng|opera|opr|safari|miui)(mobile)?(browser)?\/?([\d.]+)/i;
  891. var tmp = ua.match(versionReg1);
  892. if(!tmp) tmp = ua.match(versionReg2);
  893. sys.browserVersion = tmp ? tmp[4] : "";
  894. })();
  895. var w = window.innerWidth || document.documentElement.clientWidth;
  896. var h = window.innerHeight || document.documentElement.clientHeight;
  897. var ratio = window.devicePixelRatio || 1;
  898. sys.windowPixelResolution = {
  899. width: ratio * w,
  900. height: ratio * h
  901. };
  902. sys._checkWebGLRenderMode = function () {
  903. if (cc._renderType !== cc.game.RENDER_TYPE_WEBGL)
  904. throw new Error("This feature supports WebGL render mode only.");
  905. };
  906. sys._supportCanvasNewBlendModes = (function(){
  907. var canvas = _tmpCanvas1;
  908. canvas.width = 1;
  909. canvas.height = 1;
  910. var context = canvas.getContext('2d');
  911. context.fillStyle = '#000';
  912. context.fillRect(0,0,1,1);
  913. context.globalCompositeOperation = 'multiply';
  914. var canvas2 = _tmpCanvas2;
  915. canvas2.width = 1;
  916. canvas2.height = 1;
  917. var context2 = canvas2.getContext('2d');
  918. context2.fillStyle = '#fff';
  919. context2.fillRect(0,0,1,1);
  920. context.drawImage(canvas2, 0, 0, 1, 1);
  921. return context.getImageData(0,0,1,1).data[0] === 0;
  922. })();
  923. if (cc.sys.isMobile) {
  924. var fontStyle = document.createElement("style");
  925. fontStyle.type = "text/css";
  926. document.body.appendChild(fontStyle);
  927. fontStyle.textContent = "body,canvas,div{ -moz-user-select: none;-webkit-user-select: none;-ms-user-select: none;-khtml-user-select: none;"
  928. + "-webkit-tap-highlight-color:rgba(0,0,0,0);}";
  929. }
  930. try {
  931. var localStorage = sys.localStorage = win.localStorage;
  932. localStorage.setItem("storage", "");
  933. localStorage.removeItem("storage");
  934. localStorage = null;
  935. } catch (e) {
  936. var warn = function () {
  937. cc.warn("Warning: localStorage isn't enabled. Please confirm browser cookie or privacy option");
  938. };
  939. sys.localStorage = {
  940. getItem : warn,
  941. setItem : warn,
  942. removeItem : warn,
  943. clear : warn
  944. };
  945. }
  946. var _supportCanvas = !!_tmpCanvas1.getContext("2d");
  947. var _supportWebGL = false;
  948. if (win.WebGLRenderingContext) {
  949. var tmpCanvas = document.createElement("CANVAS");
  950. try{
  951. var context = cc.create3DContext(tmpCanvas, {'stencil': true});
  952. if(context) {
  953. _supportWebGL = true;
  954. }
  955. if (_supportWebGL && sys.os === sys.OS_ANDROID) {
  956. var browserVer = parseFloat(sys.browserVersion);
  957. switch (sys.browserType) {
  958. case sys.BROWSER_TYPE_MOBILE_QQ:
  959. case sys.BROWSER_TYPE_BAIDU:
  960. case sys.BROWSER_TYPE_BAIDU_APP:
  961. if (browserVer >= 6.2) {
  962. _supportWebGL = true;
  963. }
  964. else {
  965. _supportWebGL = false;
  966. }
  967. break;
  968. case sys.BROWSER_TYPE_CHROME:
  969. if(browserVer >= 30.0) {
  970. _supportWebGL = true;
  971. } else {
  972. _supportWebGL = false;
  973. }
  974. break;
  975. case sys.BROWSER_TYPE_ANDROID:
  976. if (sys.osMainVersion && sys.osMainVersion >= 5) {
  977. _supportWebGL = true;
  978. }
  979. break;
  980. case sys.BROWSER_TYPE_UNKNOWN:
  981. case sys.BROWSER_TYPE_360:
  982. case sys.BROWSER_TYPE_MIUI:
  983. case sys.BROWSER_TYPE_UC:
  984. _supportWebGL = false;
  985. }
  986. }
  987. }
  988. catch (e) {}
  989. tmpCanvas = null;
  990. }
  991. var capabilities = sys.capabilities = {
  992. "canvas": _supportCanvas,
  993. "opengl": _supportWebGL
  994. };
  995. if (docEle['ontouchstart'] !== undefined || doc['ontouchstart'] !== undefined || nav.msPointerEnabled)
  996. capabilities["touches"] = true;
  997. if (docEle['onmouseup'] !== undefined)
  998. capabilities["mouse"] = true;
  999. if (docEle['onkeyup'] !== undefined)
  1000. capabilities["keyboard"] = true;
  1001. if (win.DeviceMotionEvent || win.DeviceOrientationEvent)
  1002. capabilities["accelerometer"] = true;
  1003. sys.garbageCollect = function () {
  1004. };
  1005. sys.dumpRoot = function () {
  1006. };
  1007. sys.restartVM = function () {
  1008. };
  1009. sys.cleanScript = function (jsfile) {
  1010. };
  1011. sys.isObjectValid = function (obj) {
  1012. if (obj) return true;
  1013. else return false;
  1014. };
  1015. sys.dump = function () {
  1016. var self = this;
  1017. var str = "";
  1018. str += "isMobile : " + self.isMobile + "\r\n";
  1019. str += "language : " + self.language + "\r\n";
  1020. str += "browserType : " + self.browserType + "\r\n";
  1021. str += "browserVersion : " + self.browserVersion + "\r\n";
  1022. str += "capabilities : " + JSON.stringify(self.capabilities) + "\r\n";
  1023. str += "os : " + self.os + "\r\n";
  1024. str += "osVersion : " + self.osVersion + "\r\n";
  1025. str += "platform : " + self.platform + "\r\n";
  1026. str += "Using " + (cc._renderType === cc.game.RENDER_TYPE_WEBGL ? "WEBGL" : "CANVAS") + " renderer." + "\r\n";
  1027. cc.log(str);
  1028. };
  1029. sys.openURL = function(url){
  1030. window.open(url);
  1031. };
  1032. };
  1033. _initSys();
  1034. _tmpCanvas1 = null;
  1035. _tmpCanvas2 = null;
  1036. cc.log = cc.warn = cc.error = cc.assert = function () {
  1037. };
  1038. var _config = null,
  1039. _jsAddedCache = {},
  1040. _engineInitCalled = false,
  1041. _engineLoadedCallback = null;
  1042. cc._engineLoaded = false;
  1043. function _determineRenderType(config) {
  1044. var CONFIG_KEY = cc.game.CONFIG_KEY,
  1045. userRenderMode = parseInt(config[CONFIG_KEY.renderMode]) || 0;
  1046. if (isNaN(userRenderMode) || userRenderMode > 2 || userRenderMode < 0)
  1047. config[CONFIG_KEY.renderMode] = 0;
  1048. cc._renderType = cc.game.RENDER_TYPE_CANVAS;
  1049. cc._supportRender = false;
  1050. if (userRenderMode === 0) {
  1051. if (cc.sys.capabilities["opengl"]) {
  1052. cc._renderType = cc.game.RENDER_TYPE_WEBGL;
  1053. cc._supportRender = true;
  1054. }
  1055. else if (cc.sys.capabilities["canvas"]) {
  1056. cc._renderType = cc.game.RENDER_TYPE_CANVAS;
  1057. cc._supportRender = true;
  1058. }
  1059. }
  1060. else if (userRenderMode === 1 && cc.sys.capabilities["canvas"]) {
  1061. cc._renderType = cc.game.RENDER_TYPE_CANVAS;
  1062. cc._supportRender = true;
  1063. }
  1064. else if (userRenderMode === 2 && cc.sys.capabilities["opengl"]) {
  1065. cc._renderType = cc.game.RENDER_TYPE_WEBGL;
  1066. cc._supportRender = true;
  1067. }
  1068. }
  1069. function _getJsListOfModule(moduleMap, moduleName, dir) {
  1070. if (_jsAddedCache[moduleName]) return null;
  1071. dir = dir || "";
  1072. var jsList = [];
  1073. var tempList = moduleMap[moduleName];
  1074. if (!tempList) throw new Error("can not find module [" + moduleName + "]");
  1075. var ccPath = cc.path;
  1076. for (var i = 0, li = tempList.length; i < li; i++) {
  1077. var item = tempList[i];
  1078. if (_jsAddedCache[item]) continue;
  1079. var extname = ccPath.extname(item);
  1080. if (!extname) {
  1081. var arr = _getJsListOfModule(moduleMap, item, dir);
  1082. if (arr) jsList = jsList.concat(arr);
  1083. } else if (extname.toLowerCase() === ".js") jsList.push(ccPath.join(dir, item));
  1084. _jsAddedCache[item] = 1;
  1085. }
  1086. return jsList;
  1087. }
  1088. function _afterEngineLoaded(config) {
  1089. if (cc._initDebugSetting)
  1090. cc._initDebugSetting(config[cc.game.CONFIG_KEY.debugMode]);
  1091. cc._engineLoaded = true;
  1092. cc.log(cc.ENGINE_VERSION);
  1093. if (_engineLoadedCallback) _engineLoadedCallback();
  1094. }
  1095. function _load(config) {
  1096. var self = this;
  1097. var CONFIG_KEY = cc.game.CONFIG_KEY, engineDir = config[CONFIG_KEY.engineDir], loader = cc.loader;
  1098. if (cc.Class) {
  1099. _afterEngineLoaded(config);
  1100. } else {
  1101. var ccModulesPath = cc.path.join(engineDir, "moduleConfig.json");
  1102. loader.loadJson(ccModulesPath, function (err, modulesJson) {
  1103. if (err) throw new Error(err);
  1104. var modules = config["modules"] || [];
  1105. var moduleMap = modulesJson["module"];
  1106. var jsList = [];
  1107. if (cc.sys.capabilities["opengl"] && modules.indexOf("base4webgl") < 0) modules.splice(0, 0, "base4webgl");
  1108. else if (modules.indexOf("core") < 0) modules.splice(0, 0, "core");
  1109. for (var i = 0, li = modules.length; i < li; i++) {
  1110. var arr = _getJsListOfModule(moduleMap, modules[i], engineDir);
  1111. if (arr) jsList = jsList.concat(arr);
  1112. }
  1113. cc.loader.loadJsWithImg(jsList, function (err) {
  1114. if (err) throw err;
  1115. _afterEngineLoaded(config);
  1116. });
  1117. });
  1118. }
  1119. }
  1120. function _windowLoaded() {
  1121. this.removeEventListener('load', _windowLoaded, false);
  1122. _load(cc.game.config);
  1123. }
  1124. cc.initEngine = function (config, cb) {
  1125. if (_engineInitCalled) {
  1126. var previousCallback = _engineLoadedCallback;
  1127. _engineLoadedCallback = function () {
  1128. previousCallback && previousCallback();
  1129. cb && cb();
  1130. }
  1131. return;
  1132. }
  1133. _engineLoadedCallback = cb;
  1134. if (!cc.game.config && config) {
  1135. cc.game.config = config;
  1136. }
  1137. else if (!cc.game.config) {
  1138. cc.game._loadConfig();
  1139. }
  1140. config = cc.game.config;
  1141. _determineRenderType(config);
  1142. document.body ? _load(config) : cc._addEventListener(window, 'load', _windowLoaded, false);
  1143. _engineInitCalled = true;
  1144. };
  1145. })();
  1146. cc.game = {
  1147. DEBUG_MODE_NONE: 0,
  1148. DEBUG_MODE_INFO: 1,
  1149. DEBUG_MODE_WARN: 2,
  1150. DEBUG_MODE_ERROR: 3,
  1151. DEBUG_MODE_INFO_FOR_WEB_PAGE: 4,
  1152. DEBUG_MODE_WARN_FOR_WEB_PAGE: 5,
  1153. DEBUG_MODE_ERROR_FOR_WEB_PAGE: 6,
  1154. EVENT_HIDE: "game_on_hide",
  1155. EVENT_SHOW: "game_on_show",
  1156. EVENT_RESIZE: "game_on_resize",
  1157. EVENT_RENDERER_INITED: "renderer_inited",
  1158. RENDER_TYPE_CANVAS: 0,
  1159. RENDER_TYPE_WEBGL: 1,
  1160. RENDER_TYPE_OPENGL: 2,
  1161. _eventHide: null,
  1162. _eventShow: null,
  1163. CONFIG_KEY: {
  1164. width: "width",
  1165. height: "height",
  1166. engineDir: "engineDir",
  1167. modules: "modules",
  1168. debugMode: "debugMode",
  1169. showFPS: "showFPS",
  1170. frameRate: "frameRate",
  1171. id: "id",
  1172. renderMode: "renderMode",
  1173. jsList: "jsList"
  1174. },
  1175. _paused: true,//whether the game is paused
  1176. _prepareCalled: false,//whether the prepare function has been called
  1177. _prepared: false,//whether the engine has prepared
  1178. _rendererInitialized: false,
  1179. _renderContext: null,
  1180. _intervalId: null,//interval target of main
  1181. _lastTime: null,
  1182. _frameTime: null,
  1183. frame: null,
  1184. container: null,
  1185. canvas: null,
  1186. config: null,
  1187. onStart: null,
  1188. onStop: null,
  1189. setFrameRate: function (frameRate) {
  1190. var self = this, config = self.config, CONFIG_KEY = self.CONFIG_KEY;
  1191. config[CONFIG_KEY.frameRate] = frameRate;
  1192. if (self._intervalId)
  1193. window.cancelAnimationFrame(self._intervalId);
  1194. self._paused = true;
  1195. self._setAnimFrame();
  1196. self._runMainLoop();
  1197. },
  1198. step: function () {
  1199. cc.director.mainLoop();
  1200. },
  1201. pause: function () {
  1202. if (this._paused) return;
  1203. this._paused = true;
  1204. if (cc.audioEngine) {
  1205. cc.audioEngine.stopAllEffects();
  1206. cc.audioEngine.pauseMusic();
  1207. }
  1208. if (this._intervalId)
  1209. window.cancelAnimationFrame(this._intervalId);
  1210. this._intervalId = 0;
  1211. },
  1212. resume: function () {
  1213. if (!this._paused) return;
  1214. this._paused = false;
  1215. if (cc.audioEngine) {
  1216. cc.audioEngine.resumeMusic();
  1217. }
  1218. this._runMainLoop();
  1219. },
  1220. isPaused: function () {
  1221. return this._paused;
  1222. },
  1223. restart: function () {
  1224. cc.director.popToSceneStackLevel(0);
  1225. cc.audioEngine && cc.audioEngine.end();
  1226. cc.game.onStart();
  1227. },
  1228. end: function () {
  1229. close();
  1230. },
  1231. prepare: function (cb) {
  1232. var self = this,
  1233. config = self.config,
  1234. CONFIG_KEY = self.CONFIG_KEY;
  1235. this._loadConfig();
  1236. if (this._prepared) {
  1237. if (cb) cb();
  1238. return;
  1239. }
  1240. if (this._prepareCalled) {
  1241. return;
  1242. }
  1243. if (cc._engineLoaded) {
  1244. this._prepareCalled = true;
  1245. this._initRenderer(config[CONFIG_KEY.width], config[CONFIG_KEY.height]);
  1246. cc.view = cc.EGLView._getInstance();
  1247. cc.director = cc.Director._getInstance();
  1248. if (cc.director.setOpenGLView)
  1249. cc.director.setOpenGLView(cc.view);
  1250. cc.winSize = cc.director.getWinSize();
  1251. this._initEvents();
  1252. this._setAnimFrame();
  1253. this._runMainLoop();
  1254. var jsList = config[CONFIG_KEY.jsList];
  1255. if (jsList) {
  1256. cc.loader.loadJsWithImg(jsList, function (err) {
  1257. if (err) throw new Error(err);
  1258. self._prepared = true;
  1259. if (cb) cb();
  1260. });
  1261. }
  1262. else {
  1263. if (cb) cb();
  1264. }
  1265. return;
  1266. }
  1267. cc.initEngine(this.config, function () {
  1268. self.prepare(cb);
  1269. });
  1270. },
  1271. run: function (config, onStart) {
  1272. if (typeof config === 'function') {
  1273. cc.game.onStart = config;
  1274. }
  1275. else {
  1276. if (config) {
  1277. if (typeof config === 'string') {
  1278. if (!cc.game.config) this._loadConfig();
  1279. cc.game.config[cc.game.CONFIG_KEY.id] = config;
  1280. } else {
  1281. cc.game.config = config;
  1282. }
  1283. }
  1284. if (typeof onStart === 'function') {
  1285. cc.game.onStart = onStart;
  1286. }
  1287. }
  1288. this.prepare(cc.game.onStart && cc.game.onStart.bind(cc.game));
  1289. },
  1290. _setAnimFrame: function () {
  1291. this._lastTime = new Date();
  1292. this._frameTime = 1000 / cc.game.config[cc.game.CONFIG_KEY.frameRate];
  1293. if((cc.sys.os === cc.sys.OS_IOS && cc.sys.browserType === cc.sys.BROWSER_TYPE_WECHAT) || cc.game.config[cc.game.CONFIG_KEY.frameRate] !== 60) {
  1294. window.requestAnimFrame = this._stTime;
  1295. window.cancelAnimationFrame = this._ctTime;
  1296. }
  1297. else {
  1298. window.requestAnimFrame = window.requestAnimationFrame ||
  1299. window.webkitRequestAnimationFrame ||
  1300. window.mozRequestAnimationFrame ||
  1301. window.oRequestAnimationFrame ||
  1302. window.msRequestAnimationFrame ||
  1303. this._stTime;
  1304. window.cancelAnimationFrame = window.cancelAnimationFrame ||
  1305. window.cancelRequestAnimationFrame ||
  1306. window.msCancelRequestAnimationFrame ||
  1307. window.mozCancelRequestAnimationFrame ||
  1308. window.oCancelRequestAnimationFrame ||
  1309. window.webkitCancelRequestAnimationFrame ||
  1310. window.msCancelAnimationFrame ||
  1311. window.mozCancelAnimationFrame ||
  1312. window.webkitCancelAnimationFrame ||
  1313. window.oCancelAnimationFrame ||
  1314. this._ctTime;
  1315. }
  1316. },
  1317. _stTime: function(callback){
  1318. var currTime = new Date().getTime();
  1319. var timeToCall = Math.max(0, cc.game._frameTime - (currTime - cc.game._lastTime));
  1320. var id = window.setTimeout(function() { callback(); },
  1321. timeToCall);
  1322. cc.game._lastTime = currTime + timeToCall;
  1323. return id;
  1324. },
  1325. _ctTime: function(id){
  1326. window.clearTimeout(id);
  1327. },
  1328. _runMainLoop: function () {
  1329. var self = this, callback, config = self.config, CONFIG_KEY = self.CONFIG_KEY,
  1330. director = cc.director;
  1331. director.setDisplayStats(config[CONFIG_KEY.showFPS]);
  1332. callback = function () {
  1333. if (!self._paused) {
  1334. director.mainLoop();
  1335. if(self._intervalId)
  1336. window.cancelAnimationFrame(self._intervalId);
  1337. self._intervalId = window.requestAnimFrame(callback);
  1338. }
  1339. };
  1340. window.requestAnimFrame(callback);
  1341. self._paused = false;
  1342. },
  1343. _loadConfig: function () {
  1344. if (this.config) {
  1345. this._initConfig(this.config);
  1346. return;
  1347. }
  1348. if (document["ccConfig"]) {
  1349. this._initConfig(document["ccConfig"]);
  1350. }
  1351. else {
  1352. var data = {};
  1353. try {
  1354. var cocos_script = document.getElementsByTagName('script');
  1355. for(var i = 0; i < cocos_script.length; i++){
  1356. var _t = cocos_script[i].getAttribute('cocos');
  1357. if(_t === '' || _t) {
  1358. break;
  1359. }
  1360. }
  1361. var _src, txt, _resPath;
  1362. if(i < cocos_script.length){
  1363. _src = cocos_script[i].src;
  1364. if(_src){
  1365. _resPath = /(.*)\//.exec(_src)[0];
  1366. cc.loader.resPath = _resPath;
  1367. _src = cc.path.join(_resPath, 'project.json');
  1368. }
  1369. txt = cc.loader._loadTxtSync(_src);
  1370. }
  1371. if(!txt){
  1372. txt = cc.loader._loadTxtSync("project.json");
  1373. }
  1374. data = JSON.parse(txt);
  1375. } catch (e) {
  1376. cc.log("Failed to read or parse project.json");
  1377. }
  1378. this._initConfig(data);
  1379. }
  1380. },
  1381. _initConfig: function (config) {
  1382. var CONFIG_KEY = this.CONFIG_KEY,
  1383. modules = config[CONFIG_KEY.modules];
  1384. config[CONFIG_KEY.showFPS] = typeof config[CONFIG_KEY.showFPS] === 'undefined' ? true : config[CONFIG_KEY.showFPS];
  1385. config[CONFIG_KEY.engineDir] = config[CONFIG_KEY.engineDir] || "frameworks/cocos2d-html5";
  1386. if (config[CONFIG_KEY.debugMode] == null)
  1387. config[CONFIG_KEY.debugMode] = 0;
  1388. config[CONFIG_KEY.frameRate] = config[CONFIG_KEY.frameRate] || 60;
  1389. if (config[CONFIG_KEY.renderMode] == null)
  1390. config[CONFIG_KEY.renderMode] = 0;
  1391. if (config[CONFIG_KEY.registerSystemEvent] == null)
  1392. config[CONFIG_KEY.registerSystemEvent] = true;
  1393. if (modules && modules.indexOf("core") < 0) modules.splice(0, 0, "core");
  1394. modules && (config[CONFIG_KEY.modules] = modules);
  1395. this.config = config;
  1396. },
  1397. _initRenderer: function (width, height) {
  1398. if (this._rendererInitialized) return;
  1399. if (!cc._supportRender) {
  1400. throw new Error("The renderer doesn't support the renderMode " + this.config[this.CONFIG_KEY.renderMode]);
  1401. }
  1402. var el = this.config[cc.game.CONFIG_KEY.id],
  1403. win = window,
  1404. element = cc.$(el) || cc.$('#' + el),
  1405. localCanvas, localContainer, localConStyle;
  1406. if (element.tagName === "CANVAS") {
  1407. width = width || element.width;
  1408. height = height || element.height;
  1409. this.canvas = cc._canvas = localCanvas = element;
  1410. this.container = cc.container = localContainer = document.createElement("DIV");
  1411. if (localCanvas.parentNode)
  1412. localCanvas.parentNode.insertBefore(localContainer, localCanvas);
  1413. } else {
  1414. if (element.tagName !== "DIV") {
  1415. cc.log("Warning: target element is not a DIV or CANVAS");
  1416. }
  1417. width = width || element.clientWidth;
  1418. height = height || element.clientHeight;
  1419. this.canvas = cc._canvas = localCanvas = document.createElement("CANVAS");
  1420. this.container = cc.container = localContainer = document.createElement("DIV");
  1421. element.appendChild(localContainer);
  1422. }
  1423. localContainer.setAttribute('id', 'Cocos2dGameContainer');
  1424. localContainer.appendChild(localCanvas);
  1425. this.frame = (localContainer.parentNode === document.body) ? document.documentElement : localContainer.parentNode;
  1426. localCanvas.addClass("gameCanvas");
  1427. localCanvas.setAttribute("width", width || 480);
  1428. localCanvas.setAttribute("height", height || 320);
  1429. localCanvas.setAttribute("tabindex", 99);
  1430. if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) {
  1431. this._renderContext = cc._renderContext = cc.webglContext
  1432. = cc.create3DContext(localCanvas, {
  1433. 'stencil': true,
  1434. 'antialias': !cc.sys.isMobile,
  1435. 'alpha': false
  1436. });
  1437. }
  1438. if (this._renderContext) {
  1439. cc.renderer = cc.rendererWebGL;
  1440. win.gl = this._renderContext;
  1441. cc.renderer.init();
  1442. cc.shaderCache._init();
  1443. cc._drawingUtil = new cc.DrawingPrimitiveWebGL(this._renderContext);
  1444. cc.textureCache._initializingRenderer();
  1445. cc.glExt = {};
  1446. cc.glExt.instanced_arrays = win.gl.getExtension("ANGLE_instanced_arrays");
  1447. cc.glExt.element_uint = win.gl.getExtension("OES_element_index_uint");
  1448. } else {
  1449. cc._renderType = cc.game.RENDER_TYPE_CANVAS;
  1450. cc.renderer = cc.rendererCanvas;
  1451. this._renderContext = cc._renderContext = new cc.CanvasContextWrapper(localCanvas.getContext("2d"));
  1452. cc._drawingUtil = cc.DrawingPrimitiveCanvas ? new cc.DrawingPrimitiveCanvas(this._renderContext) : null;
  1453. }
  1454. cc._gameDiv = localContainer;
  1455. cc.game.canvas.oncontextmenu = function () {
  1456. if (!cc._isContextMenuEnable) return false;
  1457. };
  1458. this.dispatchEvent(this.EVENT_RENDERER_INITED, true);
  1459. this._rendererInitialized = true;
  1460. },
  1461. _initEvents: function () {
  1462. var win = window, self = this, hidden, visibilityChange, _undef = "undefined";
  1463. this._eventHide = this._eventHide || new cc.EventCustom(this.EVENT_HIDE);
  1464. this._eventHide.setUserData(this);
  1465. this._eventShow = this._eventShow || new cc.EventCustom(this.EVENT_SHOW);
  1466. this._eventShow.setUserData(this);
  1467. if (this.config[this.CONFIG_KEY.registerSystemEvent])
  1468. cc.inputManager.registerSystemEvent(this.canvas);
  1469. if (!cc.isUndefined(document.hidden)) {
  1470. hidden = "hidden";
  1471. visibilityChange = "visibilitychange";
  1472. } else if (!cc.isUndefined(document.mozHidden)) {
  1473. hidden = "mozHidden";
  1474. visibilityChange = "mozvisibilitychange";
  1475. } else if (!cc.isUndefined(document.msHidden)) {
  1476. hidden = "msHidden";
  1477. visibilityChange = "msvisibilitychange";
  1478. } else if (!cc.isUndefined(document.webkitHidden)) {
  1479. hidden = "webkitHidden";
  1480. visibilityChange = "webkitvisibilitychange";
  1481. }
  1482. var onHidden = function () {
  1483. if (cc.eventManager && cc.game._eventHide)
  1484. cc.eventManager.dispatchEvent(cc.game._eventHide);
  1485. };
  1486. var onShow = function () {
  1487. if (cc.eventManager && cc.game._eventShow)
  1488. cc.eventManager.dispatchEvent(cc.game._eventShow);
  1489. };
  1490. if (hidden) {
  1491. document.addEventListener(visibilityChange, function () {
  1492. if (document[hidden]) onHidden();
  1493. else onShow();
  1494. }, false);
  1495. } else {
  1496. win.addEventListener("blur", onHidden, false);
  1497. win.addEventListener("focus", onShow, false);
  1498. }
  1499. if(navigator.userAgent.indexOf("MicroMessenger") > -1){
  1500. win.onfocus = function(){ onShow() };
  1501. }
  1502. if ("onpageshow" in window && "onpagehide" in window) {
  1503. win.addEventListener("pagehide", onHidden, false);
  1504. win.addEventListener("pageshow", onShow, false);
  1505. }
  1506. cc.eventManager.addCustomListener(cc.game.EVENT_HIDE, function () {
  1507. cc.game.pause();
  1508. });
  1509. cc.eventManager.addCustomListener(cc.game.EVENT_SHOW, function () {
  1510. cc.game.resume();
  1511. });
  1512. }
  1513. };
  1514. Function.prototype.bind = Function.prototype.bind || function (oThis) {
  1515. if (!cc.isFunction(this)) {
  1516. throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
  1517. }
  1518. var aArgs = Array.prototype.slice.call(arguments, 1),
  1519. fToBind = this,
  1520. fNOP = function () {},
  1521. fBound = function () {
  1522. return fToBind.apply(this instanceof fNOP && oThis
  1523. ? this
  1524. : oThis,
  1525. aArgs.concat(Array.prototype.slice.call(arguments)));
  1526. };
  1527. fNOP.prototype = this.prototype;
  1528. fBound.prototype = new fNOP();
  1529. return fBound;
  1530. };
  1531. cc._urlRegExp = new RegExp(
  1532. "^" +
  1533. "(?:(?:https?|ftp)://)" +
  1534. "(?:\\S+(?::\\S*)?@)?" +
  1535. "(?:" +
  1536. "(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" +
  1537. "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" +
  1538. "(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" +
  1539. "|" +
  1540. "(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)" +
  1541. "(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*" +
  1542. "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))" +
  1543. "|" +
  1544. "(?:localhost)" +
  1545. ")" +
  1546. "(?::\\d{2,5})?" +
  1547. "(?:/\\S*)?" +
  1548. "$", "i"
  1549. );
  1550. cc.SimplePool = function () {
  1551. this._pool = [];
  1552. };
  1553. cc.SimplePool.prototype = {
  1554. constructor: cc.SimplePool,
  1555. size: function () {
  1556. return this._pool.length;
  1557. },
  1558. put: function (obj) {
  1559. if (obj && this._pool.indexOf(obj) === -1) {
  1560. this._pool.unshift(obj);
  1561. }
  1562. },
  1563. get: function () {
  1564. var last = this._pool.length-1;
  1565. if (last < 0) {
  1566. return null;
  1567. }
  1568. else {
  1569. var obj = this._pool[last];
  1570. this._pool.length = last;
  1571. return obj;
  1572. }
  1573. },
  1574. find: function (finder, end) {
  1575. var found, i, obj, pool = this._pool, last = pool.length-1;
  1576. for (i = pool.length; i >= 0; --i) {
  1577. obj = pool[i];
  1578. found = finder(i, obj);
  1579. if (found) {
  1580. pool[i] = pool[last];
  1581. pool.length = last;
  1582. return obj;
  1583. }
  1584. }
  1585. if (end) {
  1586. var index = end();
  1587. if (index >= 0) {
  1588. pool[index] = pool[last];
  1589. pool.length = last;
  1590. return obj;
  1591. }
  1592. }
  1593. return null;
  1594. }
  1595. };
  1596. cc.EventHelper = function(){};
  1597. cc.EventHelper.prototype = {
  1598. constructor: cc.EventHelper,
  1599. apply: function ( object ) {
  1600. object.addEventListener = cc.EventHelper.prototype.addEventListener;
  1601. object.hasEventListener = cc.EventHelper.prototype.hasEventListener;
  1602. object.removeEventListener = cc.EventHelper.prototype.removeEventListener;
  1603. object.dispatchEvent = cc.EventHelper.prototype.dispatchEvent;
  1604. },
  1605. addEventListener: function ( type, listener, target ) {
  1606. if(type === "load" && this._textureLoaded){
  1607. setTimeout(function(){
  1608. listener.call(target);
  1609. }, 0);
  1610. return;
  1611. }
  1612. if ( this._listeners === undefined )
  1613. this._listeners = {};
  1614. var listeners = this._listeners;
  1615. if ( listeners[ type ] === undefined )
  1616. listeners[ type ] = [];
  1617. if ( !this.hasEventListener(type, listener, target))
  1618. listeners[ type ].push( {callback:listener, eventTarget: target} );
  1619. },
  1620. hasEventListener: function ( type, listener, target ) {
  1621. if ( this._listeners === undefined )
  1622. return false;
  1623. var listeners = this._listeners;
  1624. if ( listeners[ type ] !== undefined ) {
  1625. for(var i = 0, len = listeners.length; i < len ; i++){
  1626. var selListener = listeners[i];
  1627. if(selListener.callback === listener && selListener.eventTarget === target)
  1628. return true;
  1629. }
  1630. }
  1631. return false;
  1632. },
  1633. removeEventListener: function( type, listener, target){
  1634. if ( this._listeners === undefined )
  1635. return;
  1636. var listeners = this._listeners;
  1637. var listenerArray = listeners[ type ];
  1638. if ( listenerArray !== undefined ) {
  1639. for(var i = 0; i < listenerArray.length ; ){
  1640. var selListener = listenerArray[i];
  1641. if(selListener.eventTarget === target && selListener.callback === listener)
  1642. listenerArray.splice( i, 1 );
  1643. else
  1644. i++
  1645. }
  1646. }
  1647. },
  1648. removeEventTarget: function( type, listener, target){
  1649. if ( this._listeners === undefined )
  1650. return;
  1651. var listeners = this._listeners;
  1652. var listenerArray = listeners[ type ];
  1653. if ( listenerArray !== undefined ) {
  1654. for(var i = 0; i < listenerArray.length ; ){
  1655. var selListener = listenerArray[i];
  1656. if(selListener.eventTarget === target)
  1657. listenerArray.splice( i, 1 );
  1658. else
  1659. i++
  1660. }
  1661. }
  1662. },
  1663. dispatchEvent: function ( event, clearAfterDispatch ) {
  1664. if ( this._listeners === undefined )
  1665. return;
  1666. if(clearAfterDispatch == null)
  1667. clearAfterDispatch = true;
  1668. var listeners = this._listeners;
  1669. var listenerArray = listeners[ event];
  1670. if ( listenerArray !== undefined ) {
  1671. var array = [];
  1672. var length = listenerArray.length;
  1673. for ( var i = 0; i < length; i ++ ) {
  1674. array[ i ] = listenerArray[ i ];
  1675. }
  1676. for ( i = 0; i < length; i ++ ) {
  1677. array[ i ].callback.call( array[i].eventTarget, this );
  1678. }
  1679. if(clearAfterDispatch)
  1680. listenerArray.length = 0;
  1681. }
  1682. }
  1683. };
  1684. cc.EventHelper.prototype.apply(cc.game);
  1685. var cc = cc || {};
  1686. cc._loadingImage = "data:image/gif;base64,R0lGODlhEAAQALMNAD8/P7+/vyoqKlVVVX9/fxUVFUBAQGBgYMDAwC8vL5CQkP///wAAAP///wAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh+QQFAAANACwAAAAAEAAQAAAEO5DJSau9OOvNex0IMnDIsiCkiW6g6BmKYlBFkhSUEgQKlQCARG6nEBwOgl+QApMdCIRD7YZ5RjlGpCUCACH5BAUAAA0ALAAAAgAOAA4AAAQ6kLGB0JA4M7QW0hrngRllkYyhKAYqKUGguAws0ypLS8JxCLQDgXAIDg+FRKIA6v0SAECCBpXSkstMBAAh+QQFAAANACwAAAAACgAQAAAEOJDJORAac6K1kDSKYmydpASBUl0mqmRfaGTCcQgwcxDEke+9XO2WkxQSiUIuAQAkls0n7JgsWq8RACH5BAUAAA0ALAAAAAAOAA4AAAQ6kMlplDIzTxWC0oxwHALnDQgySAdBHNWFLAvCukc215JIZihVIZEogDIJACBxnCSXTcmwGK1ar1hrBAAh+QQFAAANACwAAAAAEAAKAAAEN5DJKc4RM+tDyNFTkSQF5xmKYmQJACTVpQSBwrpJNteZSGYoFWjIGCAQA2IGsVgglBOmEyoxIiMAIfkEBQAADQAsAgAAAA4ADgAABDmQSVZSKjPPBEDSGucJxyGA1XUQxAFma/tOpDlnhqIYN6MEAUXvF+zldrMBAjHoIRYLhBMqvSmZkggAIfkEBQAADQAsBgAAAAoAEAAABDeQyUmrnSWlYhMASfeFVbZdjHAcgnUQxOHCcqWylKEohqUEAYVkgEAMfkEJYrFA6HhKJsJCNFoiACH5BAUAAA0ALAIAAgAOAA4AAAQ3kMlJq704611SKloCAEk4lln3DQgyUMJxCBKyLAh1EMRR3wiDQmHY9SQslyIQUMRmlmVTIyRaIgA7";
  1687. cc._fpsImage = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAAgCAYAAAD9qabkAAAKQ2lDQ1BJQ0MgcHJvZmlsZQAAeNqdU3dYk/cWPt/3ZQ9WQtjwsZdsgQAiI6wIyBBZohCSAGGEEBJAxYWIClYUFRGcSFXEgtUKSJ2I4qAouGdBiohai1VcOO4f3Ke1fXrv7e371/u855zn/M55zw+AERImkeaiagA5UoU8Otgfj09IxMm9gAIVSOAEIBDmy8JnBcUAAPADeXh+dLA//AGvbwACAHDVLiQSx+H/g7pQJlcAIJEA4CIS5wsBkFIAyC5UyBQAyBgAsFOzZAoAlAAAbHl8QiIAqg0A7PRJPgUA2KmT3BcA2KIcqQgAjQEAmShHJAJAuwBgVYFSLALAwgCgrEAiLgTArgGAWbYyRwKAvQUAdo5YkA9AYACAmUIszAAgOAIAQx4TzQMgTAOgMNK/4KlfcIW4SAEAwMuVzZdL0jMUuJXQGnfy8ODiIeLCbLFCYRcpEGYJ5CKcl5sjE0jnA0zODAAAGvnRwf44P5Dn5uTh5mbnbO/0xaL+a/BvIj4h8d/+vIwCBAAQTs/v2l/l5dYDcMcBsHW/a6lbANpWAGjf+V0z2wmgWgrQevmLeTj8QB6eoVDIPB0cCgsL7SViob0w44s+/zPhb+CLfvb8QB7+23rwAHGaQJmtwKOD/XFhbnauUo7nywRCMW735yP+x4V//Y4p0eI0sVwsFYrxWIm4UCJNx3m5UpFEIcmV4hLpfzLxH5b9CZN3DQCshk/ATrYHtctswH7uAQKLDljSdgBAfvMtjBoLkQAQZzQyefcAAJO/+Y9AKwEAzZek4wAAvOgYXKiUF0zGCAAARKCBKrBBBwzBFKzADpzBHbzAFwJhBkRADCTAPBBCBuSAHAqhGJZBGVTAOtgEtbADGqARmuEQtMExOA3n4BJcgetwFwZgGJ7CGLyGCQRByAgTYSE6iBFijtgizggXmY4EImFINJKApCDpiBRRIsXIcqQCqUJqkV1II/ItchQ5jVxA+pDbyCAyivyKvEcxlIGyUQPUAnVAuagfGorGoHPRdDQPXYCWomvRGrQePYC2oqfRS+h1dAB9io5jgNExDmaM2WFcjIdFYIlYGibHFmPlWDVWjzVjHVg3dhUbwJ5h7wgkAouAE+wIXoQQwmyCkJBHWExYQ6gl7CO0EroIVwmDhDHCJyKTqE+0JXoS+cR4YjqxkFhGrCbuIR4hniVeJw4TX5NIJA7JkuROCiElkDJJC0lrSNtILaRTpD7SEGmcTCbrkG3J3uQIsoCsIJeRt5APkE+S+8nD5LcUOsWI4kwJoiRSpJQSSjVlP+UEpZ8yQpmgqlHNqZ7UCKqIOp9aSW2gdlAvU4epEzR1miXNmxZDy6Qto9XQmmlnafdoL+l0ugndgx5Fl9CX0mvoB+nn6YP0dwwNhg2Dx0hiKBlrGXsZpxi3GS+ZTKYF05eZyFQw1zIbmWeYD5hvVVgq9ip8FZHKEpU6lVaVfpXnqlRVc1U/1XmqC1SrVQ+rXlZ9pkZVs1DjqQnUFqvVqR1Vu6k2rs5Sd1KPUM9RX6O+X/2C+mMNsoaFRqCGSKNUY7fGGY0hFsYyZfFYQtZyVgPrLGuYTWJbsvnsTHYF+xt2L3tMU0NzqmasZpFmneZxzQEOxrHg8DnZnErOIc4NznstAy0/LbHWaq1mrX6tN9p62r7aYu1y7Rbt69rvdXCdQJ0snfU6bTr3dQm6NrpRuoW623XP6j7TY+t56Qn1yvUO6d3RR/Vt9KP1F+rv1u/RHzcwNAg2kBlsMThj8MyQY+hrmGm40fCE4agRy2i6kcRoo9FJoye4Ju6HZ+M1eBc+ZqxvHGKsNN5l3Gs8YWJpMtukxKTF5L4pzZRrmma60bTTdMzMyCzcrNisyeyOOdWca55hvtm82/yNhaVFnMVKizaLx5balnzLBZZNlvesmFY+VnlW9VbXrEnWXOss623WV2xQG1ebDJs6m8u2qK2brcR2m23fFOIUjynSKfVTbtox7PzsCuya7AbtOfZh9iX2bfbPHcwcEh3WO3Q7fHJ0dcx2bHC866ThNMOpxKnD6VdnG2ehc53zNRemS5DLEpd2lxdTbaeKp26fesuV5RruutK10/Wjm7ub3K3ZbdTdzD3Ffav7TS6bG8ldwz3vQfTw91jicczjnaebp8LzkOcvXnZeWV77vR5Ps5wmntYwbcjbxFvgvct7YDo+PWX6zukDPsY+Ap96n4e+pr4i3z2+I37Wfpl+B/ye+zv6y/2P+L/hefIW8U4FYAHBAeUBvYEagbMDawMfBJkEpQc1BY0FuwYvDD4VQgwJDVkfcpNvwBfyG/ljM9xnLJrRFcoInRVaG/owzCZMHtYRjobPCN8Qfm+m+UzpzLYIiOBHbIi4H2kZmRf5fRQpKjKqLupRtFN0cXT3LNas5Fn7Z72O8Y+pjLk722q2cnZnrGpsUmxj7Ju4gLiquIF4h/hF8ZcSdBMkCe2J5MTYxD2J43MC52yaM5zkmlSWdGOu5dyiuRfm6c7Lnnc8WTVZkHw4hZgSl7I/5YMgQlAvGE/lp25NHRPyhJuFT0W+oo2iUbG3uEo8kuadVpX2ON07fUP6aIZPRnXGMwlPUit5kRmSuSPzTVZE1t6sz9lx2S05lJyUnKNSDWmWtCvXMLcot09mKyuTDeR55m3KG5OHyvfkI/lz89sVbIVM0aO0Uq5QDhZML6greFsYW3i4SL1IWtQz32b+6vkjC4IWfL2QsFC4sLPYuHhZ8eAiv0W7FiOLUxd3LjFdUrpkeGnw0n3LaMuylv1Q4lhSVfJqedzyjlKD0qWlQyuCVzSVqZTJy26u9Fq5YxVhlWRV72qX1VtWfyoXlV+scKyorviwRrjm4ldOX9V89Xlt2treSrfK7etI66Trbqz3Wb+vSr1qQdXQhvANrRvxjeUbX21K3nShemr1js20zcrNAzVhNe1bzLas2/KhNqP2ep1/XctW/a2rt77ZJtrWv913e/MOgx0VO97vlOy8tSt4V2u9RX31btLugt2PGmIbur/mft24R3dPxZ6Pe6V7B/ZF7+tqdG9s3K+/v7IJbVI2jR5IOnDlm4Bv2pvtmne1cFoqDsJB5cEn36Z8e+NQ6KHOw9zDzd+Zf7f1COtIeSvSOr91rC2jbaA9ob3v6IyjnR1eHUe+t/9+7zHjY3XHNY9XnqCdKD3x+eSCk+OnZKeenU4/PdSZ3Hn3TPyZa11RXb1nQ8+ePxd07ky3X/fJ897nj13wvHD0Ivdi2yW3S609rj1HfnD94UivW2/rZffL7Vc8rnT0Tes70e/Tf/pqwNVz1/jXLl2feb3vxuwbt24m3Ry4Jbr1+Hb27Rd3Cu5M3F16j3iv/L7a/eoH+g/qf7T+sWXAbeD4YMBgz8NZD+8OCYee/pT/04fh0kfMR9UjRiONj50fHxsNGr3yZM6T4aeypxPPyn5W/3nrc6vn3/3i+0vPWPzY8Av5i8+/rnmp83Lvq6mvOscjxx+8znk98ab8rc7bfe+477rfx70fmSj8QP5Q89H6Y8en0E/3Pud8/vwv94Tz+4A5JREAAAAGYktHRAD/AP8A/6C9p5MAAAAJcEhZcwAACxMAAAsTAQCanBgAAAAHdElNRQfcAgcQLxxUBNp/AAAQZ0lEQVR42u2be3QVVZbGv1N17829eRLyIKAEOiISEtPhJTJAYuyBDmhWjAEx4iAGBhxA4wABbVAMWUAeykMCM+HRTcBRWkNH2l5moS0LCCrQTkYeQWBQSCAIgYRXEpKbW/XNH5zS4noR7faPEeu31l0h4dSpvc+t/Z199jkFWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhY/H9D/MR9qfKnLj/00U71aqfJn9+HCkCR/Wk36ddsgyJ/1wF4fkDfqqm9/gPsUeTnVr6a2xlQfnxdI7zs0W7irzD17Ytb2WT7EeNv/r4ox1O3Quf2QP2pgt9utwfout4FQE8AVBSlnaRmfvAURQkg2RlAbwB9AThlW5L0GaiKojhJhgOIBqDa7XaPrusdPtr5kQwF0BVAAoBIABRCKDd5aFUhRDAAw57eAOwAhKIoupft3zoqhB1AqLwuHIBut9uFt02qqvqRDJR2dAEQJj/BAOjn56dqmma+xiaECAEQAWAggLsB6A6HQ2iaZggBhBAqgEAAnQB0kzaEmT4hAITT6VQ8Ho/HJAKKECJQtr8LwD1y/A1/vcdfEUIEyfZ9AcQbYvZ942Px88L2UwlJR0dH0EMPPbRj5syZPUeNGrXR7Xb/641xIwJ1XY9NSUlZm52dfW+XLl1w8uRJzJ8//+OGhoYJqqqe1TSt1Wsm9NN1PSIqKmr12rVrR5WUlHy1bdu2AQCumWc3IYRD1/UwVVXnFRQUTIuNjUVzczN2797dWFJSkq8oymZd15sAGAEnFEUJ1nX9nzIzM1dnZmZGh4SE4OTJk5g5c+Zf29vbp9pstrMej6fVOyhIhgAYU1hY+B+hoaGoqKg4XVlZea+XTULTNFdCQsLGiRMnPuR2u3UhBOV9eeDAAWXTpk095DUe6WsoyRE5OTlr0tLSAux2O/bs2cO5c+e+pijKUpIXSHaQVAGkvPLKK++6XK4OksJLCFlXV2cvKSlJBFAjhU+x2WwhHo9nUHp6+urMzMy7wsLCUF9fjxdffPHjxsbGiTab7WuPx9NiEutOuq4PyMjI+M+srKyYqKgoHD58GDNmzNjq8XhyVFU9b/q+LH7hBAEYu3PnTlZVVRFAGgCX6f/tAHoOHDjwa0p27txp/JO9e/f+QM7cipw9nfL3kQBKt2zZQpJ87rnn6mQmoHilw2EACs+cOUOSrK+vZ1NTE0nyo48+IoBpxswoBcMJ4Ndjx471kOTFixe5d+9ekqTH42H//v13A4jyzpAURfEH0H/OnDnthu1z5sw558MmFUCPWbNmnaMP3nrrLZoyDmP8Hl68eDFJ8siRI9/Yc+zYMQKYKdtAztrTrl27xptRXV1NAKMAOAyBBBA/Y8aMdpLs6Ojgxx9//E37+++//29yvFXppwvAwMcee8xjtDHsuXLlCqOjo//ia3wsfpkoALqFhoZuIckJEyackimm3dQmEMDUmpoakmRISMhhAHOHDx/eQJIbN24kgKEyMAHAFRMTs2XXrl1saWkhSZ0kp0+ffhrAr3wEW/S8efOukORLL72kA1gKYMPWrVtJkk899dRJAHeYrgsEsIQkjx8/TgDvAPjd448/3kaSb7zxBmUa7vC6z53BwcFbSHL9+vU6Sc6aNes8gF5ewWAH0PfVV18lSQL4DMBGIcQ6AKtcLleBFC2jXtFt8ODBe0iyoqKCAJYByC8qKmJDQwOzsrK+MAmqo1OnTveHhoa+GRkZ+XZkZOSWiIiIvzgcjk9mzpypkWRmZuZpmbYbGV4AgPnNzc1sa2sjgN0A5iQmJtaSZHl5OQHcb/K3s81mW0uSTU1NBFAFYFbfvn1Pk+Tbb79NAA8IIVzW42/hByA+Pz/fLR/2ZXIda05NI/z9/TeR5J49ewhgqlxTrtI0jY2NjQQw3zTLuWJiYjaUlJToS5Ys6fjkk080kwDEeAmADcA9GzZsIElGRUW9CyAWwLApU6Y0kOSKFSsog9QICGdERMTGsrIyZmVlEcC9AB4IDw/fTpLbtm0jgN94CUAnAJmVlZVcs2aNZ/LkyRdJcvbs2b4EwAkgZfPmzTxw4AABFAN4BkC6vFeUSewcAO5duXIlSTIhIaEawGMAxgKYAmAGgCS73e5vrKVk/yGythANYEhCQsIhkly+fDkBpKqqGmL6DgIALDKN/3yZpVWQZGVlJQE8aPI3KiMjo5okV61aRQAjAPQBMPfIkSN0u90EUCBtsPiFEwpgbn19PdetW2fM5N4zQ9ekpKQqkty0aRMBpMjiWM6JEydIkoqirJUFJ6iq6pAPVy8A6cZMehMBUACEuVyuFwG8HBwcPEIWx367ZMkSjSQXLVrUJouTRorrkAHdA8BdQogsAOsKCwtJkmPGjDkvMw2bDDo/ADEjRoz4XylyFbm5uY0mAbjLyyZ/AOOrq6tZVlbWsWDBgo69e/eyoqKCgwcPPg4gSQaoIRbp27dvN7KF+tLSUr28vJwFBQXtMpvpYRIM7+wrAkDeqVOnePbsWQIoNKfzpiXPg8uXLydJJicnNwF4f+nSpW6STEtLq5fjYwhk1wkTJtSQ5Ouvv04AqTKj+N2xY8dIkgEBAW/Ie1v8wncRegwZMmQvSfbr12+3Ua33WqPfOWbMmP0kWVpaSgCDZAqcfejQIWNZsEGKgvnh9gfQb9myZd8nAEJVVZtMkUNk8CcNHTq0liR1XWdYWNhmH1mJIme80OnTp18x1rp5eXkEsNJms92Fb7e/IgEsvHz5Mp999tkmAI/l5uZeMC0B7vEqqAYAyL106RJJsra2lpWVld+sucePH38ZQG+5NncBeOrgwYMkqbe3t/Po0aOsra011wAWyl0H7x0JJ4DE+fPnu0kyPT29DsDdUrBuyNKEEAkAdpw/f/6GeoEM8GUmfwEgPCIiopwkGxsbabPZPgOw6L777vvm4p49e26VGYjFLxUhhD+ApLKyMp44ccIoVnXybgbgzkcfffRzklyzZg0BDJYCMMmoCwQFBXkLgLGWvvcWAgBToSsKwNPTp09vMR7UuLi4rwH0lgU8c/Db5ezbeeTIkRWzZ8++aMxu+fn5BPCADBwHgP4LFy701NXVEUAJgAnPP/98kyxMNgHo53A4zH77BQQETMvPz7+Um5vbBuAlAFMSExPPmdbVL0qh8Acw8fDhw5SCchVAEYAVb775JknyhRdeaJYztHfxMwLAaqNwCGC2FArv8x0hAHKNLGPKlCme5OTk/Zs3bzb7O0wKiiG8KXl5ed8IxenTp0mSR48e1UmyW7duWywBuD2xyQcgFECgoih+8H1gyJgZV5Lkyy+/3CbTRIePtl2HDBmyw1QBHyGDdXZdXR1JUghRKkXBjOMHCoBdpr0L3nvvPZLkF198wejo6O0A4lVVDTb74HQ6AwD8Wq7Jh8rgGgDgQ13XjVR8qaxJuADMbmlpYXl5uV5UVNRWUFDgfv/993Vj/ZydnU1c37eHXML4S3viAcQqitJD2l104cIFY8lTKsXSBWBMVVWVcd9yed2A1NTUQ6Zl00CvLMMOoHdubm6zFIlWOf5+PsY/Kj09vdrU11QAwwGsv3jxIk21m2DZr10I0RXAuAcffPBgaWkpV69eTYfDcdiwUxY0w6xw+flX8L1xApjevXv3lREREaW6rofB93aPDUDQpEmTMgHgtddeqwBwEd/utZvpqK6uPgEAcXFxkA94NwB9unfvjrNnz4LklwDcf08iIqv66Zs2bXrl4YcfxooVKxAbG7uqrq5uAYA2TdOEqqpGYIi2tjbl6aeffu/YsWPv5uTk7JaC1wHg4Pnz542MwoVvTx+21dbWYvjw4WLixIl+2dnZ9lGjRgmSTE1NRUpKCkwFTGiaxtTU1OXTpk3707Bhw/6g67pDipnT4biuj7qut+Lbk3Vf1tTUXI9qu91Pjq1QFEUBgJaWFgBo8yGOQ8eNGxcAAOvXr/8QwBUfYygAKL169eoCABcuXACAWtn2hOGv0+kMNO1KiPDw8F4A4rZv3/7R1KlTR0+bNu1ht9u9r1+/fqitrQXJgwDarRC6/QjPzs4+QJIffPCB9/aQmSAA43ft2mW0e1QGoi8CAPyLsZccExNTC2BlRkbGRdOyYJCP2csBIN6UAZzCd7cBbQCijYp/dXU1ExMTz6SmptaMHj36f9LS0vYlJCRsl6mxIWSdu3fv/g5J7t+/nwC2AShMTk6+SJKff/45AWRLYbD7+fndAeDf5BJnLoCCyZMnt5JkdnZ2C4B/F0KEm1Pu+Pj4rST55ZdfEsBWAK+mpaVdMo3raDn7KwDuSEpK+m+S3LBhAwG8DuCtHTt2UBbpjgC408vvcFVV15HkuXPnjMp+p5uMf0RcXNyHJNnQ0EBVVfcCWBQXF3fG+Jv0yxABPwB5LS0tRmFxN4BlTzzxxGWSXLx4sS5F3GGFy+1Hp5SUlJq6ujoWFxdTpsZ2H+0iIyMj/0iSWVlZX5mr5jfJFroPGzasxlhTnjp1iiTZ3NxMl8tlrCd9pfa9SkpKSJI5OTmnZOageLUZZqxvfVFWVkZcPwdgNwnSCKPqb17jkmR8fPzfZMDZ5CRsFBmNI7h95s2b1yhT7/MAYmStwCx4vy0uLqa3v5qmEcCfvSr1QQAeXb16NY3Cm3HQ55133iGAp+SxZTNhKSkpfzUddkrFjYevzAQCeGjp0qXfsYckY2NjTwD4leGDLCL2HTdunNtoY+zWSHFcIHdsFCtcfuZ1vO9Eqs3m7/F47sb1k2qX/f3997W2tl7BjWfpBYDOzzzzzIVJkyZh0KBBCwEsB3AJvl9AETabLcDj8dwRFRW1ctasWb8JCgpSzp07d62wsPC/Wltb8xRFadR1/ZqPXYbgAQMGbI2Pjw/+6quv9ldVVT0r01ezuPRJSUn5Y9euXXVd11WzDaqq6kePHm3+7LPPRgO4KlNuxWazhXo8nuTk5OSXMjIyEl0uFxoaGtqKior+dPXq1VdUVT0jj7r68ieoT58+vx8yZMjdx48fP1JVVTVF9m20VW02WyfZf97YsWPjXS4X6urqWvPy8jYCWCyEuEDS8FdVFKWzruv//OSTTy5OTk7uqWkaPv3007qysrJ8RVH+LI8ym8/rB3Tu3HnRI488knLo0KG2ffv2ZQI4C98vP6mqqoZqmpaclpa2cOTIkX39/f3R0NDQUVxc/G5TU9PLqqrWa5rWLH1QVFUN0TStX1JSUvH48eP7BwYG4uDBg1cKCgpeBbBe2u+2Qug2EwD5N5sMPuNtMe8XP4TT6Qxoa2sbIGeXvUKIK7d4IISiKC5d1wPljOfA9bPwzYqiXNV13dd6Uqiq6qdpml2mpe02m63d4/G4vcTF5fF47LJf71nJA6BZVVW3pmntuPHlmAD5wk6Q9NnbHp9vHaqq6tA0zU/64PZhk1FfCZB9G/23ALiqKEqzD39tpvbGUqoFwFUhRLP3yzpCCDtJpxyXDulfG27+pqRR3DXsUWVd4Yq0x/taVQjhIhksC8L+ABpM9ljBf5sKwI8pIBr75L5E4vvu+UNeG/a+hv+AL7yFH8qPtOfHjtOP6V/Bja8D6z/B2Nys/1u9Xv33tLf4GfF/LC4GCJwByWIAAAAASUVORK5CYII=";
  1688. cc._loaderImage = "data:image/jpeg;base64,/9j/4QAYRXhpZgAASUkqAAgAAAAAAAAAAAAAAP/sABFEdWNreQABAAQAAAAlAAD/4QMpaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLwA8P3hwYWNrZXQgYmVnaW49Iu+7vyIgaWQ9Ilc1TTBNcENlaGlIenJlU3pOVGN6a2M5ZCI/PiA8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGEvIiB4OnhtcHRrPSJBZG9iZSBYTVAgQ29yZSA1LjAtYzA2MCA2MS4xMzQ3NzcsIDIwMTAvMDIvMTItMTc6MzI6MDAgICAgICAgICI+IDxyZGY6UkRGIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyI+IDxyZGY6RGVzY3JpcHRpb24gcmRmOmFib3V0PSIiIHhtbG5zOnhtcE1NPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvbW0vIiB4bWxuczpzdFJlZj0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL3NUeXBlL1Jlc291cmNlUmVmIyIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOjM4MDBEMDY2QTU1MjExRTFBQTAzQjEzMUNFNzMxRkQwIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjM4MDBEMDY1QTU1MjExRTFBQTAzQjEzMUNFNzMxRkQwIiB4bXA6Q3JlYXRvclRvb2w9IkFkb2JlIFBob3Rvc2hvcCBDUzUgV2luZG93cyI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOkU2RTk0OEM4OERCNDExRTE5NEUyRkE3M0M3QkE1NTlEIiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOkU2RTk0OEM5OERCNDExRTE5NEUyRkE3M0M3QkE1NTlEIi8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+/+4ADkFkb2JlAGTAAAAAAf/bAIQADQkJCQoJDQoKDRMMCwwTFhENDREWGhUVFhUVGhkUFhUVFhQZGR0fIB8dGScnKionJzk4ODg5QEBAQEBAQEBAQAEODAwOEA4RDw8RFA4RDhQVERISERUfFRUXFRUfKB0ZGRkZHSgjJiAgICYjLCwoKCwsNzc1NzdAQEBAQEBAQEBA/8AAEQgAyACgAwEiAAIRAQMRAf/EALAAAAEFAQEAAAAAAAAAAAAAAAQAAgMFBgcBAQEAAwEBAAAAAAAAAAAAAAAAAQMEAgUQAAIBAgIEBwoLBgQGAwAAAAECAwAEEQUhMRIGQVFxsTITFGGBwdEiQlKSMzWRoeFicqKyI1NzFYJjJDQWB9KjVCbxwkNkJWXik3QRAAIBAgMFBQcDBQEAAAAAAAABAhEDIRIEMUFRcTJhwVIUBZGhsSJyEzOB0ULhYpIjUxX/2gAMAwEAAhEDEQA/AMJSpUqAVKlXuFAeUq9wpUB5XuFe4V6ooDzZHDox0CnGMinzwl7Z8NajaHeoO3vmTBZBtp9YUIqTEV5ROxHKnWRnaU8VRMhFBUjpV7hSoSeUq9pUB5Sr2lhQHlKvcK8oBV7hSFSRrtaKAZs07YNPM1pG2xJIAw1jSeandry/8X4m8VCKkWwaWwam7Xl/4v1W8VLtmX/i/VbxUoKkWwakSM407tmX/i/VbxUmzGwjQsjdY41IARie/U0IbZO0kNtCXnOCkEBeFu4KI3Bs7DNb27ya+jDx3kJeEnpJJEcQVbWDsk17u5urd591ucZkWhym2Vnd9RkCDEpFxDRpbw0bunu5mlp2De2FMLYXOD2wB2xbOeraUcYGJ72mlSUiqzzdzMd3Z3mixltA2yzcK/NlHM1DQyRXce1HocdNOEfJXZ88y9ZojOqhiBszIRiHQ8Y4cK5TvHuzLljHNMqxNoDjLFraHHnjPxcNCGVbxEUzYNTx5jZSxhpW6qTzlwJ+DCvO2Zf+L9VvFSgqyHYNLYNTdssPxfibxUu15f8Ai/VPiqCakOwa82DU/a8v/F+JvFTDdWPBL8R8VKCvYRYV5UzoMAy6QdIIqI0B4KJtxiRQwou16QoGUkntH5Tz0RbZbmF2hktraSVBo2lUkY8tDye0flPPXTslVUyiyVRsjqUOA4yMT8dW2ram2m6UVTNq9S7EIyUVJydMTn/6DnP+im9Wl+g5z/opvVrpteEhQWY4AaSTwAVf5WPiZh/9S5/zj7zltzlmYWkfWXNvJDGTgGcYDHirR7i7mSbwXParsFMrgb7w6jKw/wCmnc9I14kF3vpvCljbMyWMOJL4aEiB8qU/ObUK7HYWVrl1pFZWiCOCBQqKOLjPGTrNZZqKbUXVHq2nNwTuJRk1VpbgXN8s7Rk5ym0UQQzhIG2NAjhxHWbI+gCBVjBBFbwxwQqEiiUJGg1BVGAFe7dV28WYLYZFmF2Th1UD7JGjymGyn1iK5OyzIBGB1HgrLZhamzumQAGJwSqnSCh1q3GOCodxt4cxurdcpzuN4cyhiWaF5Bg09udUmnWw1H/jV9nFuJ7Quo+8h8peThFA+047vduyMtk7fYqTl07YFdfUufMPzT5p71UdtlmYXaGS2t3mQHAsgxANdadYJopLe4QS2867EsZ4QfCNYrCFbjdDPmgkYyWFxgVf04ifJf6ScNdRUW1XBb6FU5TjF5EpSSrGu/s5lN+g5z/opvVpfoOc/wCim9WtdHnatvObJXDW7xLGhB8nrPaY9/HCr+tEdPCVaSeDoYLnqF63lzW4/PFSW3ecxbI84VSzWUwUaSdg0DXXK5nvAipnd6qgKvWnQO7pri9ZUEmm3Vl2j1kr8pRlFRyquBNZjGxQ/S56Y1S2fu9OVueon11Szahoou06QoQUXadIVCD2FJJ7R+U89dMydv8Axdn+TH9muZye0flPPXQstlK5Tbka1gUjlC1q0vVLkeb6r+O3Tx9xcY1nt8c0NrZCyiOE1108NYjGv1joo7Js1jzKyScYLIvkzL6LDwHXVJksH9Sb49dKNq0tj1jA6uriOCL+02FWX7iVtZX1/AzaHTyeoauKn2MX9W79zebiZCuR5MjSrhfXuEtwTrUeZH+yNfdrRNcxI6IzhXlJEak6WIGJ2Rw4ChWnChndtlVBLMdQA0k1gbXNMzzDfDLs6mjaPKppJbWwJ1bOwwxw43OnHh71YT3DpfWUJmFlb5jHHDdeXBHIsrRea5TSqvxqG04cNN62vetoCS4tre5mgnkGE9q+3DKOkuI2WX6LDQRRHWDh1UCtwj7QRg2wdl8Djgw1qe7XvW0BQ3kfZ7mSLgU+T9E6RVbnuVrnWVSWqj+Lt8ZbRuHEdKPkYVcZ2MJY5fSGyeVar45+rkWQHAqccalPE5km1htWK5nK4Wnt5FuUBUwOMG4nGkA/BXUrW4S6torlOjMgcd/xVn7rLo7zKs0uEjCNeSvdwoBhgsZxX1l2j36k3Lu+uyprdj5Vs5A+i/lD48a0aaVJOPi7jB6lbzWozpjB48pf1NDXNN4vfl7+Z4BXS65pvF78vfzPAK71XTHmZ/S/yT+jvJ7L3fHytz1E+upbL+Qj5W56jfXWRnsIYKLtekKEFGWvSFQgyjk9o/Keet3YthlMP/5x9msJJ7R+U89biyb/AMXEv7gD6tadL1T+kwepRrC39ZkLDMbiwMvUHRPG0bjlGg8ore/23sxBldxfMPLupNhT8yL/AORNZbdzJ484scytxgLqJY5LZj6Q2sV5G1Vud1mjjyG0ij0NEGSZToKyhjtqw4waztuiXA3qKTbSxltfGhbZlE95ZtZqxVbgiOZhrER9ph3Svk9+pJILZ4Y4DGBFCUMKjRsGPobPFhUfW0NJmljE2xJcIrcI2vFUEln1lRXd6lrazXT9GCNpD+yNqoI7mOVduNw6nzlOIoPOUa6yye1XXcbMR5GdQ3xY0BSbj31/FcTQZirJ+q431q7anbHCTZ72Bw7lbPrKBMcBWNNgbMBBh+bsjBdni0VJ1lARZs6yWiupxCuMDy6KpS2IwOo6DTr3Mre3e5tZZVUM4ZBjqOOJoWO4jkXajcOOMHGgDISvWIrdAkKR80+TzVl908bPPL3LzxOuHdifxVfiTAg92qI/w+/8gGgSyN/mR7XPVlp0lF/3L3mbVKtu5Hjbk/8AHE2Fc03i9+Xv5ngFdKNc13i9+Xv5ngFaNV0x5nn+l/kn9HeEWXu+PlbnqJ9dS2Xu9OVueon11kZ7CGCjLXpCgxRlr0hUIPYUcntH5Tz1s8vb+Bt1/dqPirGSe0flPPWusG/g4Py15q06XqlyMWvVYQ+ruI9xJOqzO9hOto/sP8tbGOFIrmWeM7IuMDMnAXXQJOUjQeOsJk0nY96ip0CYunrjaHx1t+srPJUbXBm2LrFPikwTOb+T+VhbZxGMrDXp83x1QSy2tucJpUjPETp+Cn5/ftaRvKvtp3Kx48HG3erHMzOxZiWZtLMdJNQSbbL71Vk6yynViOkqnEEfOWtPbXi3EQkGg6mXiNckjeSJxJGxR10qw0GtxuxmvbImD4CZMFlA4fRfv0BqesqqzTMZNMEDbIHtHH2QeCiZJSqMQdOGiue53mz3czQwsRbIcNHnkec3c4qAMuriz68gTIToxwOOnlp0MjxMJYW741Gs3RVldtbygE/dMcHX/moDaxTiWNZB53B3arb8/wC+4SOF4sf/AKxU9kcBsfOGHfoUHtG/RbzY5Die5HHhXdvavqiZ9Q8Jdlq4/gbKua7xe/L38zwCuhpf2Uk/Zo50kmwJKIdogDjw1VzzeL35e/meAVp1LTgqY4nn+mRauzqmqwrjzCLL3fHytz1E+upLL+Qj5W56jfXWRnroYKLtekKEFF2vSFQg9hSSe0flPPWosm/hIfoLzVl5PaPynnrRWb/w0X0F5q06XqlyM2sVYx5gmbFre/t71NY2T+0h8VbSO5SWNJUOKSAMp7jDGspmMPaLRlXS6eWve1/FRO7WYdbZm1Y/eW/R7qHxHRXGojlm3ulid6aVbaW+OALvgCLq2Hm9WxHKWqjhj6xsK1e8dm15l4niG1LZkswGsxtrPeOmsvayBJA1VItlWjptLuTdPMo7LtjRDq9naK4+WF9IrUW7BaHOljGqVHB7w2hzVoZt87d8vaNYSLl02CcRsDEbJbj71Uu7UBkvJ7/D7q2QoDxySaAO8MTXdxRVMpRp5XZOWdF/ms7R5XdyKfKWJsO/5PhrG5XlNxmEywW6bTnTxAAcJNbGSMXkM1pjgbiNo1PziPJ+Os7u7m/6ReM00ZOgxSpqYYHT3wRXMKN4ll9zUG4bQfNshu8sZVuEA2hirA4qe/VOwwrVbzbww5mI44UKRRYkbWG0S3JWctbd7u5WFfOOLHiUdJqmaipfLsIsObhWe001lMkMVvJNjhghIALMcBxCs7fxXQmkupx1bXDswGPlaTidVaEyKNXkoo4eBV+Sq7L7Vs9zcBgeyQ4GQ/MB1crmoim2orezqcowTuSeEY48jQ7oZX2PLzdyLhNd6RjrEY6I7+uspvH78vfzPAK6UAAAFGAGgAcArmu8Xvy9/M8ArTfio24RW5nnaG67uou3H/KPuqT2X8hHytz1G+upLL3enK3PUb66ys9RDBRdr0hQgou06QqEGUkntH5Tz1e238vF9BeaqKT2j8p56vbb+Xi+gvNWjTdUuRn1XTHmTh8KrJTJlt8t1CPIY44cGnpJVjTJYkmjaN9Ib4u7V923njTethRauZJV3PaW1rfLIiXEDYg6R4VYc9CXW7thfOZbKdbGZtLW8uPVY/u3GrkNUkM9zlcxUjbhfWOA90cRq4gv4LhdqN+VToNYWmnRm9NNVWNTyHc6VWBv8wt4YeHqm6xyPmroq1Z7WGFLSxTq7WLSuPSdjrkfumq5yHXDUeA92oO2SKpVumNAaoJLMXH3myp0rpJ4uKhc3tbDM5BMri1zAj79j7KTiY8TcdBpcsith0286o+sPCagEX9Pzg4zXUCp6QYse8oouCG3tk6m1BYv05W6T+IdyolxbHDAAa2OgDlNCz3ryN2WxBd5PJMg1t81eId2ukqnLlTBbfcuY+9uJLiRcvtPvHdsHK+cfRHcHDWsyawjyy0WBcDI3lTP6TeIcFV+S5OmXx9bJg1048o8Cj0V8Jq2DVu09nL80up7OxHi+oal3P8AXB/IsZS8T/YOV65zvCcc7vfzPAK3ivWCz445zeH954BXOr6I8yfSfyz+jvCLP3fHytz1G+upLP3fHytz1E+usbPaQ0UXadIUIKLtekKhB7Ckk9o/Keer22/l4/oLzVRSe0flPPV7b/y8X0F5q0abqlyM+q6Y8yQsBTDMor1o8aiaE1pbluMqS3sbLLHIhSRQyngqukhaJ9uBjo+H5aOa3ao2t34qouRlLajTalGP8v0IY8ylXQ+PKPFU/bYXOLPge6CKia0LaxTOxHu1Q7cuBd9yPEJ7TbjXKO8CajbMIF6CNIeNvJHjqIWJ7tSpYkalqVblwIdyG+RGXur0hXYJFxal+Dhq5y3slkv3Y2pD0pTr+QUClpJRUdo9XW4OLrTHtM16cZLLWkeC7y4jvlNEpcRtw1Ux27Ci448NZrTFy3nn3IQWxlgGrDZ3pza7/M8ArZo+ArF5171uvp+CqdV0R5l/psUrs2vB3hdl7vTlbnqJ9dS2Xu+PlbnqJ9dY2eshooq16QoQUXa9IVCD2FLJ7RuU89WNtmUSQqkgYMgw0accKrpPaPynnrZWG4Vi+VWmY5tnMWXG+XrIYnA0rhj0mdcTgdNdwnKDqjmduM1SRR/qlr8/4KX6pa8T/BVzDuLZXudRZblmbxXcPUNPc3KqCIwrbOzgrHEnHjoyD+3eSXkht7DeKG4umDGOJVUklfouThXfmbnZ7Cvy1vt9pmv1W1+d8FL9VteJvgq5yrcOGfLmzHN80iyyETPbptAEFo2ZG8pmUa1OFNn3Ky6W/sbDKM5hv5bx2WTZA+7RF2y52WOPJTzE+z2Dy1vt9pT/AKpacTerS/U7Tib1a04/t7kDXPY03jhN0W6sQ7K7W3q2dnrMccaDy/8At80kuZfqWYxWNtlcvUPPhiGYhWDeUy7IwYU8xPs9g8tb7faUn6pacTerTxm9oOBvVq3v9z927aynuId44LiWKNnjhAXF2UYhRg516qpsryjLr21665zFLSTaK9U2GOA87SwqY37knRU+BzOzags0s1Oyr+BKM6sxwP6tSDPLMen6vy0rvdm3Sxlu7K/S7WDDrFUDUTxgnTU826eXW7KlxmqQuwDBXUKcD+1Xee/wXuKX5XDGWLapSVcOyhEM/seJ/V+WnjeGx4pPV+Wkm6kKZlFay3Jlt7iFpYZY8ASVK6DjtDDA0f8A0Tl340/1f8Ndx8xJVWXB0KbktFFpNzdVXAC/qOwA0CQni2flrO3Vwbm5lnI2TKxbDirX/wBE5d+NcfV/wVR7xZPa5U9utvI8nWhmbbw0YEAYYAVxfhfy5rlKR4Fulu6X7mW1mzT8S4Yis/5CPlbnqJ9dSWfu9OVueon11mZvQ2i7XpChKKtekKhBlNJ7R+U89bDfGTb3a3ZX0Lcj6kdY+T2j8p560288m1kWQr6MJ+ylSAr+2cnV5renjs3H1loX+3j9XvbbtxLN9lqW4UnV5jdnjtXHxihtyZNjeSBu5J9k1BJe7xy7W5CJ/wCzuD/mTVTf2+fq97LJuLrPsNRueS7W6aJ/38x+vLVXuY+xvHaNxbf2GoCezf8A36j/APsSf8w1sLnqczTefJluYoLm5uo5F61sBshItP1cNFYe1f8A3ir/APfE/wCZUe9bB94r5jwuPsrQFhmG4l/Z2M17HdW90tuu3IkTHaCjWdIw0VVZdks9/C06yJFEp2dp+E1bbqybGTZ8vpQD7L1XRv8A7blT96Oda7tpNuuNE37Cq9KSisjyuUoxrStKllHbLlWTXsMs8chuSuwEPDqwoLe5y+YRE/gLzmqRekvKKtd4327yM/ulHxmrHJStySWVRyrjxKI2XC/CTlnlPPKTpTdFbP0L1bgrf5Lp0G3dPhQHwV0S1lzBsns3sESR8Crh9WAJGjSOKuU3E+zdZQ3oJh8IArdZXFDmOTpHa3i2+YrI2KtKy4ricBsBuHHgFXSo440+Wa2qqxjvM9uMoy+WvzWpLCWWWE28HxL6e43ojgkeSCBY1Ri5BGIUDT51cl3vm276BBqSEH4WbxV0tlkyXJcxTMb+OW6uY9mGHrCzDQwwAbTp2uKuTZ9N1uYsfRRR8WPhrm419mSSjRyiqxVK7y23B/ftuTm2oSdJyzNVw3BFn7vTlbnqF9dS2fu9OVueon11lZuQ2iLdsGFD05H2dNQGV0ntG5Tz1dWm9N1b2kVq8EVwsI2UaQaQOKhmitZGLOmk68DhSFvY+gfWNSAg7z3Qvo7yKCKIohiaNR5LKxx8qpxvjcqS0VpbxvwOAcRQPZ7D0G9Y0uz2HoH1jUCpLY7zXlpbm3eKO5QuzjrBqZji3x17PvNcyT288VvDBJbMWUovS2hslW7mFQ9nsPQPrGl2ew9A+saCod/WNxtbYsrfb17WBxx5ddD2281xC88klvDcSXEnWuzrqOGGC9zRUPZ7D0G9Y0uzWHoH1jQVCLreq6ntZbaO3it1mGy7RjTs1X2mYy20ZiCq8ZOODcdEdmsPQb1jS7PYegfWNdJuLqnQiSUlRqpFLmryxtH1Ma7Qw2gNNPOdSt0oI27p007s9h6B9Y0uz2HoH1jXX3Z+I4+1b8IJdX89xLHKQFMXQUahpxoiPN5P+onfU+A0/s9h6DesaXZ7D0D6xpG7OLbUtu0StW5JJx2bBsmbtiSiEk+cxoCWWSaVpZOk2vDVo0VYdnsPQb1jSNvZcCH1jSd2c+p1XAmFqEOmOPEfaH+BQd1ueo211IzrgFUYKNAAqI1WztCpUqVCRUqVKgFSpUqAVKlSoBUqVKgFSpUqAVKlSoBUqVKgFSpUqAVKlSoD/9k=";
  1689. cc.loader.loadBinary = function (url, cb) {
  1690. var self = this;
  1691. var xhr = this.getXMLHttpRequest(),
  1692. errInfo = "load " + url + " failed!";
  1693. xhr.open("GET", url, true);
  1694. if (cc.loader.loadBinary._IEFilter) {
  1695. xhr.setRequestHeader("Accept-Charset", "x-user-defined");
  1696. xhr.onreadystatechange = function () {
  1697. if (xhr.readyState === 4 && xhr.status === 200) {
  1698. var fileContents = cc._convertResponseBodyToText(xhr["responseBody"]);
  1699. cb(null, self._str2Uint8Array(fileContents));
  1700. } else cb(errInfo);
  1701. };
  1702. } else {
  1703. if (xhr.overrideMimeType) xhr.overrideMimeType("text\/plain; charset=x-user-defined");
  1704. xhr.onload = function () {
  1705. xhr.readyState === 4 && xhr.status === 200 ? cb(null, self._str2Uint8Array(xhr.responseText)) : cb(errInfo);
  1706. };
  1707. }
  1708. xhr.send(null);
  1709. };
  1710. cc.loader.loadBinary._IEFilter = (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent) && window.IEBinaryToArray_ByteStr && window.IEBinaryToArray_ByteStr_Last);
  1711. cc.loader._str2Uint8Array = function (strData) {
  1712. if (!strData)
  1713. return null;
  1714. var arrData = new Uint8Array(strData.length);
  1715. for (var i = 0; i < strData.length; i++) {
  1716. arrData[i] = strData.charCodeAt(i) & 0xff;
  1717. }
  1718. return arrData;
  1719. };
  1720. cc.loader.loadBinarySync = function (url) {
  1721. var self = this;
  1722. var req = this.getXMLHttpRequest();
  1723. var errInfo = "load " + url + " failed!";
  1724. req.open('GET', url, false);
  1725. var arrayInfo = null;
  1726. if (cc.loader.loadBinary._IEFilter) {
  1727. req.setRequestHeader("Accept-Charset", "x-user-defined");
  1728. req.send(null);
  1729. if (req.status !== 200) {
  1730. cc.log(errInfo);
  1731. return null;
  1732. }
  1733. var fileContents = cc._convertResponseBodyToText(req["responseBody"]);
  1734. if (fileContents) {
  1735. arrayInfo = self._str2Uint8Array(fileContents);
  1736. }
  1737. } else {
  1738. if (req.overrideMimeType)
  1739. req.overrideMimeType('text\/plain; charset=x-user-defined');
  1740. req.send(null);
  1741. if (req.status !== 200) {
  1742. cc.log(errInfo);
  1743. return null;
  1744. }
  1745. arrayInfo = this._str2Uint8Array(req.responseText);
  1746. }
  1747. return arrayInfo;
  1748. };
  1749. window.Uint8Array = window.Uint8Array || window.Array;
  1750. if (cc.loader.loadBinary._IEFilter) {
  1751. var IEBinaryToArray_ByteStr_Script =
  1752. "<!-- IEBinaryToArray_ByteStr -->\r\n" +
  1753. "Function IEBinaryToArray_ByteStr(Binary)\r\n" +
  1754. " IEBinaryToArray_ByteStr = CStr(Binary)\r\n" +
  1755. "End Function\r\n" +
  1756. "Function IEBinaryToArray_ByteStr_Last(Binary)\r\n" +
  1757. " Dim lastIndex\r\n" +
  1758. " lastIndex = LenB(Binary)\r\n" +
  1759. " if lastIndex mod 2 Then\r\n" +
  1760. " IEBinaryToArray_ByteStr_Last = Chr( AscB( MidB( Binary, lastIndex, 1 ) ) )\r\n" +
  1761. " Else\r\n" +
  1762. " IEBinaryToArray_ByteStr_Last = " + '""' + "\r\n" +
  1763. " End If\r\n" +
  1764. "End Function\r\n";// +
  1765. var myVBScript = document.createElement('script');
  1766. myVBScript.type = "text/vbscript";
  1767. myVBScript.textContent = IEBinaryToArray_ByteStr_Script;
  1768. document.body.appendChild(myVBScript);
  1769. cc._convertResponseBodyToText = function (binary) {
  1770. var byteMapping = {};
  1771. for (var i = 0; i < 256; i++) {
  1772. for (var j = 0; j < 256; j++) {
  1773. byteMapping[ String.fromCharCode(i + j * 256) ] =
  1774. String.fromCharCode(i) + String.fromCharCode(j);
  1775. }
  1776. }
  1777. var rawBytes = IEBinaryToArray_ByteStr(binary);
  1778. var lastChr = IEBinaryToArray_ByteStr_Last(binary);
  1779. return rawBytes.replace(/[\s\S]/g,
  1780. function (match) {
  1781. return byteMapping[match];
  1782. }) + lastChr;
  1783. };
  1784. }
  1785. var cc = cc || {};
  1786. var ClassManager = {
  1787. id : (0|(Math.random()*998)),
  1788. instanceId : (0|(Math.random()*998)),
  1789. getNewID : function(){
  1790. return this.id++;
  1791. },
  1792. getNewInstanceId : function(){
  1793. return this.instanceId++;
  1794. }
  1795. };
  1796. (function () {
  1797. var fnTest = /\b_super\b/;
  1798. cc.Class = function () {
  1799. };
  1800. cc.Class.extend = function (props) {
  1801. var _super = this.prototype;
  1802. var prototype = Object.create(_super);
  1803. var classId = ClassManager.getNewID();
  1804. ClassManager[classId] = _super;
  1805. var desc = { writable: true, enumerable: false, configurable: true };
  1806. prototype.__instanceId = null;
  1807. function Class() {
  1808. this.__instanceId = ClassManager.getNewInstanceId();
  1809. if (this.ctor)
  1810. this.ctor.apply(this, arguments);
  1811. }
  1812. Class.id = classId;
  1813. desc.value = classId;
  1814. Object.defineProperty(prototype, '__pid', desc);
  1815. Class.prototype = prototype;
  1816. desc.value = Class;
  1817. Object.defineProperty(Class.prototype, 'constructor', desc);
  1818. this.__getters__ && (Class.__getters__ = cc.clone(this.__getters__));
  1819. this.__setters__ && (Class.__setters__ = cc.clone(this.__setters__));
  1820. for(var idx = 0, li = arguments.length; idx < li; ++idx) {
  1821. var prop = arguments[idx];
  1822. for (var name in prop) {
  1823. var isFunc = (typeof prop[name] === "function");
  1824. var override = (typeof _super[name] === "function");
  1825. var hasSuperCall = fnTest.test(prop[name]);
  1826. if (isFunc && override && hasSuperCall) {
  1827. desc.value = (function (name, fn) {
  1828. return function () {
  1829. var tmp = this._super;
  1830. this._super = _super[name];
  1831. var ret = fn.apply(this, arguments);
  1832. this._super = tmp;
  1833. return ret;
  1834. };
  1835. })(name, prop[name]);
  1836. Object.defineProperty(prototype, name, desc);
  1837. } else if (isFunc) {
  1838. desc.value = prop[name];
  1839. Object.defineProperty(prototype, name, desc);
  1840. } else {
  1841. prototype[name] = prop[name];
  1842. }
  1843. if (isFunc) {
  1844. var getter, setter, propertyName;
  1845. if (this.__getters__ && this.__getters__[name]) {
  1846. propertyName = this.__getters__[name];
  1847. for (var i in this.__setters__) {
  1848. if (this.__setters__[i] === propertyName) {
  1849. setter = i;
  1850. break;
  1851. }
  1852. }
  1853. cc.defineGetterSetter(prototype, propertyName, prop[name], prop[setter] ? prop[setter] : prototype[setter], name, setter);
  1854. }
  1855. if (this.__setters__ && this.__setters__[name]) {
  1856. propertyName = this.__setters__[name];
  1857. for (var i in this.__getters__) {
  1858. if (this.__getters__[i] === propertyName) {
  1859. getter = i;
  1860. break;
  1861. }
  1862. }
  1863. cc.defineGetterSetter(prototype, propertyName, prop[getter] ? prop[getter] : prototype[getter], prop[name], getter, name);
  1864. }
  1865. }
  1866. }
  1867. }
  1868. Class.extend = cc.Class.extend;
  1869. Class.implement = function (prop) {
  1870. for (var name in prop) {
  1871. prototype[name] = prop[name];
  1872. }
  1873. };
  1874. return Class;
  1875. };
  1876. })();
  1877. cc.defineGetterSetter = function (proto, prop, getter, setter, getterName, setterName){
  1878. if (proto.__defineGetter__) {
  1879. getter && proto.__defineGetter__(prop, getter);
  1880. setter && proto.__defineSetter__(prop, setter);
  1881. } else if (Object.defineProperty) {
  1882. var desc = { enumerable: false, configurable: true };
  1883. getter && (desc.get = getter);
  1884. setter && (desc.set = setter);
  1885. Object.defineProperty(proto, prop, desc);
  1886. } else {
  1887. throw new Error("browser does not support getters");
  1888. }
  1889. if(!getterName && !setterName) {
  1890. var hasGetter = (getter != null), hasSetter = (setter != undefined), props = Object.getOwnPropertyNames(proto);
  1891. for (var i = 0; i < props.length; i++) {
  1892. var name = props[i];
  1893. if( (proto.__lookupGetter__ ? proto.__lookupGetter__(name)
  1894. : Object.getOwnPropertyDescriptor(proto, name))
  1895. || typeof proto[name] !== "function" )
  1896. continue;
  1897. var func = proto[name];
  1898. if (hasGetter && func === getter) {
  1899. getterName = name;
  1900. if(!hasSetter || setterName) break;
  1901. }
  1902. if (hasSetter && func === setter) {
  1903. setterName = name;
  1904. if(!hasGetter || getterName) break;
  1905. }
  1906. }
  1907. }
  1908. var ctor = proto.constructor;
  1909. if (getterName) {
  1910. if (!ctor.__getters__) {
  1911. ctor.__getters__ = {};
  1912. }
  1913. ctor.__getters__[getterName] = prop;
  1914. }
  1915. if (setterName) {
  1916. if (!ctor.__setters__) {
  1917. ctor.__setters__ = {};
  1918. }
  1919. ctor.__setters__[setterName] = prop;
  1920. }
  1921. };
  1922. cc.clone = function (obj) {
  1923. var newObj = (obj.constructor) ? new obj.constructor : {};
  1924. for (var key in obj) {
  1925. var copy = obj[key];
  1926. if (((typeof copy) === "object") && copy &&
  1927. !(copy instanceof cc.Node) && !(copy instanceof HTMLElement)) {
  1928. newObj[key] = cc.clone(copy);
  1929. } else {
  1930. newObj[key] = copy;
  1931. }
  1932. }
  1933. return newObj;
  1934. };
  1935. cc.inject = function(srcPrototype, destPrototype){
  1936. for(var key in srcPrototype)
  1937. destPrototype[key] = srcPrototype[key];
  1938. };
  1939. cc.Point = function (x, y) {
  1940. this.x = x || 0;
  1941. this.y = y || 0;
  1942. };
  1943. cc.p = function (x, y) {
  1944. if (x === undefined)
  1945. return {x: 0, y: 0};
  1946. if (y === undefined)
  1947. return {x: x.x, y: x.y};
  1948. return {x: x, y: y};
  1949. };
  1950. cc.pointEqualToPoint = function (point1, point2) {
  1951. return point1 && point2 && (point1.x === point2.x) && (point1.y === point2.y);
  1952. };
  1953. cc.Size = function (width, height) {
  1954. this.width = width || 0;
  1955. this.height = height || 0;
  1956. };
  1957. cc.size = function (w, h) {
  1958. if (w === undefined)
  1959. return {width: 0, height: 0};
  1960. if (h === undefined)
  1961. return {width: w.width, height: w.height};
  1962. return {width: w, height: h};
  1963. };
  1964. cc.sizeEqualToSize = function (size1, size2) {
  1965. return (size1 && size2 && (size1.width === size2.width) && (size1.height === size2.height));
  1966. };
  1967. cc.Rect = function (x, y, width, height) {
  1968. this.x = x||0;
  1969. this.y = y||0;
  1970. this.width = width||0;
  1971. this.height = height||0;
  1972. };
  1973. cc.rect = function (x, y, w, h) {
  1974. if (x === undefined)
  1975. return {x: 0, y: 0, width: 0, height: 0};
  1976. if (y === undefined)
  1977. return {x: x.x, y: x.y, width: x.width, height: x.height};
  1978. return {x: x, y: y, width: w, height: h };
  1979. };
  1980. cc.rectEqualToRect = function (rect1, rect2) {
  1981. return rect1 && rect2 && (rect1.x === rect2.x) && (rect1.y === rect2.y) && (rect1.width === rect2.width) && (rect1.height === rect2.height);
  1982. };
  1983. cc._rectEqualToZero = function(rect){
  1984. return rect && (rect.x === 0) && (rect.y === 0) && (rect.width === 0) && (rect.height === 0);
  1985. };
  1986. cc.rectContainsRect = function (rect1, rect2) {
  1987. if (!rect1 || !rect2)
  1988. return false;
  1989. return !((rect1.x >= rect2.x) || (rect1.y >= rect2.y) ||
  1990. ( rect1.x + rect1.width <= rect2.x + rect2.width) ||
  1991. ( rect1.y + rect1.height <= rect2.y + rect2.height));
  1992. };
  1993. cc.rectGetMaxX = function (rect) {
  1994. return (rect.x + rect.width);
  1995. };
  1996. cc.rectGetMidX = function (rect) {
  1997. return (rect.x + rect.width / 2.0);
  1998. };
  1999. cc.rectGetMinX = function (rect) {
  2000. return rect.x;
  2001. };
  2002. cc.rectGetMaxY = function (rect) {
  2003. return(rect.y + rect.height);
  2004. };
  2005. cc.rectGetMidY = function (rect) {
  2006. return rect.y + rect.height / 2.0;
  2007. };
  2008. cc.rectGetMinY = function (rect) {
  2009. return rect.y;
  2010. };
  2011. cc.rectContainsPoint = function (rect, point) {
  2012. return (point.x >= cc.rectGetMinX(rect) && point.x <= cc.rectGetMaxX(rect) &&
  2013. point.y >= cc.rectGetMinY(rect) && point.y <= cc.rectGetMaxY(rect)) ;
  2014. };
  2015. cc.rectIntersectsRect = function (ra, rb) {
  2016. var maxax = ra.x + ra.width,
  2017. maxay = ra.y + ra.height,
  2018. maxbx = rb.x + rb.width,
  2019. maxby = rb.y + rb.height;
  2020. return !(maxax < rb.x || maxbx < ra.x || maxay < rb.y || maxby < ra.y);
  2021. };
  2022. cc.rectOverlapsRect = function (rectA, rectB) {
  2023. return !((rectA.x + rectA.width < rectB.x) ||
  2024. (rectB.x + rectB.width < rectA.x) ||
  2025. (rectA.y + rectA.height < rectB.y) ||
  2026. (rectB.y + rectB.height < rectA.y));
  2027. };
  2028. cc.rectUnion = function (rectA, rectB) {
  2029. var rect = cc.rect(0, 0, 0, 0);
  2030. rect.x = Math.min(rectA.x, rectB.x);
  2031. rect.y = Math.min(rectA.y, rectB.y);
  2032. rect.width = Math.max(rectA.x + rectA.width, rectB.x + rectB.width) - rect.x;
  2033. rect.height = Math.max(rectA.y + rectA.height, rectB.y + rectB.height) - rect.y;
  2034. return rect;
  2035. };
  2036. cc.rectIntersection = function (rectA, rectB) {
  2037. var intersection = cc.rect(
  2038. Math.max(cc.rectGetMinX(rectA), cc.rectGetMinX(rectB)),
  2039. Math.max(cc.rectGetMinY(rectA), cc.rectGetMinY(rectB)),
  2040. 0, 0);
  2041. intersection.width = Math.min(cc.rectGetMaxX(rectA), cc.rectGetMaxX(rectB)) - cc.rectGetMinX(intersection);
  2042. intersection.height = Math.min(cc.rectGetMaxY(rectA), cc.rectGetMaxY(rectB)) - cc.rectGetMinY(intersection);
  2043. return intersection;
  2044. };
  2045. cc.SAXParser = cc.Class.extend({
  2046. _parser: null,
  2047. _isSupportDOMParser: null,
  2048. ctor: function () {
  2049. if (window.DOMParser) {
  2050. this._isSupportDOMParser = true;
  2051. this._parser = new DOMParser();
  2052. } else {
  2053. this._isSupportDOMParser = false;
  2054. }
  2055. },
  2056. parse : function(xmlTxt){
  2057. return this._parseXML(xmlTxt);
  2058. },
  2059. _parseXML: function (textxml) {
  2060. var xmlDoc;
  2061. if (this._isSupportDOMParser) {
  2062. xmlDoc = this._parser.parseFromString(textxml, "text/xml");
  2063. } else {
  2064. xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
  2065. xmlDoc.async = "false";
  2066. xmlDoc.loadXML(textxml);
  2067. }
  2068. return xmlDoc;
  2069. }
  2070. });
  2071. cc.PlistParser = cc.SAXParser.extend({
  2072. parse : function (xmlTxt) {
  2073. var xmlDoc = this._parseXML(xmlTxt);
  2074. var plist = xmlDoc.documentElement;
  2075. if (plist.tagName !== 'plist') {
  2076. cc.warn("Not a plist file!");
  2077. return {};
  2078. }
  2079. var node = null;
  2080. for (var i = 0, len = plist.childNodes.length; i < len; i++) {
  2081. node = plist.childNodes[i];
  2082. if (node.nodeType === 1)
  2083. break;
  2084. }
  2085. xmlDoc = null;
  2086. return this._parseNode(node);
  2087. },
  2088. _parseNode: function (node) {
  2089. var data = null, tagName = node.tagName;
  2090. if(tagName === "dict"){
  2091. data = this._parseDict(node);
  2092. }else if(tagName === "array"){
  2093. data = this._parseArray(node);
  2094. }else if(tagName === "string"){
  2095. if (node.childNodes.length === 1)
  2096. data = node.firstChild.nodeValue;
  2097. else {
  2098. data = "";
  2099. for (var i = 0; i < node.childNodes.length; i++)
  2100. data += node.childNodes[i].nodeValue;
  2101. }
  2102. }else if(tagName === "false"){
  2103. data = false;
  2104. }else if(tagName === "true"){
  2105. data = true;
  2106. }else if(tagName === "real"){
  2107. data = parseFloat(node.firstChild.nodeValue);
  2108. }else if(tagName === "integer"){
  2109. data = parseInt(node.firstChild.nodeValue, 10);
  2110. }
  2111. return data;
  2112. },
  2113. _parseArray: function (node) {
  2114. var data = [];
  2115. for (var i = 0, len = node.childNodes.length; i < len; i++) {
  2116. var child = node.childNodes[i];
  2117. if (child.nodeType !== 1)
  2118. continue;
  2119. data.push(this._parseNode(child));
  2120. }
  2121. return data;
  2122. },
  2123. _parseDict: function (node) {
  2124. var data = {};
  2125. var key = null;
  2126. for (var i = 0, len = node.childNodes.length; i < len; i++) {
  2127. var child = node.childNodes[i];
  2128. if (child.nodeType !== 1)
  2129. continue;
  2130. if (child.tagName === 'key')
  2131. key = child.firstChild.nodeValue;
  2132. else
  2133. data[key] = this._parseNode(child);
  2134. }
  2135. return data;
  2136. }
  2137. });
  2138. cc.saxParser = new cc.SAXParser();
  2139. cc.plistParser = new cc.PlistParser();
  2140. cc._txtLoader = {
  2141. load : function(realUrl, url, res, cb){
  2142. cc.loader.loadTxt(realUrl, cb);
  2143. }
  2144. };
  2145. cc.loader.register(["txt", "xml", "vsh", "fsh", "atlas"], cc._txtLoader);
  2146. cc._jsonLoader = {
  2147. load : function(realUrl, url, res, cb){
  2148. cc.loader.loadJson(realUrl, cb);
  2149. }
  2150. };
  2151. cc.loader.register(["json", "ExportJson"], cc._jsonLoader);
  2152. cc._jsLoader = {
  2153. load : function(realUrl, url, res, cb){
  2154. cc.loader.loadJs(realUrl, cb);
  2155. }
  2156. };
  2157. cc.loader.register(["js"], cc._jsLoader);
  2158. cc._imgLoader = {
  2159. load : function(realUrl, url, res, cb){
  2160. var callback;
  2161. if (cc.loader.isLoading(realUrl)) {
  2162. callback = cb;
  2163. }
  2164. else {
  2165. callback = function(err, img){
  2166. if(err)
  2167. return cb(err);
  2168. cc.loader.cache[url] = img;
  2169. cc.textureCache.handleLoadedTexture(url);
  2170. cb(null, img);
  2171. };
  2172. }
  2173. cc.loader.loadImg(realUrl, callback);
  2174. }
  2175. };
  2176. cc.loader.register(["png", "jpg", "bmp","jpeg","gif", "ico", "tiff", "webp"], cc._imgLoader);
  2177. cc._serverImgLoader = {
  2178. load : function(realUrl, url, res, cb){
  2179. cc._imgLoader.load(res.src, url, res, cb);
  2180. }
  2181. };
  2182. cc.loader.register(["serverImg"], cc._serverImgLoader);
  2183. cc._plistLoader = {
  2184. load : function(realUrl, url, res, cb){
  2185. cc.loader.loadTxt(realUrl, function(err, txt){
  2186. if(err)
  2187. return cb(err);
  2188. cb(null, cc.plistParser.parse(txt));
  2189. });
  2190. }
  2191. };
  2192. cc.loader.register(["plist"], cc._plistLoader);
  2193. cc._fontLoader = {
  2194. TYPE : {
  2195. ".eot" : "embedded-opentype",
  2196. ".ttf" : "truetype",
  2197. ".ttc" : "truetype",
  2198. ".woff" : "woff",
  2199. ".svg" : "svg"
  2200. },
  2201. _loadFont : function(name, srcs, type){
  2202. var doc = document, path = cc.path, TYPE = this.TYPE, fontStyle = document.createElement("style");
  2203. fontStyle.type = "text/css";
  2204. doc.body.appendChild(fontStyle);
  2205. var fontStr = "";
  2206. if(isNaN(name - 0))
  2207. fontStr += "@font-face { font-family:" + name + "; src:";
  2208. else
  2209. fontStr += "@font-face { font-family:'" + name + "'; src:";
  2210. if(srcs instanceof Array){
  2211. for(var i = 0, li = srcs.length; i < li; i++){
  2212. var src = srcs[i];
  2213. type = path.extname(src).toLowerCase();
  2214. fontStr += "url('" + srcs[i] + "') format('" + TYPE[type] + "')";
  2215. fontStr += (i === li - 1) ? ";" : ",";
  2216. }
  2217. }else{
  2218. type = type.toLowerCase();
  2219. fontStr += "url('" + srcs + "') format('" + TYPE[type] + "');";
  2220. }
  2221. fontStyle.textContent += fontStr + "}";
  2222. var preloadDiv = document.createElement("div");
  2223. var _divStyle = preloadDiv.style;
  2224. _divStyle.fontFamily = name;
  2225. preloadDiv.innerHTML = ".";
  2226. _divStyle.position = "absolute";
  2227. _divStyle.left = "-100px";
  2228. _divStyle.top = "-100px";
  2229. doc.body.appendChild(preloadDiv);
  2230. },
  2231. load : function(realUrl, url, res, cb){
  2232. var self = this;
  2233. var type = res.type, name = res.name, srcs = res.srcs;
  2234. if(cc.isString(res)){
  2235. type = cc.path.extname(res);
  2236. name = cc.path.basename(res, type);
  2237. self._loadFont(name, res, type);
  2238. }else{
  2239. self._loadFont(name, srcs);
  2240. }
  2241. if(document.fonts){
  2242. document.fonts.load("1em " + name).then(function(){
  2243. cb(null, true);
  2244. }, function(err){
  2245. cb(err);
  2246. });
  2247. }else{
  2248. cb(null, true);
  2249. }
  2250. }
  2251. };
  2252. cc.loader.register(["font", "eot", "ttf", "woff", "svg", "ttc"], cc._fontLoader);
  2253. cc._binaryLoader = {
  2254. load : function(realUrl, url, res, cb){
  2255. cc.loader.loadBinary(realUrl, cb);
  2256. }
  2257. };
  2258. cc._csbLoader = {
  2259. load: function(realUrl, url, res, cb){
  2260. cc.loader.loadCsb(realUrl, cb);
  2261. }
  2262. };
  2263. cc.loader.register(["csb"], cc._csbLoader);
  2264. window["CocosEngine"] = cc.ENGINE_VERSION = "Cocos2d-JS v3.13";
  2265. cc.FIX_ARTIFACTS_BY_STRECHING_TEXEL = 0;
  2266. cc.DIRECTOR_STATS_POSITION = cc.p(0, 0);
  2267. cc.DIRECTOR_FPS_INTERVAL = 0.5;
  2268. cc.COCOSNODE_RENDER_SUBPIXEL = 1;
  2269. cc.SPRITEBATCHNODE_RENDER_SUBPIXEL = 1;
  2270. cc.OPTIMIZE_BLEND_FUNC_FOR_PREMULTIPLIED_ALPHA = 1;
  2271. cc.TEXTURE_ATLAS_USE_TRIANGLE_STRIP = 0;
  2272. cc.TEXTURE_ATLAS_USE_VAO = 0;
  2273. cc.TEXTURE_NPOT_SUPPORT = 0;
  2274. cc.RETINA_DISPLAY_SUPPORT = 1;
  2275. cc.RETINA_DISPLAY_FILENAME_SUFFIX = "-hd";
  2276. cc.USE_LA88_LABELS = 1;
  2277. cc.SPRITE_DEBUG_DRAW = 0;
  2278. cc.SPRITEBATCHNODE_DEBUG_DRAW = 0;
  2279. cc.LABELBMFONT_DEBUG_DRAW = 0;
  2280. cc.LABELATLAS_DEBUG_DRAW = 0;
  2281. cc.IS_RETINA_DISPLAY_SUPPORTED = 1;
  2282. cc.DEFAULT_ENGINE = cc.ENGINE_VERSION + "-canvas";
  2283. cc.ENABLE_STACKABLE_ACTIONS = 1;
  2284. cc.ENABLE_GL_STATE_CACHE = 1;
  2285. cc.$ = function (x) {
  2286. var parent = (this === cc) ? document : this;
  2287. var el = (x instanceof HTMLElement) ? x : parent.querySelector(x);
  2288. if (el) {
  2289. el.find = el.find || cc.$;
  2290. el.hasClass = el.hasClass || function (cls) {
  2291. return this.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
  2292. };
  2293. el.addClass = el.addClass || function (cls) {
  2294. if (!this.hasClass(cls)) {
  2295. if (this.className) {
  2296. this.className += " ";
  2297. }
  2298. this.className += cls;
  2299. }
  2300. return this;
  2301. };
  2302. el.removeClass = el.removeClass || function (cls) {
  2303. if (this.hasClass(cls)) {
  2304. this.className = this.className.replace(cls, '');
  2305. }
  2306. return this;
  2307. };
  2308. el.remove = el.remove || function () {
  2309. if (this.parentNode)
  2310. this.parentNode.removeChild(this);
  2311. return this;
  2312. };
  2313. el.appendTo = el.appendTo || function (x) {
  2314. x.appendChild(this);
  2315. return this;
  2316. };
  2317. el.prependTo = el.prependTo || function (x) {
  2318. ( x.childNodes[0]) ? x.insertBefore(this, x.childNodes[0]) : x.appendChild(this);
  2319. return this;
  2320. };
  2321. el.transforms = el.transforms || function () {
  2322. this.style[cc.$.trans] = cc.$.translate(this.position) + cc.$.rotate(this.rotation) + cc.$.scale(this.scale) + cc.$.skew(this.skew);
  2323. return this;
  2324. };
  2325. el.position = el.position || {x: 0, y: 0};
  2326. el.rotation = el.rotation || 0;
  2327. el.scale = el.scale || {x: 1, y: 1};
  2328. el.skew = el.skew || {x: 0, y: 0};
  2329. el.translates = function (x, y) {
  2330. this.position.x = x;
  2331. this.position.y = y;
  2332. this.transforms();
  2333. return this
  2334. };
  2335. el.rotate = function (x) {
  2336. this.rotation = x;
  2337. this.transforms();
  2338. return this
  2339. };
  2340. el.resize = function (x, y) {
  2341. this.scale.x = x;
  2342. this.scale.y = y;
  2343. this.transforms();
  2344. return this
  2345. };
  2346. el.setSkew = function (x, y) {
  2347. this.skew.x = x;
  2348. this.skew.y = y;
  2349. this.transforms();
  2350. return this
  2351. };
  2352. }
  2353. return el;
  2354. };
  2355. switch (cc.sys.browserType) {
  2356. case cc.sys.BROWSER_TYPE_FIREFOX:
  2357. cc.$.pfx = "Moz";
  2358. cc.$.hd = true;
  2359. break;
  2360. case cc.sys.BROWSER_TYPE_CHROME:
  2361. case cc.sys.BROWSER_TYPE_SAFARI:
  2362. cc.$.pfx = "webkit";
  2363. cc.$.hd = true;
  2364. break;
  2365. case cc.sys.BROWSER_TYPE_OPERA:
  2366. cc.$.pfx = "O";
  2367. cc.$.hd = false;
  2368. break;
  2369. case cc.sys.BROWSER_TYPE_IE:
  2370. cc.$.pfx = "ms";
  2371. cc.$.hd = false;
  2372. break;
  2373. default:
  2374. cc.$.pfx = "webkit";
  2375. cc.$.hd = true;
  2376. }
  2377. cc.$.trans = cc.$.pfx + "Transform";
  2378. cc.$.translate = (cc.$.hd) ? function (a) {
  2379. return "translate3d(" + a.x + "px, " + a.y + "px, 0) "
  2380. } : function (a) {
  2381. return "translate(" + a.x + "px, " + a.y + "px) "
  2382. };
  2383. cc.$.rotate = (cc.$.hd) ? function (a) {
  2384. return "rotateZ(" + a + "deg) ";
  2385. } : function (a) {
  2386. return "rotate(" + a + "deg) ";
  2387. };
  2388. cc.$.scale = function (a) {
  2389. return "scale(" + a.x + ", " + a.y + ") "
  2390. };
  2391. cc.$.skew = function (a) {
  2392. return "skewX(" + -a.x + "deg) skewY(" + a.y + "deg)";
  2393. };
  2394. cc.$new = function (x) {
  2395. return cc.$(document.createElement(x))
  2396. };
  2397. cc.$.findpos = function (obj) {
  2398. var curleft = 0;
  2399. var curtop = 0;
  2400. do {
  2401. curleft += obj.offsetLeft;
  2402. curtop += obj.offsetTop;
  2403. } while (obj = obj.offsetParent);
  2404. return {x: curleft, y: curtop};
  2405. };
  2406. cc.INVALID_INDEX = -1;
  2407. cc.PI = Math.PI;
  2408. cc.FLT_MAX = parseFloat('3.402823466e+38F');
  2409. cc.FLT_MIN = parseFloat("1.175494351e-38F");
  2410. cc.RAD = cc.PI / 180;
  2411. cc.DEG = 180 / cc.PI;
  2412. cc.UINT_MAX = 0xffffffff;
  2413. cc.swap = function (x, y, ref) {
  2414. if (cc.isObject(ref) && !cc.isUndefined(ref.x) && !cc.isUndefined(ref.y)) {
  2415. var tmp = ref[x];
  2416. ref[x] = ref[y];
  2417. ref[y] = tmp;
  2418. } else
  2419. cc.log(cc._LogInfos.swap);
  2420. };
  2421. cc.lerp = function (a, b, r) {
  2422. return a + (b - a) * r;
  2423. };
  2424. cc.rand = function () {
  2425. return Math.random() * 0xffffff;
  2426. };
  2427. cc.randomMinus1To1 = function () {
  2428. return (Math.random() - 0.5) * 2;
  2429. };
  2430. cc.random0To1 = Math.random;
  2431. cc.degreesToRadians = function (angle) {
  2432. return angle * cc.RAD;
  2433. };
  2434. cc.radiansToDegrees = function (angle) {
  2435. return angle * cc.DEG;
  2436. };
  2437. cc.radiansToDegress = function (angle) {
  2438. cc.log(cc._LogInfos.radiansToDegress);
  2439. return angle * cc.DEG;
  2440. };
  2441. cc.REPEAT_FOREVER = Number.MAX_VALUE - 1;
  2442. cc.nodeDrawSetup = function (node) {
  2443. if (node._shaderProgram) {
  2444. node._shaderProgram.use();
  2445. node._shaderProgram.setUniformForModelViewAndProjectionMatrixWithMat4();
  2446. }
  2447. };
  2448. cc.enableDefaultGLStates = function () {
  2449. };
  2450. cc.disableDefaultGLStates = function () {
  2451. };
  2452. cc.incrementGLDraws = function (addNumber) {
  2453. cc.g_NumberOfDraws += addNumber;
  2454. };
  2455. cc.FLT_EPSILON = 0.0000001192092896;
  2456. cc.contentScaleFactor = cc.IS_RETINA_DISPLAY_SUPPORTED ? function () {
  2457. return cc.director.getContentScaleFactor();
  2458. } : function () {
  2459. return 1;
  2460. };
  2461. cc.pointPointsToPixels = function (points) {
  2462. var scale = cc.contentScaleFactor();
  2463. return cc.p(points.x * scale, points.y * scale);
  2464. };
  2465. cc.pointPixelsToPoints = function (pixels) {
  2466. var scale = cc.contentScaleFactor();
  2467. return cc.p(pixels.x / scale, pixels.y / scale);
  2468. };
  2469. cc._pointPixelsToPointsOut = function(pixels, outPoint){
  2470. var scale = cc.contentScaleFactor();
  2471. outPoint.x = pixels.x / scale;
  2472. outPoint.y = pixels.y / scale;
  2473. };
  2474. cc.sizePointsToPixels = function (sizeInPoints) {
  2475. var scale = cc.contentScaleFactor();
  2476. return cc.size(sizeInPoints.width * scale, sizeInPoints.height * scale);
  2477. };
  2478. cc.sizePixelsToPoints = function (sizeInPixels) {
  2479. var scale = cc.contentScaleFactor();
  2480. return cc.size(sizeInPixels.width / scale, sizeInPixels.height / scale);
  2481. };
  2482. cc._sizePixelsToPointsOut = function (sizeInPixels, outSize) {
  2483. var scale = cc.contentScaleFactor();
  2484. outSize.width = sizeInPixels.width / scale;
  2485. outSize.height = sizeInPixels.height / scale;
  2486. };
  2487. cc.rectPixelsToPoints = cc.IS_RETINA_DISPLAY_SUPPORTED ? function (pixel) {
  2488. var scale = cc.contentScaleFactor();
  2489. return cc.rect(pixel.x / scale, pixel.y / scale,
  2490. pixel.width / scale, pixel.height / scale);
  2491. } : function (p) {
  2492. return p;
  2493. };
  2494. cc.rectPointsToPixels = cc.IS_RETINA_DISPLAY_SUPPORTED ? function (point) {
  2495. var scale = cc.contentScaleFactor();
  2496. return cc.rect(point.x * scale, point.y * scale,
  2497. point.width * scale, point.height * scale);
  2498. } : function (p) {
  2499. return p;
  2500. };
  2501. cc.ONE = 1;
  2502. cc.ZERO = 0;
  2503. cc.SRC_ALPHA = 0x0302;
  2504. cc.SRC_ALPHA_SATURATE = 0x308;
  2505. cc.SRC_COLOR = 0x300;
  2506. cc.DST_ALPHA = 0x304;
  2507. cc.DST_COLOR = 0x306;
  2508. cc.ONE_MINUS_SRC_ALPHA = 0x0303;
  2509. cc.ONE_MINUS_SRC_COLOR = 0x301;
  2510. cc.ONE_MINUS_DST_ALPHA = 0x305;
  2511. cc.ONE_MINUS_DST_COLOR = 0x0307;
  2512. cc.ONE_MINUS_CONSTANT_ALPHA = 0x8004;
  2513. cc.ONE_MINUS_CONSTANT_COLOR = 0x8002;
  2514. cc.LINEAR = 0x2601;
  2515. cc.REPEAT = 0x2901;
  2516. cc.CLAMP_TO_EDGE = 0x812f;
  2517. cc.MIRRORED_REPEAT = 0x8370;
  2518. cc.BLEND_SRC = cc.SRC_ALPHA;
  2519. cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
  2520. if (cc._renderType === cc.game.RENDER_TYPE_WEBGL
  2521. && cc.OPTIMIZE_BLEND_FUNC_FOR_PREMULTIPLIED_ALPHA) {
  2522. cc.BLEND_SRC = cc.ONE;
  2523. }
  2524. });
  2525. cc.BLEND_DST = cc.ONE_MINUS_SRC_ALPHA;
  2526. cc.checkGLErrorDebug = function () {
  2527. if (cc.renderMode === cc.game.RENDER_TYPE_WEBGL) {
  2528. var _error = cc._renderContext.getError();
  2529. if (_error) {
  2530. cc.log(cc._LogInfos.checkGLErrorDebug, _error);
  2531. }
  2532. }
  2533. };
  2534. cc.ORIENTATION_PORTRAIT = 1;
  2535. cc.ORIENTATION_LANDSCAPE = 2;
  2536. cc.ORIENTATION_AUTO = 3;
  2537. cc.VERTEX_ATTRIB_FLAG_NONE = 0;
  2538. cc.VERTEX_ATTRIB_FLAG_POSITION = 1 << 0;
  2539. cc.VERTEX_ATTRIB_FLAG_COLOR = 1 << 1;
  2540. cc.VERTEX_ATTRIB_FLAG_TEX_COORDS = 1 << 2;
  2541. cc.VERTEX_ATTRIB_FLAG_POS_COLOR_TEX = ( cc.VERTEX_ATTRIB_FLAG_POSITION | cc.VERTEX_ATTRIB_FLAG_COLOR | cc.VERTEX_ATTRIB_FLAG_TEX_COORDS );
  2542. cc.GL_ALL = 0;
  2543. cc.VERTEX_ATTRIB_POSITION = 0;
  2544. cc.VERTEX_ATTRIB_COLOR = 1;
  2545. cc.VERTEX_ATTRIB_TEX_COORDS = 2;
  2546. cc.VERTEX_ATTRIB_MAX = 7;
  2547. cc.UNIFORM_PMATRIX = 0;
  2548. cc.UNIFORM_MVMATRIX = 1;
  2549. cc.UNIFORM_MVPMATRIX = 2;
  2550. cc.UNIFORM_TIME = 3;
  2551. cc.UNIFORM_SINTIME = 4;
  2552. cc.UNIFORM_COSTIME = 5;
  2553. cc.UNIFORM_RANDOM01 = 6;
  2554. cc.UNIFORM_SAMPLER = 7;
  2555. cc.UNIFORM_MAX = 8;
  2556. cc.SHADER_POSITION_TEXTURECOLOR = "ShaderPositionTextureColor";
  2557. cc.SHADER_SPRITE_POSITION_TEXTURECOLOR = "ShaderSpritePositionTextureColor";
  2558. cc.SHADER_POSITION_TEXTURECOLORALPHATEST = "ShaderPositionTextureColorAlphaTest";
  2559. cc.SHADER_SPRITE_POSITION_TEXTURECOLORALPHATEST = "ShaderSpritePositionTextureColorAlphaTest";
  2560. cc.SHADER_POSITION_COLOR = "ShaderPositionColor";
  2561. cc.SHADER_SPRITE_POSITION_COLOR = "ShaderSpritePositionColor";
  2562. cc.SHADER_POSITION_TEXTURE = "ShaderPositionTexture";
  2563. cc.SHADER_POSITION_TEXTURE_UCOLOR = "ShaderPositionTexture_uColor";
  2564. cc.SHADER_POSITION_TEXTUREA8COLOR = "ShaderPositionTextureA8Color";
  2565. cc.SHADER_POSITION_UCOLOR = "ShaderPosition_uColor";
  2566. cc.SHADER_POSITION_LENGTHTEXTURECOLOR = "ShaderPositionLengthTextureColor";
  2567. cc.UNIFORM_PMATRIX_S = "CC_PMatrix";
  2568. cc.UNIFORM_MVMATRIX_S = "CC_MVMatrix";
  2569. cc.UNIFORM_MVPMATRIX_S = "CC_MVPMatrix";
  2570. cc.UNIFORM_TIME_S = "CC_Time";
  2571. cc.UNIFORM_SINTIME_S = "CC_SinTime";
  2572. cc.UNIFORM_COSTIME_S = "CC_CosTime";
  2573. cc.UNIFORM_RANDOM01_S = "CC_Random01";
  2574. cc.UNIFORM_SAMPLER_S = "CC_Texture0";
  2575. cc.UNIFORM_ALPHA_TEST_VALUE_S = "CC_alpha_value";
  2576. cc.ATTRIBUTE_NAME_COLOR = "a_color";
  2577. cc.ATTRIBUTE_NAME_POSITION = "a_position";
  2578. cc.ATTRIBUTE_NAME_TEX_COORD = "a_texCoord";
  2579. cc.ATTRIBUTE_NAME_MVMAT = "a_mvMatrix";
  2580. cc.ITEM_SIZE = 32;
  2581. cc.CURRENT_ITEM = 0xc0c05001;
  2582. cc.ZOOM_ACTION_TAG = 0xc0c05002;
  2583. cc.NORMAL_TAG = 8801;
  2584. cc.SELECTED_TAG = 8802;
  2585. cc.DISABLE_TAG = 8803;
  2586. cc.arrayVerifyType = function (arr, type) {
  2587. if (arr && arr.length > 0) {
  2588. for (var i = 0; i < arr.length; i++) {
  2589. if (!(arr[i] instanceof type)) {
  2590. cc.log("element type is wrong!");
  2591. return false;
  2592. }
  2593. }
  2594. }
  2595. return true;
  2596. };
  2597. cc.arrayRemoveObject = function (arr, delObj) {
  2598. for (var i = 0, l = arr.length; i < l; i++) {
  2599. if (arr[i] === delObj) {
  2600. arr.splice(i, 1);
  2601. break;
  2602. }
  2603. }
  2604. };
  2605. cc.arrayRemoveArray = function (arr, minusArr) {
  2606. for (var i = 0, l = minusArr.length; i < l; i++) {
  2607. cc.arrayRemoveObject(arr, minusArr[i]);
  2608. }
  2609. };
  2610. cc.arrayAppendObjectsToIndex = function(arr, addObjs,index){
  2611. arr.splice.apply(arr, [index, 0].concat(addObjs));
  2612. return arr;
  2613. };
  2614. cc.copyArray = function(arr){
  2615. var i, len = arr.length, arr_clone = new Array(len);
  2616. for (i = 0; i < len; i += 1)
  2617. arr_clone[i] = arr[i];
  2618. return arr_clone;
  2619. };
  2620. cc._tmp.PrototypeColor = function () {
  2621. var _p = cc.color;
  2622. _p._getWhite = function () {
  2623. return _p(255, 255, 255);
  2624. };
  2625. _p._getYellow = function () {
  2626. return _p(255, 255, 0);
  2627. };
  2628. _p._getBlue = function () {
  2629. return _p(0, 0, 255);
  2630. };
  2631. _p._getGreen = function () {
  2632. return _p(0, 255, 0);
  2633. };
  2634. _p._getRed = function () {
  2635. return _p(255, 0, 0);
  2636. };
  2637. _p._getMagenta = function () {
  2638. return _p(255, 0, 255);
  2639. };
  2640. _p._getBlack = function () {
  2641. return _p(0, 0, 0);
  2642. };
  2643. _p._getOrange = function () {
  2644. return _p(255, 127, 0);
  2645. };
  2646. _p._getGray = function () {
  2647. return _p(166, 166, 166);
  2648. };
  2649. _p.WHITE;
  2650. cc.defineGetterSetter(_p, "WHITE", _p._getWhite);
  2651. _p.YELLOW;
  2652. cc.defineGetterSetter(_p, "YELLOW", _p._getYellow);
  2653. _p.BLUE;
  2654. cc.defineGetterSetter(_p, "BLUE", _p._getBlue);
  2655. _p.GREEN;
  2656. cc.defineGetterSetter(_p, "GREEN", _p._getGreen);
  2657. _p.RED;
  2658. cc.defineGetterSetter(_p, "RED", _p._getRed);
  2659. _p.MAGENTA;
  2660. cc.defineGetterSetter(_p, "MAGENTA", _p._getMagenta);
  2661. _p.BLACK;
  2662. cc.defineGetterSetter(_p, "BLACK", _p._getBlack);
  2663. _p.ORANGE;
  2664. cc.defineGetterSetter(_p, "ORANGE", _p._getOrange);
  2665. _p.GRAY;
  2666. cc.defineGetterSetter(_p, "GRAY", _p._getGray);
  2667. cc.BlendFunc._disable = function(){
  2668. return new cc.BlendFunc(cc.ONE, cc.ZERO);
  2669. };
  2670. cc.BlendFunc._alphaPremultiplied = function(){
  2671. return new cc.BlendFunc(cc.ONE, cc.ONE_MINUS_SRC_ALPHA);
  2672. };
  2673. cc.BlendFunc._alphaNonPremultiplied = function(){
  2674. return new cc.BlendFunc(cc.SRC_ALPHA, cc.ONE_MINUS_SRC_ALPHA);
  2675. };
  2676. cc.BlendFunc._additive = function(){
  2677. return new cc.BlendFunc(cc.SRC_ALPHA, cc.ONE);
  2678. };
  2679. cc.BlendFunc.DISABLE;
  2680. cc.defineGetterSetter(cc.BlendFunc, "DISABLE", cc.BlendFunc._disable);
  2681. cc.BlendFunc.ALPHA_PREMULTIPLIED;
  2682. cc.defineGetterSetter(cc.BlendFunc, "ALPHA_PREMULTIPLIED", cc.BlendFunc._alphaPremultiplied);
  2683. cc.BlendFunc.ALPHA_NON_PREMULTIPLIED;
  2684. cc.defineGetterSetter(cc.BlendFunc, "ALPHA_NON_PREMULTIPLIED", cc.BlendFunc._alphaNonPremultiplied);
  2685. cc.BlendFunc.ADDITIVE;
  2686. cc.defineGetterSetter(cc.BlendFunc, "ADDITIVE", cc.BlendFunc._additive);
  2687. };
  2688. var cc = cc || {};
  2689. cc._tmp = cc._tmp || {};
  2690. cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
  2691. if (cc._renderType !== cc.game.RENDER_TYPE_WEBGL) {
  2692. return;
  2693. }
  2694. cc.color = function (r, g, b, a, arrayBuffer, offset) {
  2695. if (r === undefined)
  2696. return new cc.Color(0, 0, 0, 255, arrayBuffer, offset);
  2697. if (cc.isString(r)) {
  2698. var color = cc.hexToColor(r);
  2699. return new cc.Color(color.r, color.g, color.b, color.a);
  2700. }
  2701. if (cc.isObject(r))
  2702. return new cc.Color(r.r, r.g, r.b, r.a, r.arrayBuffer, r.offset);
  2703. return new cc.Color(r, g, b, a, arrayBuffer, offset);
  2704. };
  2705. cc.Color = function (r, g, b, a, arrayBuffer, offset) {
  2706. this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.Color.BYTES_PER_ELEMENT);
  2707. this._offset = offset || 0;
  2708. var locArrayBuffer = this._arrayBuffer, locOffset = this._offset;
  2709. this._view = new Uint8Array(locArrayBuffer, locOffset, 4);
  2710. this._view[0] = r || 0;
  2711. this._view[1] = g || 0;
  2712. this._view[2] = b || 0;
  2713. this._view[3] = (a == null) ? 255 : a;
  2714. if (a === undefined)
  2715. this.a_undefined = true;
  2716. };
  2717. cc.Color.BYTES_PER_ELEMENT = 4;
  2718. var _p = cc.Color.prototype;
  2719. _p._getR = function () {
  2720. return this._view[0];
  2721. };
  2722. _p._setR = function (value) {
  2723. this._view[0] = value < 0 ? 0 : value;
  2724. };
  2725. _p._getG = function () {
  2726. return this._view[1];
  2727. };
  2728. _p._setG = function (value) {
  2729. this._view[1] = value < 0 ? 0 : value;
  2730. };
  2731. _p._getB = function () {
  2732. return this._view[2];
  2733. };
  2734. _p._setB = function (value) {
  2735. this._view[2] = value < 0 ? 0 : value;
  2736. };
  2737. _p._getA = function () {
  2738. return this._view[3];
  2739. };
  2740. _p._setA = function (value) {
  2741. this._view[3] = value < 0 ? 0 : value;
  2742. };
  2743. _p.r;
  2744. cc.defineGetterSetter(_p, "r", _p._getR, _p._setR);
  2745. _p.g;
  2746. cc.defineGetterSetter(_p, "g", _p._getG, _p._setG);
  2747. _p.b;
  2748. cc.defineGetterSetter(_p, "b", _p._getB, _p._setB);
  2749. _p.a;
  2750. cc.defineGetterSetter(_p, "a", _p._getA, _p._setA);
  2751. cc.assert(cc.isFunction(cc._tmp.PrototypeColor), cc._LogInfos.MissingFile, "CCTypesPropertyDefine.js");
  2752. cc._tmp.PrototypeColor();
  2753. delete cc._tmp.PrototypeColor;
  2754. });
  2755. cc.Color = function (r, g, b, a) {
  2756. this.r = r || 0;
  2757. this.g = g || 0;
  2758. this.b = b || 0;
  2759. this.a = (a == null) ? 255 : a;
  2760. };
  2761. cc.color = function (r, g, b, a) {
  2762. if (r === undefined)
  2763. return {r: 0, g: 0, b: 0, a: 255};
  2764. if (cc.isString(r))
  2765. return cc.hexToColor(r);
  2766. if (cc.isObject(r))
  2767. return {r: r.r, g: r.g, b: r.b, a: (r.a == null) ? 255 : r.a};
  2768. return {r: r, g: g, b: b, a: (a == null ? 255 : a)};
  2769. };
  2770. cc.colorEqual = function (color1, color2) {
  2771. return color1.r === color2.r && color1.g === color2.g && color1.b === color2.b;
  2772. };
  2773. cc.Acceleration = function (x, y, z, timestamp) {
  2774. this.x = x || 0;
  2775. this.y = y || 0;
  2776. this.z = z || 0;
  2777. this.timestamp = timestamp || 0;
  2778. };
  2779. cc.Vertex2F = function (x, y, arrayBuffer, offset) {
  2780. this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.Vertex2F.BYTES_PER_ELEMENT);
  2781. this._offset = offset || 0;
  2782. this._view = new Float32Array(this._arrayBuffer, this._offset, 2);
  2783. this._view[0] = x || 0;
  2784. this._view[1] = y || 0;
  2785. };
  2786. cc.Vertex2F.BYTES_PER_ELEMENT = 8;
  2787. _p = cc.Vertex2F.prototype;
  2788. _p._getX = function () {
  2789. return this._view[0];
  2790. };
  2791. _p._setX = function (xValue) {
  2792. this._view[0] = xValue;
  2793. };
  2794. _p._getY = function () {
  2795. return this._view[1];
  2796. };
  2797. _p._setY = function (yValue) {
  2798. this._view[1] = yValue;
  2799. };
  2800. _p.x;
  2801. cc.defineGetterSetter(_p, "x", _p._getX, _p._setX);
  2802. _p.y;
  2803. cc.defineGetterSetter(_p, "y", _p._getY, _p._setY);
  2804. cc.Vertex3F = function (x, y, z, arrayBuffer, offset) {
  2805. this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.Vertex3F.BYTES_PER_ELEMENT);
  2806. this._offset = offset || 0;
  2807. var locArrayBuffer = this._arrayBuffer, locOffset = this._offset;
  2808. this._view = new Float32Array(locArrayBuffer, locOffset, 3);
  2809. this._view[0] = x || 0;
  2810. this._view[1] = y || 0;
  2811. this._view[2] = z || 0;
  2812. };
  2813. cc.Vertex3F.BYTES_PER_ELEMENT = 12;
  2814. _p = cc.Vertex3F.prototype;
  2815. _p._getX = function () {
  2816. return this._view[0];
  2817. };
  2818. _p._setX = function (xValue) {
  2819. this._view[0] = xValue;
  2820. };
  2821. _p._getY = function () {
  2822. return this._view[1];
  2823. };
  2824. _p._setY = function (yValue) {
  2825. this._view[1] = yValue;
  2826. };
  2827. _p._getZ = function () {
  2828. return this._view[2];
  2829. };
  2830. _p._setZ = function (zValue) {
  2831. this._view[2] = zValue;
  2832. };
  2833. _p.x;
  2834. cc.defineGetterSetter(_p, "x", _p._getX, _p._setX);
  2835. _p.y;
  2836. cc.defineGetterSetter(_p, "y", _p._getY, _p._setY);
  2837. _p.z;
  2838. cc.defineGetterSetter(_p, "z", _p._getZ, _p._setZ);
  2839. cc.Tex2F = function (u, v, arrayBuffer, offset) {
  2840. this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.Tex2F.BYTES_PER_ELEMENT);
  2841. this._offset = offset || 0;
  2842. this._view = new Float32Array(this._arrayBuffer, this._offset, 2);
  2843. this._view[0] = u || 0;
  2844. this._view[1] = v || 0;
  2845. };
  2846. cc.Tex2F.BYTES_PER_ELEMENT = 8;
  2847. _p = cc.Tex2F.prototype;
  2848. _p._getU = function () {
  2849. return this._view[0];
  2850. };
  2851. _p._setU = function (xValue) {
  2852. this._view[0] = xValue;
  2853. };
  2854. _p._getV = function () {
  2855. return this._view[1];
  2856. };
  2857. _p._setV = function (yValue) {
  2858. this._view[1] = yValue;
  2859. };
  2860. _p.u;
  2861. cc.defineGetterSetter(_p, "u", _p._getU, _p._setU);
  2862. _p.v;
  2863. cc.defineGetterSetter(_p, "v", _p._getV, _p._setV);
  2864. cc.Quad2 = function (tl, tr, bl, br, arrayBuffer, offset) {
  2865. this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.Quad2.BYTES_PER_ELEMENT);
  2866. this._offset = offset || 0;
  2867. var locArrayBuffer = this._arrayBuffer, locOffset = this._offset, locElementLen = cc.Vertex2F.BYTES_PER_ELEMENT;
  2868. this._tl = tl ? new cc.Vertex2F(tl.x, tl.y, locArrayBuffer, locOffset) : new cc.Vertex2F(0, 0, locArrayBuffer, locOffset);
  2869. locOffset += locElementLen;
  2870. this._tr = tr ? new cc.Vertex2F(tr.x, tr.y, locArrayBuffer, locOffset) : new cc.Vertex2F(0, 0, locArrayBuffer, locOffset);
  2871. locOffset += locElementLen;
  2872. this._bl = bl ? new cc.Vertex2F(bl.x, bl.y, locArrayBuffer, locOffset) : new cc.Vertex2F(0, 0, locArrayBuffer, locOffset);
  2873. locOffset += locElementLen;
  2874. this._br = br ? new cc.Vertex2F(br.x, br.y, locArrayBuffer, locOffset) : new cc.Vertex2F(0, 0, locArrayBuffer, locOffset);
  2875. };
  2876. cc.Quad2.BYTES_PER_ELEMENT = 32;
  2877. _p = cc.Quad2.prototype;
  2878. _p._getTL = function () {
  2879. return this._tl;
  2880. };
  2881. _p._setTL = function (tlValue) {
  2882. this._tl._view[0] = tlValue.x;
  2883. this._tl._view[1] = tlValue.y;
  2884. };
  2885. _p._getTR = function () {
  2886. return this._tr;
  2887. };
  2888. _p._setTR = function (trValue) {
  2889. this._tr._view[0] = trValue.x;
  2890. this._tr._view[1] = trValue.y;
  2891. };
  2892. _p._getBL = function() {
  2893. return this._bl;
  2894. };
  2895. _p._setBL = function (blValue) {
  2896. this._bl._view[0] = blValue.x;
  2897. this._bl._view[1] = blValue.y;
  2898. };
  2899. _p._getBR = function () {
  2900. return this._br;
  2901. };
  2902. _p._setBR = function (brValue) {
  2903. this._br._view[0] = brValue.x;
  2904. this._br._view[1] = brValue.y;
  2905. };
  2906. _p.tl;
  2907. cc.defineGetterSetter(_p, "tl", _p._getTL, _p._setTL);
  2908. _p.tr;
  2909. cc.defineGetterSetter(_p, "tr", _p._getTR, _p._setTR);
  2910. _p.bl;
  2911. cc.defineGetterSetter(_p, "bl", _p._getBL, _p._setBL);
  2912. _p.br;
  2913. cc.defineGetterSetter(_p, "br", _p._getBR, _p._setBR);
  2914. cc.Quad3 = function (bl, br, tl, tr, arrayBuffer, offset) {
  2915. this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.Quad3.BYTES_PER_ELEMENT);
  2916. this._offset = offset || 0;
  2917. var locArrayBuffer = this._arrayBuffer, locOffset = this._offset, locElementLen = cc.Vertex3F.BYTES_PER_ELEMENT;
  2918. this.bl = bl ? new cc.Vertex3F(bl.x, bl.y, bl.z, locArrayBuffer, locOffset) : new cc.Vertex3F(0, 0, 0, locArrayBuffer, locOffset);
  2919. locOffset += locElementLen;
  2920. this.br = br ? new cc.Vertex3F(br.x, br.y, br.z, locArrayBuffer, locOffset) : new cc.Vertex3F(0, 0, 0, locArrayBuffer, locOffset);
  2921. locOffset += locElementLen;
  2922. this.tl = tl ? new cc.Vertex3F(tl.x, tl.y, tl.z, locArrayBuffer, locOffset) : new cc.Vertex3F(0, 0, 0, locArrayBuffer, locOffset);
  2923. locOffset += locElementLen;
  2924. this.tr = tr ? new cc.Vertex3F(tr.x, tr.y, tr.z, locArrayBuffer, locOffset) : new cc.Vertex3F(0, 0, 0, locArrayBuffer, locOffset);
  2925. };
  2926. cc.Quad3.BYTES_PER_ELEMENT = 48;
  2927. cc.V3F_C4B_T2F = function (vertices, colors, texCoords, arrayBuffer, offset) {
  2928. this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.V3F_C4B_T2F.BYTES_PER_ELEMENT);
  2929. this._offset = offset || 0;
  2930. var locArrayBuffer = this._arrayBuffer, locOffset = this._offset;
  2931. this._vertices = vertices ? new cc.Vertex3F(vertices.x, vertices.y, vertices.z, locArrayBuffer, locOffset) :
  2932. new cc.Vertex3F(0, 0, 0, locArrayBuffer, locOffset);
  2933. locOffset += cc.Vertex3F.BYTES_PER_ELEMENT;
  2934. this._colors = colors ? new cc.Color(colors.r, colors.g, colors.b, colors.a, locArrayBuffer, locOffset) :
  2935. new cc.Color(0, 0, 0, 0, locArrayBuffer, locOffset);
  2936. locOffset += cc.Color.BYTES_PER_ELEMENT;
  2937. this._texCoords = texCoords ? new cc.Tex2F(texCoords.u, texCoords.v, locArrayBuffer, locOffset) :
  2938. new cc.Tex2F(0, 0, locArrayBuffer, locOffset);
  2939. };
  2940. cc.V3F_C4B_T2F.BYTES_PER_ELEMENT = 24;
  2941. _p = cc.V3F_C4B_T2F.prototype;
  2942. _p._getVertices = function () {
  2943. return this._vertices;
  2944. };
  2945. _p._setVertices = function (verticesValue) {
  2946. var locVertices = this._vertices;
  2947. locVertices._view[0] = verticesValue.x;
  2948. locVertices._view[1] = verticesValue.y;
  2949. locVertices._view[2] = verticesValue.z;
  2950. };
  2951. _p._getColor = function () {
  2952. return this._colors;
  2953. };
  2954. _p._setColor = function (colorValue) {
  2955. var locColors = this._colors;
  2956. locColors._view[0] = colorValue.r;
  2957. locColors._view[1] = colorValue.g;
  2958. locColors._view[2] = colorValue.b;
  2959. locColors._view[3] = colorValue.a;
  2960. };
  2961. _p._getTexCoords = function () {
  2962. return this._texCoords;
  2963. };
  2964. _p._setTexCoords = function (texValue) {
  2965. this._texCoords._view[0] = texValue.u;
  2966. this._texCoords._view[1] = texValue.v;
  2967. };
  2968. _p.vertices;
  2969. cc.defineGetterSetter(_p, "vertices", _p._getVertices, _p._setVertices);
  2970. _p.colors;
  2971. cc.defineGetterSetter(_p, "colors", _p._getColor, _p._setColor);
  2972. _p.texCoords;
  2973. cc.defineGetterSetter(_p, "texCoords", _p._getTexCoords, _p._setTexCoords);
  2974. cc.V3F_C4B_T2F_Quad = function (tl, bl, tr, br, arrayBuffer, offset) {
  2975. this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.V3F_C4B_T2F_Quad.BYTES_PER_ELEMENT);
  2976. this._offset = offset || 0;
  2977. var locArrayBuffer = this._arrayBuffer, locOffset = this._offset, locElementLen = cc.V3F_C4B_T2F.BYTES_PER_ELEMENT;
  2978. this._tl = tl ? new cc.V3F_C4B_T2F(tl.vertices, tl.colors, tl.texCoords, locArrayBuffer, locOffset) :
  2979. new cc.V3F_C4B_T2F(null, null, null, locArrayBuffer, locOffset);
  2980. locOffset += locElementLen;
  2981. this._bl = bl ? new cc.V3F_C4B_T2F(bl.vertices, bl.colors, bl.texCoords, locArrayBuffer, locOffset) :
  2982. new cc.V3F_C4B_T2F(null, null, null, locArrayBuffer, locOffset);
  2983. locOffset += locElementLen;
  2984. this._tr = tr ? new cc.V3F_C4B_T2F(tr.vertices, tr.colors, tr.texCoords, locArrayBuffer, locOffset) :
  2985. new cc.V3F_C4B_T2F(null, null, null, locArrayBuffer, locOffset);
  2986. locOffset += locElementLen;
  2987. this._br = br ? new cc.V3F_C4B_T2F(br.vertices, br.colors, br.texCoords, locArrayBuffer, locOffset) :
  2988. new cc.V3F_C4B_T2F(null, null, null, locArrayBuffer, locOffset);
  2989. };
  2990. cc.V3F_C4B_T2F_Quad.BYTES_PER_ELEMENT = 96;
  2991. _p = cc.V3F_C4B_T2F_Quad.prototype;
  2992. _p._getTL = function () {
  2993. return this._tl;
  2994. };
  2995. _p._setTL = function (tlValue) {
  2996. var locTl = this._tl;
  2997. locTl.vertices = tlValue.vertices;
  2998. locTl.colors = tlValue.colors;
  2999. locTl.texCoords = tlValue.texCoords;
  3000. };
  3001. _p._getBL = function () {
  3002. return this._bl;
  3003. };
  3004. _p._setBL = function (blValue) {
  3005. var locBl = this._bl;
  3006. locBl.vertices = blValue.vertices;
  3007. locBl.colors = blValue.colors;
  3008. locBl.texCoords = blValue.texCoords;
  3009. };
  3010. _p._getTR = function () {
  3011. return this._tr;
  3012. };
  3013. _p._setTR = function (trValue) {
  3014. var locTr = this._tr;
  3015. locTr.vertices = trValue.vertices;
  3016. locTr.colors = trValue.colors;
  3017. locTr.texCoords = trValue.texCoords;
  3018. };
  3019. _p._getBR = function () {
  3020. return this._br;
  3021. };
  3022. _p._setBR = function (brValue) {
  3023. var locBr = this._br;
  3024. locBr.vertices = brValue.vertices;
  3025. locBr.colors = brValue.colors;
  3026. locBr.texCoords = brValue.texCoords;
  3027. };
  3028. _p._getArrayBuffer = function () {
  3029. return this._arrayBuffer;
  3030. };
  3031. _p.tl;
  3032. cc.defineGetterSetter(_p, "tl", _p._getTL, _p._setTL);
  3033. _p.tr;
  3034. cc.defineGetterSetter(_p, "tr", _p._getTR, _p._setTR);
  3035. _p.bl;
  3036. cc.defineGetterSetter(_p, "bl", _p._getBL, _p._setBL);
  3037. _p.br;
  3038. cc.defineGetterSetter(_p, "br", _p._getBR, _p._setBR);
  3039. _p.arrayBuffer;
  3040. cc.defineGetterSetter(_p, "arrayBuffer", _p._getArrayBuffer, null);
  3041. cc.V3F_C4B_T2F_QuadZero = function () {
  3042. return new cc.V3F_C4B_T2F_Quad();
  3043. };
  3044. cc.V3F_C4B_T2F_QuadCopy = function (sourceQuad) {
  3045. if (!sourceQuad)
  3046. return cc.V3F_C4B_T2F_QuadZero();
  3047. var srcTL = sourceQuad.tl, srcBL = sourceQuad.bl, srcTR = sourceQuad.tr, srcBR = sourceQuad.br;
  3048. return {
  3049. tl: {vertices: {x: srcTL.vertices.x, y: srcTL.vertices.y, z: srcTL.vertices.z},
  3050. colors: {r: srcTL.colors.r, g: srcTL.colors.g, b: srcTL.colors.b, a: srcTL.colors.a},
  3051. texCoords: {u: srcTL.texCoords.u, v: srcTL.texCoords.v}},
  3052. bl: {vertices: {x: srcBL.vertices.x, y: srcBL.vertices.y, z: srcBL.vertices.z},
  3053. colors: {r: srcBL.colors.r, g: srcBL.colors.g, b: srcBL.colors.b, a: srcBL.colors.a},
  3054. texCoords: {u: srcBL.texCoords.u, v: srcBL.texCoords.v}},
  3055. tr: {vertices: {x: srcTR.vertices.x, y: srcTR.vertices.y, z: srcTR.vertices.z},
  3056. colors: {r: srcTR.colors.r, g: srcTR.colors.g, b: srcTR.colors.b, a: srcTR.colors.a},
  3057. texCoords: {u: srcTR.texCoords.u, v: srcTR.texCoords.v}},
  3058. br: {vertices: {x: srcBR.vertices.x, y: srcBR.vertices.y, z: srcBR.vertices.z},
  3059. colors: {r: srcBR.colors.r, g: srcBR.colors.g, b: srcBR.colors.b, a: srcBR.colors.a},
  3060. texCoords: {u: srcBR.texCoords.u, v: srcBR.texCoords.v}}
  3061. };
  3062. };
  3063. cc.V3F_C4B_T2F_QuadsCopy = function (sourceQuads) {
  3064. if (!sourceQuads)
  3065. return [];
  3066. var retArr = [];
  3067. for (var i = 0; i < sourceQuads.length; i++) {
  3068. retArr.push(cc.V3F_C4B_T2F_QuadCopy(sourceQuads[i]));
  3069. }
  3070. return retArr;
  3071. };
  3072. cc.V2F_C4B_T2F = function (vertices, colors, texCoords, arrayBuffer, offset) {
  3073. this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.V2F_C4B_T2F.BYTES_PER_ELEMENT);
  3074. this._offset = offset || 0;
  3075. var locArrayBuffer = this._arrayBuffer, locOffset = this._offset;
  3076. this._vertices = vertices ? new cc.Vertex2F(vertices.x, vertices.y, locArrayBuffer, locOffset) :
  3077. new cc.Vertex2F(0, 0, locArrayBuffer, locOffset);
  3078. locOffset += cc.Vertex2F.BYTES_PER_ELEMENT;
  3079. this._colors = colors ? cc.color(colors.r, colors.g, colors.b, colors.a, locArrayBuffer, locOffset) :
  3080. cc.color(0, 0, 0, 0, locArrayBuffer, locOffset);
  3081. locOffset += cc.Color.BYTES_PER_ELEMENT;
  3082. this._texCoords = texCoords ? new cc.Tex2F(texCoords.u, texCoords.v, locArrayBuffer, locOffset) :
  3083. new cc.Tex2F(0, 0, locArrayBuffer, locOffset);
  3084. };
  3085. cc.V2F_C4B_T2F.BYTES_PER_ELEMENT = 20;
  3086. _p = cc.V2F_C4B_T2F.prototype;
  3087. _p._getVertices = function () {
  3088. return this._vertices;
  3089. };
  3090. _p._setVertices = function (verticesValue) {
  3091. this._vertices._view[0] = verticesValue.x;
  3092. this._vertices._view[1] = verticesValue.y;
  3093. };
  3094. _p._getColor = function () {
  3095. return this._colors;
  3096. };
  3097. _p._setColor = function (colorValue) {
  3098. var locColors = this._colors;
  3099. locColors._view[0] = colorValue.r;
  3100. locColors._view[1] = colorValue.g;
  3101. locColors._view[2] = colorValue.b;
  3102. locColors._view[3] = colorValue.a;
  3103. };
  3104. _p._getTexCoords = function () {
  3105. return this._texCoords;
  3106. };
  3107. _p._setTexCoords = function (texValue) {
  3108. this._texCoords._view[0] = texValue.u;
  3109. this._texCoords._view[1] = texValue.v;
  3110. };
  3111. _p.vertices;
  3112. cc.defineGetterSetter(_p, "vertices", _p._getVertices, _p._setVertices);
  3113. _p.colors;
  3114. cc.defineGetterSetter(_p, "colors", _p._getColor, _p._setColor);
  3115. _p.texCoords;
  3116. cc.defineGetterSetter(_p, "texCoords", _p._getTexCoords, _p._setTexCoords);
  3117. cc.V2F_C4B_T2F_Triangle = function (a, b, c, arrayBuffer, offset) {
  3118. this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT);
  3119. this._offset = offset || 0;
  3120. var locArrayBuffer = this._arrayBuffer, locOffset = this._offset, locElementLen = cc.V2F_C4B_T2F.BYTES_PER_ELEMENT;
  3121. this._a = a ? new cc.V2F_C4B_T2F(a.vertices, a.colors, a.texCoords, locArrayBuffer, locOffset) :
  3122. new cc.V2F_C4B_T2F(null, null, null, locArrayBuffer, locOffset);
  3123. locOffset += locElementLen;
  3124. this._b = b ? new cc.V2F_C4B_T2F(b.vertices, b.colors, b.texCoords, locArrayBuffer, locOffset) :
  3125. new cc.V2F_C4B_T2F(null, null, null, locArrayBuffer, locOffset);
  3126. locOffset += locElementLen;
  3127. this._c = c ? new cc.V2F_C4B_T2F(c.vertices, c.colors, c.texCoords, locArrayBuffer, locOffset) :
  3128. new cc.V2F_C4B_T2F(null, null, null, locArrayBuffer, locOffset);
  3129. };
  3130. cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT = 60;
  3131. _p = cc.V2F_C4B_T2F_Triangle.prototype;
  3132. _p._getA = function () {
  3133. return this._a;
  3134. };
  3135. _p._setA = function (aValue) {
  3136. var locA = this._a;
  3137. locA.vertices = aValue.vertices;
  3138. locA.colors = aValue.colors;
  3139. locA.texCoords = aValue.texCoords;
  3140. };
  3141. _p._getB = function () {
  3142. return this._b;
  3143. };
  3144. _p._setB = function (bValue) {
  3145. var locB = this._b;
  3146. locB.vertices = bValue.vertices;
  3147. locB.colors = bValue.colors;
  3148. locB.texCoords = bValue.texCoords;
  3149. };
  3150. _p._getC = function () {
  3151. return this._c;
  3152. };
  3153. _p._setC = function (cValue) {
  3154. var locC = this._c;
  3155. locC.vertices = cValue.vertices;
  3156. locC.colors = cValue.colors;
  3157. locC.texCoords = cValue.texCoords;
  3158. };
  3159. _p.a;
  3160. cc.defineGetterSetter(_p, "a", _p._getA, _p._setA);
  3161. _p.b;
  3162. cc.defineGetterSetter(_p, "b", _p._getB, _p._setB);
  3163. _p.c;
  3164. cc.defineGetterSetter(_p, "c", _p._getC, _p._setC);
  3165. cc.vertex2 = function (x, y) {
  3166. return new cc.Vertex2F(x, y);
  3167. };
  3168. cc.vertex3 = function (x, y, z) {
  3169. return new cc.Vertex3F(x, y, z);
  3170. };
  3171. cc.tex2 = function (u, v) {
  3172. return new cc.Tex2F(u, v);
  3173. };
  3174. cc.BlendFunc = function (src1, dst1) {
  3175. this.src = src1;
  3176. this.dst = dst1;
  3177. };
  3178. cc.blendFuncDisable = function () {
  3179. return new cc.BlendFunc(cc.ONE, cc.ZERO);
  3180. };
  3181. cc.hexToColor = function (hex) {
  3182. hex = hex.replace(/^#?/, "0x");
  3183. var c = parseInt(hex);
  3184. var r = c >> 16;
  3185. var g = (c >> 8) % 256;
  3186. var b = c % 256;
  3187. return cc.color(r, g, b);
  3188. };
  3189. cc.colorToHex = function (color) {
  3190. var hR = color.r.toString(16), hG = color.g.toString(16), hB = color.b.toString(16);
  3191. return "#" + (color.r < 16 ? ("0" + hR) : hR) + (color.g < 16 ? ("0" + hG) : hG) + (color.b < 16 ? ("0" + hB) : hB);
  3192. };
  3193. cc.TEXT_ALIGNMENT_LEFT = 0;
  3194. cc.TEXT_ALIGNMENT_CENTER = 1;
  3195. cc.TEXT_ALIGNMENT_RIGHT = 2;
  3196. cc.VERTICAL_TEXT_ALIGNMENT_TOP = 0;
  3197. cc.VERTICAL_TEXT_ALIGNMENT_CENTER = 1;
  3198. cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM = 2;
  3199. cc._Dictionary = cc.Class.extend({
  3200. _keyMapTb: null,
  3201. _valueMapTb: null,
  3202. __currId: 0,
  3203. ctor: function () {
  3204. this._keyMapTb = {};
  3205. this._valueMapTb = {};
  3206. this.__currId = 2 << (0 | (Math.random() * 10));
  3207. },
  3208. __getKey: function () {
  3209. this.__currId++;
  3210. return "key_" + this.__currId;
  3211. },
  3212. setObject: function (value, key) {
  3213. if (key == null)
  3214. return;
  3215. var keyId = this.__getKey();
  3216. this._keyMapTb[keyId] = key;
  3217. this._valueMapTb[keyId] = value;
  3218. },
  3219. objectForKey: function (key) {
  3220. if (key == null)
  3221. return null;
  3222. var locKeyMapTb = this._keyMapTb;
  3223. for (var keyId in locKeyMapTb) {
  3224. if (locKeyMapTb[keyId] === key)
  3225. return this._valueMapTb[keyId];
  3226. }
  3227. return null;
  3228. },
  3229. valueForKey: function (key) {
  3230. return this.objectForKey(key);
  3231. },
  3232. removeObjectForKey: function (key) {
  3233. if (key == null)
  3234. return;
  3235. var locKeyMapTb = this._keyMapTb;
  3236. for (var keyId in locKeyMapTb) {
  3237. if (locKeyMapTb[keyId] === key) {
  3238. delete this._valueMapTb[keyId];
  3239. delete locKeyMapTb[keyId];
  3240. return;
  3241. }
  3242. }
  3243. },
  3244. removeObjectsForKeys: function (keys) {
  3245. if (keys == null)
  3246. return;
  3247. for (var i = 0; i < keys.length; i++)
  3248. this.removeObjectForKey(keys[i]);
  3249. },
  3250. allKeys: function () {
  3251. var keyArr = [], locKeyMapTb = this._keyMapTb;
  3252. for (var key in locKeyMapTb)
  3253. keyArr.push(locKeyMapTb[key]);
  3254. return keyArr;
  3255. },
  3256. removeAllObjects: function () {
  3257. this._keyMapTb = {};
  3258. this._valueMapTb = {};
  3259. },
  3260. count: function () {
  3261. return this.allKeys().length;
  3262. }
  3263. });
  3264. cc.FontDefinition = function (properties) {
  3265. var _t = this;
  3266. _t.fontName = "Arial";
  3267. _t.fontSize = 12;
  3268. _t.textAlign = cc.TEXT_ALIGNMENT_CENTER;
  3269. _t.verticalAlign = cc.VERTICAL_TEXT_ALIGNMENT_TOP;
  3270. _t.fillStyle = cc.color(255, 255, 255, 255);
  3271. _t.boundingWidth = 0;
  3272. _t.boundingHeight = 0;
  3273. _t.strokeEnabled = false;
  3274. _t.strokeStyle = cc.color(255, 255, 255, 255);
  3275. _t.lineWidth = 1;
  3276. _t.lineHeight = "normal";
  3277. _t.fontStyle = "normal";
  3278. _t.fontWeight = "normal";
  3279. _t.shadowEnabled = false;
  3280. _t.shadowOffsetX = 0;
  3281. _t.shadowOffsetY = 0;
  3282. _t.shadowBlur = 0;
  3283. _t.shadowOpacity = 1.0;
  3284. if(properties && properties instanceof Object){
  3285. for(var key in properties){
  3286. _t[key] = properties[key];
  3287. }
  3288. }
  3289. };
  3290. cc.FontDefinition.prototype._getCanvasFontStr = function(){
  3291. var lineHeight = !this.lineHeight.charAt ? this.lineHeight+"px" : this.lineHeight;
  3292. return this.fontStyle + " " + this.fontWeight + " " + this.fontSize + "px/"+lineHeight+" '" + this.fontName + "'";
  3293. };
  3294. cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
  3295. if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) {
  3296. cc.assert(cc.isFunction(cc._tmp.PrototypeColor), cc._LogInfos.MissingFile, "CCTypesPropertyDefine.js");
  3297. cc._tmp.PrototypeColor();
  3298. delete cc._tmp.PrototypeColor;
  3299. }
  3300. });
  3301. cc.Touches = [];
  3302. cc.TouchesIntergerDict = {};
  3303. cc.DENSITYDPI_DEVICE = "device-dpi";
  3304. cc.DENSITYDPI_HIGH = "high-dpi";
  3305. cc.DENSITYDPI_MEDIUM = "medium-dpi";
  3306. cc.DENSITYDPI_LOW = "low-dpi";
  3307. var __BrowserGetter = {
  3308. init: function(){
  3309. this.html = document.getElementsByTagName("html")[0];
  3310. },
  3311. availWidth: function(frame){
  3312. if(!frame || frame === this.html)
  3313. return window.innerWidth;
  3314. else
  3315. return frame.clientWidth;
  3316. },
  3317. availHeight: function(frame){
  3318. if(!frame || frame === this.html)
  3319. return window.innerHeight;
  3320. else
  3321. return frame.clientHeight;
  3322. },
  3323. meta: {
  3324. "width": "device-width"
  3325. },
  3326. adaptationType: cc.sys.browserType
  3327. };
  3328. if(window.navigator.userAgent.indexOf("OS 8_1_") > -1)
  3329. __BrowserGetter.adaptationType = cc.sys.BROWSER_TYPE_MIUI;
  3330. if(cc.sys.os === cc.sys.OS_IOS)
  3331. __BrowserGetter.adaptationType = cc.sys.BROWSER_TYPE_SAFARI;
  3332. switch(__BrowserGetter.adaptationType){
  3333. case cc.sys.BROWSER_TYPE_SAFARI:
  3334. __BrowserGetter.meta["minimal-ui"] = "true";
  3335. __BrowserGetter.availWidth = function(frame){
  3336. return frame.clientWidth;
  3337. };
  3338. __BrowserGetter.availHeight = function(frame){
  3339. return frame.clientHeight;
  3340. };
  3341. break;
  3342. case cc.sys.BROWSER_TYPE_CHROME:
  3343. __BrowserGetter.__defineGetter__("target-densitydpi", function(){
  3344. return cc.view._targetDensityDPI;
  3345. });
  3346. case cc.sys.BROWSER_TYPE_SOUGOU:
  3347. case cc.sys.BROWSER_TYPE_UC:
  3348. __BrowserGetter.availWidth = function(frame){
  3349. return frame.clientWidth;
  3350. };
  3351. __BrowserGetter.availHeight = function(frame){
  3352. return frame.clientHeight;
  3353. };
  3354. break;
  3355. case cc.sys.BROWSER_TYPE_MIUI:
  3356. __BrowserGetter.init = function(view){
  3357. if(view.__resizeWithBrowserSize) return;
  3358. var resize = function(){
  3359. view.setDesignResolutionSize(
  3360. view._designResolutionSize.width,
  3361. view._designResolutionSize.height,
  3362. view._resolutionPolicy
  3363. );
  3364. window.removeEventListener("resize", resize, false);
  3365. };
  3366. window.addEventListener("resize", resize, false);
  3367. };
  3368. break;
  3369. }
  3370. var _scissorRect = cc.rect();
  3371. cc.EGLView = cc.Class.extend({
  3372. _delegate: null,
  3373. _frameSize: null,
  3374. _designResolutionSize: null,
  3375. _originalDesignResolutionSize: null,
  3376. _viewPortRect: null,
  3377. _visibleRect: null,
  3378. _retinaEnabled: false,
  3379. _autoFullScreen: false,
  3380. _devicePixelRatio: 1,
  3381. _viewName: "",
  3382. _resizeCallback: null,
  3383. _scaleX: 1,
  3384. _originalScaleX: 1,
  3385. _scaleY: 1,
  3386. _originalScaleY: 1,
  3387. _isRotated: false,
  3388. _orientation: 3,
  3389. _resolutionPolicy: null,
  3390. _rpExactFit: null,
  3391. _rpShowAll: null,
  3392. _rpNoBorder: null,
  3393. _rpFixedHeight: null,
  3394. _rpFixedWidth: null,
  3395. _initialized: false,
  3396. _contentTranslateLeftTop: null,
  3397. _frame: null,
  3398. _frameZoomFactor: 1.0,
  3399. __resizeWithBrowserSize: false,
  3400. _isAdjustViewPort: true,
  3401. _targetDensityDPI: null,
  3402. ctor: function () {
  3403. var _t = this, d = document, _strategyer = cc.ContainerStrategy, _strategy = cc.ContentStrategy;
  3404. __BrowserGetter.init(this);
  3405. _t._frame = (cc.container.parentNode === d.body) ? d.documentElement : cc.container.parentNode;
  3406. _t._frameSize = cc.size(0, 0);
  3407. _t._initFrameSize();
  3408. var w = cc._canvas.width, h = cc._canvas.height;
  3409. _t._designResolutionSize = cc.size(w, h);
  3410. _t._originalDesignResolutionSize = cc.size(w, h);
  3411. _t._viewPortRect = cc.rect(0, 0, w, h);
  3412. _t._visibleRect = cc.rect(0, 0, w, h);
  3413. _t._contentTranslateLeftTop = {left: 0, top: 0};
  3414. _t._viewName = "Cocos2dHTML5";
  3415. var sys = cc.sys;
  3416. _t.enableRetina(sys.os === sys.OS_IOS || sys.os === sys.OS_OSX);
  3417. _t.enableAutoFullScreen(sys.isMobile && sys.browserType !== sys.BROWSER_TYPE_BAIDU);
  3418. cc.visibleRect && cc.visibleRect.init(_t._visibleRect);
  3419. _t._rpExactFit = new cc.ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.EXACT_FIT);
  3420. _t._rpShowAll = new cc.ResolutionPolicy(_strategyer.PROPORTION_TO_FRAME, _strategy.SHOW_ALL);
  3421. _t._rpNoBorder = new cc.ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.NO_BORDER);
  3422. _t._rpFixedHeight = new cc.ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.FIXED_HEIGHT);
  3423. _t._rpFixedWidth = new cc.ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.FIXED_WIDTH);
  3424. _t._targetDensityDPI = cc.DENSITYDPI_HIGH;
  3425. },
  3426. _resizeEvent: function () {
  3427. var view;
  3428. if (this.setDesignResolutionSize) {
  3429. view = this;
  3430. } else {
  3431. view = cc.view;
  3432. }
  3433. var prevFrameW = view._frameSize.width, prevFrameH = view._frameSize.height, prevRotated = view._isRotated;
  3434. view._initFrameSize();
  3435. if (view._isRotated === prevRotated && view._frameSize.width === prevFrameW && view._frameSize.height === prevFrameH)
  3436. return;
  3437. if (view._resizeCallback) {
  3438. view._resizeCallback.call();
  3439. }
  3440. var width = view._originalDesignResolutionSize.width;
  3441. var height = view._originalDesignResolutionSize.height;
  3442. if (width > 0) {
  3443. view.setDesignResolutionSize(width, height, view._resolutionPolicy);
  3444. }
  3445. },
  3446. setTargetDensityDPI: function(densityDPI){
  3447. this._targetDensityDPI = densityDPI;
  3448. this._adjustViewportMeta();
  3449. },
  3450. getTargetDensityDPI: function(){
  3451. return this._targetDensityDPI;
  3452. },
  3453. resizeWithBrowserSize: function (enabled) {
  3454. if (enabled) {
  3455. if (!this.__resizeWithBrowserSize) {
  3456. this.__resizeWithBrowserSize = true;
  3457. window.addEventListener('resize', this._resizeEvent);
  3458. window.addEventListener('orientationchange', this._resizeEvent);
  3459. }
  3460. } else {
  3461. if (this.__resizeWithBrowserSize) {
  3462. this.__resizeWithBrowserSize = false;
  3463. window.removeEventListener('resize', this._resizeEvent);
  3464. window.removeEventListener('orientationchange', this._resizeEvent);
  3465. }
  3466. }
  3467. },
  3468. setResizeCallback: function (callback) {
  3469. if (cc.isFunction(callback) || callback == null) {
  3470. this._resizeCallback = callback;
  3471. }
  3472. },
  3473. setOrientation: function (orientation) {
  3474. orientation = orientation & cc.ORIENTATION_AUTO;
  3475. if (orientation) {
  3476. this._orientation = orientation;
  3477. }
  3478. },
  3479. _initFrameSize: function () {
  3480. var locFrameSize = this._frameSize;
  3481. var w = __BrowserGetter.availWidth(this._frame);
  3482. var h = __BrowserGetter.availHeight(this._frame);
  3483. var isLandscape = w >= h;
  3484. if (!cc.sys.isMobile ||
  3485. (isLandscape && this._orientation & cc.ORIENTATION_LANDSCAPE) ||
  3486. (!isLandscape && this._orientation & cc.ORIENTATION_PORTRAIT)) {
  3487. locFrameSize.width = w;
  3488. locFrameSize.height = h;
  3489. cc.container.style['-webkit-transform'] = 'rotate(0deg)';
  3490. cc.container.style.transform = 'rotate(0deg)';
  3491. this._isRotated = false;
  3492. }
  3493. else {
  3494. locFrameSize.width = h;
  3495. locFrameSize.height = w;
  3496. cc.container.style['-webkit-transform'] = 'rotate(90deg)';
  3497. cc.container.style.transform = 'rotate(90deg)';
  3498. cc.container.style['-webkit-transform-origin'] = '0px 0px 0px';
  3499. cc.container.style.transformOrigin = '0px 0px 0px';
  3500. this._isRotated = true;
  3501. }
  3502. },
  3503. _adjustSizeKeepCanvasSize: function () {
  3504. var designWidth = this._originalDesignResolutionSize.width;
  3505. var designHeight = this._originalDesignResolutionSize.height;
  3506. if (designWidth > 0)
  3507. this.setDesignResolutionSize(designWidth, designHeight, this._resolutionPolicy);
  3508. },
  3509. _setViewportMeta: function (metas, overwrite) {
  3510. var vp = document.getElementById("cocosMetaElement");
  3511. if(vp && overwrite){
  3512. document.head.removeChild(vp);
  3513. }
  3514. var elems = document.getElementsByName("viewport"),
  3515. currentVP = elems ? elems[0] : null,
  3516. content, key, pattern;
  3517. content = currentVP ? currentVP.content : "";
  3518. vp = vp || document.createElement("meta");
  3519. vp.id = "cocosMetaElement";
  3520. vp.name = "viewport";
  3521. vp.content = "";
  3522. for (key in metas) {
  3523. if (content.indexOf(key) == -1) {
  3524. content += "," + key + "=" + metas[key];
  3525. }
  3526. else if (overwrite) {
  3527. pattern = new RegExp(key+"\s*=\s*[^,]+");
  3528. content.replace(pattern, key + "=" + metas[key]);
  3529. }
  3530. }
  3531. if(/^,/.test(content))
  3532. content = content.substr(1);
  3533. vp.content = content;
  3534. if (currentVP)
  3535. currentVP.content = content;
  3536. document.head.appendChild(vp);
  3537. },
  3538. _adjustViewportMeta: function () {
  3539. if (this._isAdjustViewPort) {
  3540. this._setViewportMeta(__BrowserGetter.meta, false);
  3541. this._isAdjustViewPort = false;
  3542. }
  3543. },
  3544. _setScaleXYForRenderTexture: function () {
  3545. var scaleFactor = cc.contentScaleFactor();
  3546. this._scaleX = scaleFactor;
  3547. this._scaleY = scaleFactor;
  3548. },
  3549. _resetScale: function () {
  3550. this._scaleX = this._originalScaleX;
  3551. this._scaleY = this._originalScaleY;
  3552. },
  3553. _adjustSizeToBrowser: function () {
  3554. },
  3555. initialize: function () {
  3556. this._initialized = true;
  3557. },
  3558. adjustViewPort: function (enabled) {
  3559. this._isAdjustViewPort = enabled;
  3560. },
  3561. enableRetina: function(enabled) {
  3562. this._retinaEnabled = enabled ? true : false;
  3563. },
  3564. isRetinaEnabled: function() {
  3565. return this._retinaEnabled;
  3566. },
  3567. enableAutoFullScreen: function(enabled) {
  3568. if (enabled && enabled !== this._autoFullScreen && cc.sys.isMobile && this._frame === document.documentElement) {
  3569. this._autoFullScreen = true;
  3570. cc.screen.autoFullScreen(this._frame);
  3571. }
  3572. else {
  3573. this._autoFullScreen = false;
  3574. }
  3575. },
  3576. isAutoFullScreenEnabled: function() {
  3577. return this._autoFullScreen;
  3578. },
  3579. end: function () {
  3580. },
  3581. isOpenGLReady: function () {
  3582. return (cc.game.canvas && cc._renderContext);
  3583. },
  3584. setFrameZoomFactor: function (zoomFactor) {
  3585. this._frameZoomFactor = zoomFactor;
  3586. this.centerWindow();
  3587. cc.director.setProjection(cc.director.getProjection());
  3588. },
  3589. swapBuffers: function () {
  3590. },
  3591. setIMEKeyboardState: function (isOpen) {
  3592. },
  3593. setContentTranslateLeftTop: function (offsetLeft, offsetTop) {
  3594. this._contentTranslateLeftTop = {left: offsetLeft, top: offsetTop};
  3595. },
  3596. getContentTranslateLeftTop: function () {
  3597. return this._contentTranslateLeftTop;
  3598. },
  3599. getCanvasSize: function () {
  3600. return cc.size(cc._canvas.width, cc._canvas.height);
  3601. },
  3602. getFrameSize: function () {
  3603. return cc.size(this._frameSize.width, this._frameSize.height);
  3604. },
  3605. setFrameSize: function (width, height) {
  3606. this._frameSize.width = width;
  3607. this._frameSize.height = height;
  3608. this._frame.style.width = width + "px";
  3609. this._frame.style.height = height + "px";
  3610. this._resizeEvent();
  3611. cc.director.setProjection(cc.director.getProjection());
  3612. },
  3613. centerWindow: function () {
  3614. },
  3615. getVisibleSize: function () {
  3616. return cc.size(this._visibleRect.width,this._visibleRect.height);
  3617. },
  3618. getVisibleSizeInPixel: function () {
  3619. return cc.size( this._visibleRect.width * this._scaleX,
  3620. this._visibleRect.height * this._scaleY );
  3621. },
  3622. getVisibleOrigin: function () {
  3623. return cc.p(this._visibleRect.x,this._visibleRect.y);
  3624. },
  3625. getVisibleOriginInPixel: function () {
  3626. return cc.p(this._visibleRect.x * this._scaleX,
  3627. this._visibleRect.y * this._scaleY);
  3628. },
  3629. canSetContentScaleFactor: function () {
  3630. return true;
  3631. },
  3632. getResolutionPolicy: function () {
  3633. return this._resolutionPolicy;
  3634. },
  3635. setResolutionPolicy: function (resolutionPolicy) {
  3636. var _t = this;
  3637. if (resolutionPolicy instanceof cc.ResolutionPolicy) {
  3638. _t._resolutionPolicy = resolutionPolicy;
  3639. }
  3640. else {
  3641. var _locPolicy = cc.ResolutionPolicy;
  3642. if(resolutionPolicy === _locPolicy.EXACT_FIT)
  3643. _t._resolutionPolicy = _t._rpExactFit;
  3644. if(resolutionPolicy === _locPolicy.SHOW_ALL)
  3645. _t._resolutionPolicy = _t._rpShowAll;
  3646. if(resolutionPolicy === _locPolicy.NO_BORDER)
  3647. _t._resolutionPolicy = _t._rpNoBorder;
  3648. if(resolutionPolicy === _locPolicy.FIXED_HEIGHT)
  3649. _t._resolutionPolicy = _t._rpFixedHeight;
  3650. if(resolutionPolicy === _locPolicy.FIXED_WIDTH)
  3651. _t._resolutionPolicy = _t._rpFixedWidth;
  3652. }
  3653. },
  3654. setDesignResolutionSize: function (width, height, resolutionPolicy) {
  3655. if( !(width > 0 || height > 0) ){
  3656. cc.log(cc._LogInfos.EGLView_setDesignResolutionSize);
  3657. return;
  3658. }
  3659. this.setResolutionPolicy(resolutionPolicy);
  3660. var policy = this._resolutionPolicy;
  3661. if (!policy){
  3662. cc.log(cc._LogInfos.EGLView_setDesignResolutionSize_2);
  3663. return;
  3664. }
  3665. policy.preApply(this);
  3666. if(cc.sys.isMobile)
  3667. this._adjustViewportMeta();
  3668. this._initFrameSize();
  3669. this._originalDesignResolutionSize.width = this._designResolutionSize.width = width;
  3670. this._originalDesignResolutionSize.height = this._designResolutionSize.height = height;
  3671. var result = policy.apply(this, this._designResolutionSize);
  3672. if(result.scale && result.scale.length === 2){
  3673. this._scaleX = result.scale[0];
  3674. this._scaleY = result.scale[1];
  3675. }
  3676. if(result.viewport){
  3677. var vp = this._viewPortRect,
  3678. vb = this._visibleRect,
  3679. rv = result.viewport;
  3680. vp.x = rv.x;
  3681. vp.y = rv.y;
  3682. vp.width = rv.width;
  3683. vp.height = rv.height;
  3684. vb.x = -vp.x / this._scaleX;
  3685. vb.y = -vp.y / this._scaleY;
  3686. vb.width = cc._canvas.width / this._scaleX;
  3687. vb.height = cc._canvas.height / this._scaleY;
  3688. cc._renderContext.setOffset && cc._renderContext.setOffset(vp.x, -vp.y);
  3689. }
  3690. var director = cc.director;
  3691. director._winSizeInPoints.width = this._designResolutionSize.width;
  3692. director._winSizeInPoints.height = this._designResolutionSize.height;
  3693. policy.postApply(this);
  3694. cc.winSize.width = director._winSizeInPoints.width;
  3695. cc.winSize.height = director._winSizeInPoints.height;
  3696. if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) {
  3697. director.setGLDefaultValues();
  3698. }
  3699. this._originalScaleX = this._scaleX;
  3700. this._originalScaleY = this._scaleY;
  3701. if (cc.DOM)
  3702. cc.DOM._resetEGLViewDiv();
  3703. cc.visibleRect && cc.visibleRect.init(this._visibleRect);
  3704. },
  3705. getDesignResolutionSize: function () {
  3706. return cc.size(this._designResolutionSize.width, this._designResolutionSize.height);
  3707. },
  3708. setRealPixelResolution: function (width, height, resolutionPolicy) {
  3709. this._setViewportMeta({"width": width, "target-densitydpi": cc.DENSITYDPI_DEVICE}, true);
  3710. document.body.style.width = width + "px";
  3711. document.body.style.left = "0px";
  3712. document.body.style.top = "0px";
  3713. this.setDesignResolutionSize(width, height, resolutionPolicy);
  3714. },
  3715. setViewPortInPoints: function (x, y, w, h) {
  3716. var locFrameZoomFactor = this._frameZoomFactor, locScaleX = this._scaleX, locScaleY = this._scaleY;
  3717. cc._renderContext.viewport((x * locScaleX * locFrameZoomFactor + this._viewPortRect.x * locFrameZoomFactor),
  3718. (y * locScaleY * locFrameZoomFactor + this._viewPortRect.y * locFrameZoomFactor),
  3719. (w * locScaleX * locFrameZoomFactor),
  3720. (h * locScaleY * locFrameZoomFactor));
  3721. },
  3722. setScissorInPoints: function (x, y, w, h) {
  3723. var zoomFactor = this._frameZoomFactor, scaleX = this._scaleX, scaleY = this._scaleY;
  3724. _scissorRect.x = x;
  3725. _scissorRect.y = y;
  3726. _scissorRect.width = w;
  3727. _scissorRect.height = h;
  3728. cc._renderContext.scissor(x * scaleX * zoomFactor + this._viewPortRect.x * zoomFactor,
  3729. y * scaleY * zoomFactor + this._viewPortRect.y * zoomFactor,
  3730. w * scaleX * zoomFactor,
  3731. h * scaleY * zoomFactor);
  3732. },
  3733. isScissorEnabled: function () {
  3734. return cc._renderContext.isEnabled(gl.SCISSOR_TEST);
  3735. },
  3736. getScissorRect: function () {
  3737. return cc.rect(_scissorRect);
  3738. },
  3739. setViewName: function (viewName) {
  3740. if (viewName != null && viewName.length > 0) {
  3741. this._viewName = viewName;
  3742. }
  3743. },
  3744. getViewName: function () {
  3745. return this._viewName;
  3746. },
  3747. getViewPortRect: function () {
  3748. return this._viewPortRect;
  3749. },
  3750. getScaleX: function () {
  3751. return this._scaleX;
  3752. },
  3753. getScaleY: function () {
  3754. return this._scaleY;
  3755. },
  3756. getDevicePixelRatio: function() {
  3757. return this._devicePixelRatio;
  3758. },
  3759. convertToLocationInView: function (tx, ty, relatedPos) {
  3760. var x = this._devicePixelRatio * (tx - relatedPos.left);
  3761. var y = this._devicePixelRatio * (relatedPos.top + relatedPos.height - ty);
  3762. return this._isRotated ? {x: this._viewPortRect.width - y, y: x} : {x: x, y: y};
  3763. },
  3764. _convertMouseToLocationInView: function(point, relatedPos) {
  3765. var locViewPortRect = this._viewPortRect, _t = this;
  3766. point.x = ((_t._devicePixelRatio * (point.x - relatedPos.left)) - locViewPortRect.x) / _t._scaleX;
  3767. point.y = (_t._devicePixelRatio * (relatedPos.top + relatedPos.height - point.y) - locViewPortRect.y) / _t._scaleY;
  3768. },
  3769. _convertPointWithScale: function (point) {
  3770. var viewport = this._viewPortRect;
  3771. point.x = (point.x - viewport.x) / this._scaleX;
  3772. point.y = (point.y - viewport.y) / this._scaleY;
  3773. },
  3774. _convertTouchesWithScale: function (touches) {
  3775. var viewport = this._viewPortRect, scaleX = this._scaleX, scaleY = this._scaleY,
  3776. selTouch, selPoint, selPrePoint;
  3777. for( var i = 0; i < touches.length; i++){
  3778. selTouch = touches[i];
  3779. selPoint = selTouch._point;
  3780. selPrePoint = selTouch._prevPoint;
  3781. selPoint.x = (selPoint.x - viewport.x) / scaleX;
  3782. selPoint.y = (selPoint.y - viewport.y) / scaleY;
  3783. selPrePoint.x = (selPrePoint.x - viewport.x) / scaleX;
  3784. selPrePoint.y = (selPrePoint.y - viewport.y) / scaleY;
  3785. }
  3786. }
  3787. });
  3788. cc.EGLView._getInstance = function () {
  3789. if (!this._instance) {
  3790. this._instance = this._instance || new cc.EGLView();
  3791. this._instance.initialize();
  3792. }
  3793. return this._instance;
  3794. };
  3795. cc.ContainerStrategy = cc.Class.extend({
  3796. preApply: function (view) {
  3797. },
  3798. apply: function (view, designedResolution) {
  3799. },
  3800. postApply: function (view) {
  3801. },
  3802. _setupContainer: function (view, w, h) {
  3803. var locCanvas = cc.game.canvas, locContainer = cc.game.container;
  3804. locContainer.style.width = locCanvas.style.width = w + 'px';
  3805. locContainer.style.height = locCanvas.style.height = h + 'px';
  3806. var devicePixelRatio = view._devicePixelRatio = 1;
  3807. if (view.isRetinaEnabled())
  3808. devicePixelRatio = view._devicePixelRatio = Math.min(2, window.devicePixelRatio || 1);
  3809. locCanvas.width = w * devicePixelRatio;
  3810. locCanvas.height = h * devicePixelRatio;
  3811. cc._renderContext.resetCache && cc._renderContext.resetCache();
  3812. },
  3813. _fixContainer: function () {
  3814. document.body.insertBefore(cc.container, document.body.firstChild);
  3815. var bs = document.body.style;
  3816. bs.width = window.innerWidth + "px";
  3817. bs.height = window.innerHeight + "px";
  3818. bs.overflow = "hidden";
  3819. var contStyle = cc.container.style;
  3820. contStyle.position = "fixed";
  3821. contStyle.left = contStyle.top = "0px";
  3822. document.body.scrollTop = 0;
  3823. }
  3824. });
  3825. cc.ContentStrategy = cc.Class.extend({
  3826. _result: {
  3827. scale: [1, 1],
  3828. viewport: null
  3829. },
  3830. _buildResult: function (containerW, containerH, contentW, contentH, scaleX, scaleY) {
  3831. Math.abs(containerW - contentW) < 2 && (contentW = containerW);
  3832. Math.abs(containerH - contentH) < 2 && (contentH = containerH);
  3833. var viewport = cc.rect(Math.round((containerW - contentW) / 2),
  3834. Math.round((containerH - contentH) / 2),
  3835. contentW, contentH);
  3836. if (cc._renderType === cc.game.RENDER_TYPE_CANVAS){
  3837. }
  3838. this._result.scale = [scaleX, scaleY];
  3839. this._result.viewport = viewport;
  3840. return this._result;
  3841. },
  3842. preApply: function (view) {
  3843. },
  3844. apply: function (view, designedResolution) {
  3845. return {"scale": [1, 1]};
  3846. },
  3847. postApply: function (view) {
  3848. }
  3849. });
  3850. (function () {
  3851. var EqualToFrame = cc.ContainerStrategy.extend({
  3852. apply: function (view) {
  3853. var frameH = view._frameSize.height, containerStyle = cc.container.style;
  3854. this._setupContainer(view, view._frameSize.width, view._frameSize.height);
  3855. if (view._isRotated) {
  3856. containerStyle.marginLeft = frameH + 'px';
  3857. }
  3858. else {
  3859. containerStyle.margin = '0px';
  3860. }
  3861. }
  3862. });
  3863. var ProportionalToFrame = cc.ContainerStrategy.extend({
  3864. apply: function (view, designedResolution) {
  3865. var frameW = view._frameSize.width, frameH = view._frameSize.height, containerStyle = cc.container.style,
  3866. designW = designedResolution.width, designH = designedResolution.height,
  3867. scaleX = frameW / designW, scaleY = frameH / designH,
  3868. containerW, containerH;
  3869. scaleX < scaleY ? (containerW = frameW, containerH = designH * scaleX) : (containerW = designW * scaleY, containerH = frameH);
  3870. var offx = Math.round((frameW - containerW) / 2);
  3871. var offy = Math.round((frameH - containerH) / 2);
  3872. containerW = frameW - 2 * offx;
  3873. containerH = frameH - 2 * offy;
  3874. this._setupContainer(view, containerW, containerH);
  3875. if (view._isRotated) {
  3876. containerStyle.marginLeft = frameH + 'px';
  3877. }
  3878. else {
  3879. containerStyle.margin = '0px';
  3880. }
  3881. containerStyle.paddingLeft = offx + "px";
  3882. containerStyle.paddingRight = offx + "px";
  3883. containerStyle.paddingTop = offy + "px";
  3884. containerStyle.paddingBottom = offy + "px";
  3885. }
  3886. });
  3887. var EqualToWindow = EqualToFrame.extend({
  3888. preApply: function (view) {
  3889. this._super(view);
  3890. view._frame = document.documentElement;
  3891. },
  3892. apply: function (view) {
  3893. this._super(view);
  3894. this._fixContainer();
  3895. }
  3896. });
  3897. var ProportionalToWindow = ProportionalToFrame.extend({
  3898. preApply: function (view) {
  3899. this._super(view);
  3900. view._frame = document.documentElement;
  3901. },
  3902. apply: function (view, designedResolution) {
  3903. this._super(view, designedResolution);
  3904. this._fixContainer();
  3905. }
  3906. });
  3907. var OriginalContainer = cc.ContainerStrategy.extend({
  3908. apply: function (view) {
  3909. this._setupContainer(view, cc._canvas.width, cc._canvas.height);
  3910. }
  3911. });
  3912. cc.ContainerStrategy.EQUAL_TO_FRAME = new EqualToFrame();
  3913. cc.ContainerStrategy.PROPORTION_TO_FRAME = new ProportionalToFrame();
  3914. cc.ContainerStrategy.ORIGINAL_CONTAINER = new OriginalContainer();
  3915. var ExactFit = cc.ContentStrategy.extend({
  3916. apply: function (view, designedResolution) {
  3917. var containerW = cc._canvas.width, containerH = cc._canvas.height,
  3918. scaleX = containerW / designedResolution.width, scaleY = containerH / designedResolution.height;
  3919. return this._buildResult(containerW, containerH, containerW, containerH, scaleX, scaleY);
  3920. }
  3921. });
  3922. var ShowAll = cc.ContentStrategy.extend({
  3923. apply: function (view, designedResolution) {
  3924. var containerW = cc._canvas.width, containerH = cc._canvas.height,
  3925. designW = designedResolution.width, designH = designedResolution.height,
  3926. scaleX = containerW / designW, scaleY = containerH / designH, scale = 0,
  3927. contentW, contentH;
  3928. scaleX < scaleY ? (scale = scaleX, contentW = containerW, contentH = designH * scale)
  3929. : (scale = scaleY, contentW = designW * scale, contentH = containerH);
  3930. return this._buildResult(containerW, containerH, contentW, contentH, scale, scale);
  3931. }
  3932. });
  3933. var NoBorder = cc.ContentStrategy.extend({
  3934. apply: function (view, designedResolution) {
  3935. var containerW = cc._canvas.width, containerH = cc._canvas.height,
  3936. designW = designedResolution.width, designH = designedResolution.height,
  3937. scaleX = containerW / designW, scaleY = containerH / designH, scale,
  3938. contentW, contentH;
  3939. scaleX < scaleY ? (scale = scaleY, contentW = designW * scale, contentH = containerH)
  3940. : (scale = scaleX, contentW = containerW, contentH = designH * scale);
  3941. return this._buildResult(containerW, containerH, contentW, contentH, scale, scale);
  3942. }
  3943. });
  3944. var FixedHeight = cc.ContentStrategy.extend({
  3945. apply: function (view, designedResolution) {
  3946. var containerW = cc._canvas.width, containerH = cc._canvas.height,
  3947. designH = designedResolution.height, scale = containerH / designH,
  3948. contentW = containerW, contentH = containerH;
  3949. return this._buildResult(containerW, containerH, contentW, contentH, scale, scale);
  3950. },
  3951. postApply: function (view) {
  3952. cc.director._winSizeInPoints = view.getVisibleSize();
  3953. }
  3954. });
  3955. var FixedWidth = cc.ContentStrategy.extend({
  3956. apply: function (view, designedResolution) {
  3957. var containerW = cc._canvas.width, containerH = cc._canvas.height,
  3958. designW = designedResolution.width, scale = containerW / designW,
  3959. contentW = containerW, contentH = containerH;
  3960. return this._buildResult(containerW, containerH, contentW, contentH, scale, scale);
  3961. },
  3962. postApply: function (view) {
  3963. cc.director._winSizeInPoints = view.getVisibleSize();
  3964. }
  3965. });
  3966. cc.ContentStrategy.EXACT_FIT = new ExactFit();
  3967. cc.ContentStrategy.SHOW_ALL = new ShowAll();
  3968. cc.ContentStrategy.NO_BORDER = new NoBorder();
  3969. cc.ContentStrategy.FIXED_HEIGHT = new FixedHeight();
  3970. cc.ContentStrategy.FIXED_WIDTH = new FixedWidth();
  3971. })();
  3972. cc.ResolutionPolicy = cc.Class.extend({
  3973. _containerStrategy: null,
  3974. _contentStrategy: null,
  3975. ctor: function (containerStg, contentStg) {
  3976. this.setContainerStrategy(containerStg);
  3977. this.setContentStrategy(contentStg);
  3978. },
  3979. preApply: function (view) {
  3980. this._containerStrategy.preApply(view);
  3981. this._contentStrategy.preApply(view);
  3982. },
  3983. apply: function (view, designedResolution) {
  3984. this._containerStrategy.apply(view, designedResolution);
  3985. return this._contentStrategy.apply(view, designedResolution);
  3986. },
  3987. postApply: function (view) {
  3988. this._containerStrategy.postApply(view);
  3989. this._contentStrategy.postApply(view);
  3990. },
  3991. setContainerStrategy: function (containerStg) {
  3992. if (containerStg instanceof cc.ContainerStrategy)
  3993. this._containerStrategy = containerStg;
  3994. },
  3995. setContentStrategy: function (contentStg) {
  3996. if (contentStg instanceof cc.ContentStrategy)
  3997. this._contentStrategy = contentStg;
  3998. }
  3999. });
  4000. cc.ResolutionPolicy.EXACT_FIT = 0;
  4001. cc.ResolutionPolicy.NO_BORDER = 1;
  4002. cc.ResolutionPolicy.SHOW_ALL = 2;
  4003. cc.ResolutionPolicy.FIXED_HEIGHT = 3;
  4004. cc.ResolutionPolicy.FIXED_WIDTH = 4;
  4005. cc.ResolutionPolicy.UNKNOWN = 5;
  4006. cc.screen = {
  4007. _supportsFullScreen: false,
  4008. _preOnFullScreenChange: null,
  4009. _touchEvent: "",
  4010. _fn: null,
  4011. _fnMap: [
  4012. [
  4013. 'requestFullscreen',
  4014. 'exitFullscreen',
  4015. 'fullscreenchange',
  4016. 'fullscreenEnabled',
  4017. 'fullscreenElement'
  4018. ],
  4019. [
  4020. 'requestFullScreen',
  4021. 'exitFullScreen',
  4022. 'fullScreenchange',
  4023. 'fullScreenEnabled',
  4024. 'fullScreenElement'
  4025. ],
  4026. [
  4027. 'webkitRequestFullScreen',
  4028. 'webkitCancelFullScreen',
  4029. 'webkitfullscreenchange',
  4030. 'webkitIsFullScreen',
  4031. 'webkitCurrentFullScreenElement'
  4032. ],
  4033. [
  4034. 'mozRequestFullScreen',
  4035. 'mozCancelFullScreen',
  4036. 'mozfullscreenchange',
  4037. 'mozFullScreen',
  4038. 'mozFullScreenElement'
  4039. ],
  4040. [
  4041. 'msRequestFullscreen',
  4042. 'msExitFullscreen',
  4043. 'MSFullscreenChange',
  4044. 'msFullscreenEnabled',
  4045. 'msFullscreenElement'
  4046. ]
  4047. ],
  4048. init: function () {
  4049. this._fn = {};
  4050. var i, val, map = this._fnMap, valL;
  4051. for (i = 0, l = map.length; i < l; i++) {
  4052. val = map[i];
  4053. if (val && val[1] in document) {
  4054. for (i = 0, valL = val.length; i < valL; i++) {
  4055. this._fn[map[0][i]] = val[i];
  4056. }
  4057. break;
  4058. }
  4059. }
  4060. this._supportsFullScreen = (typeof this._fn.requestFullscreen !== 'undefined');
  4061. this._touchEvent = ('ontouchstart' in window) ? 'touchstart' : 'mousedown';
  4062. },
  4063. fullScreen: function () {
  4064. if(!this._supportsFullScreen) return false;
  4065. else if( document[this._fn.fullscreenElement] === undefined || document[this._fn.fullscreenElement] === null )
  4066. return false;
  4067. else
  4068. return true;
  4069. },
  4070. requestFullScreen: function (element, onFullScreenChange) {
  4071. if (!this._supportsFullScreen) {
  4072. return;
  4073. }
  4074. element = element || document.documentElement;
  4075. if (onFullScreenChange) {
  4076. var eventName = this._fn.fullscreenchange;
  4077. if (this._preOnFullScreenChange) {
  4078. document.removeEventListener(eventName, this._preOnFullScreenChange);
  4079. }
  4080. this._preOnFullScreenChange = onFullScreenChange;
  4081. document.addEventListener(eventName, onFullScreenChange, false);
  4082. }
  4083. return element[this._fn.requestFullscreen]();
  4084. },
  4085. exitFullScreen: function () {
  4086. return this._supportsFullScreen ? document[this._fn.exitFullscreen]() : true;
  4087. },
  4088. autoFullScreen: function (element, onFullScreenChange) {
  4089. element = element || document.body;
  4090. var touchTarget = cc.game.canvas || element;
  4091. var theScreen = this;
  4092. function callback() {
  4093. touchTarget.removeEventListener(theScreen._touchEvent, callback);
  4094. theScreen.requestFullScreen(element, onFullScreenChange);
  4095. }
  4096. this.requestFullScreen(element, onFullScreenChange);
  4097. touchTarget.addEventListener(this._touchEvent, callback);
  4098. }
  4099. };
  4100. cc.screen.init();
  4101. cc.visibleRect = {
  4102. topLeft:cc.p(0,0),
  4103. topRight:cc.p(0,0),
  4104. top:cc.p(0,0),
  4105. bottomLeft:cc.p(0,0),
  4106. bottomRight:cc.p(0,0),
  4107. bottom:cc.p(0,0),
  4108. center:cc.p(0,0),
  4109. left:cc.p(0,0),
  4110. right:cc.p(0,0),
  4111. width:0,
  4112. height:0,
  4113. init:function(visibleRect){
  4114. var w = this.width = visibleRect.width;
  4115. var h = this.height = visibleRect.height;
  4116. var l = visibleRect.x,
  4117. b = visibleRect.y,
  4118. t = b + h,
  4119. r = l + w;
  4120. this.topLeft.x = l;
  4121. this.topLeft.y = t;
  4122. this.topRight.x = r;
  4123. this.topRight.y = t;
  4124. this.top.x = l + w/2;
  4125. this.top.y = t;
  4126. this.bottomLeft.x = l;
  4127. this.bottomLeft.y = b;
  4128. this.bottomRight.x = r;
  4129. this.bottomRight.y = b;
  4130. this.bottom.x = l + w/2;
  4131. this.bottom.y = b;
  4132. this.center.x = l + w/2;
  4133. this.center.y = b + h/2;
  4134. this.left.x = l;
  4135. this.left.y = b + h/2;
  4136. this.right.x = r;
  4137. this.right.y = b + h/2;
  4138. }
  4139. };
  4140. cc.UIInterfaceOrientationLandscapeLeft = -90;
  4141. cc.UIInterfaceOrientationLandscapeRight = 90;
  4142. cc.UIInterfaceOrientationPortraitUpsideDown = 180;
  4143. cc.UIInterfaceOrientationPortrait = 0;
  4144. cc.inputManager = {
  4145. _mousePressed: false,
  4146. _isRegisterEvent: false,
  4147. _preTouchPoint: cc.p(0,0),
  4148. _prevMousePoint: cc.p(0,0),
  4149. _preTouchPool: [],
  4150. _preTouchPoolPointer: 0,
  4151. _touches: [],
  4152. _touchesIntegerDict:{},
  4153. _indexBitsUsed: 0,
  4154. _maxTouches: 5,
  4155. _accelEnabled: false,
  4156. _accelInterval: 1/30,
  4157. _accelMinus: 1,
  4158. _accelCurTime: 0,
  4159. _acceleration: null,
  4160. _accelDeviceEvent: null,
  4161. _getUnUsedIndex: function () {
  4162. var temp = this._indexBitsUsed;
  4163. for (var i = 0; i < this._maxTouches; i++) {
  4164. if (!(temp & 0x00000001)) {
  4165. this._indexBitsUsed |= (1 << i);
  4166. return i;
  4167. }
  4168. temp >>= 1;
  4169. }
  4170. return -1;
  4171. },
  4172. _removeUsedIndexBit: function (index) {
  4173. if (index < 0 || index >= this._maxTouches)
  4174. return;
  4175. var temp = 1 << index;
  4176. temp = ~temp;
  4177. this._indexBitsUsed &= temp;
  4178. },
  4179. _glView: null,
  4180. handleTouchesBegin: function (touches) {
  4181. var selTouch, index, curTouch, touchID, handleTouches = [], locTouchIntDict = this._touchesIntegerDict;
  4182. for(var i = 0, len = touches.length; i< len; i ++){
  4183. selTouch = touches[i];
  4184. touchID = selTouch.getID();
  4185. index = locTouchIntDict[touchID];
  4186. if(index == null){
  4187. var unusedIndex = this._getUnUsedIndex();
  4188. if (unusedIndex === -1) {
  4189. cc.log(cc._LogInfos.inputManager_handleTouchesBegin, unusedIndex);
  4190. continue;
  4191. }
  4192. curTouch = this._touches[unusedIndex] = new cc.Touch(selTouch._point.x, selTouch._point.y, selTouch.getID());
  4193. curTouch._setPrevPoint(selTouch._prevPoint);
  4194. locTouchIntDict[touchID] = unusedIndex;
  4195. handleTouches.push(curTouch);
  4196. }
  4197. }
  4198. if(handleTouches.length > 0){
  4199. this._glView._convertTouchesWithScale(handleTouches);
  4200. var touchEvent = new cc.EventTouch(handleTouches);
  4201. touchEvent._eventCode = cc.EventTouch.EventCode.BEGAN;
  4202. cc.eventManager.dispatchEvent(touchEvent);
  4203. }
  4204. },
  4205. handleTouchesMove: function(touches){
  4206. var selTouch, index, touchID, handleTouches = [], locTouches = this._touches;
  4207. for(var i = 0, len = touches.length; i< len; i ++){
  4208. selTouch = touches[i];
  4209. touchID = selTouch.getID();
  4210. index = this._touchesIntegerDict[touchID];
  4211. if(index == null){
  4212. continue;
  4213. }
  4214. if(locTouches[index]){
  4215. locTouches[index]._setPoint(selTouch._point);
  4216. locTouches[index]._setPrevPoint(selTouch._prevPoint);
  4217. handleTouches.push(locTouches[index]);
  4218. }
  4219. }
  4220. if(handleTouches.length > 0){
  4221. this._glView._convertTouchesWithScale(handleTouches);
  4222. var touchEvent = new cc.EventTouch(handleTouches);
  4223. touchEvent._eventCode = cc.EventTouch.EventCode.MOVED;
  4224. cc.eventManager.dispatchEvent(touchEvent);
  4225. }
  4226. },
  4227. handleTouchesEnd: function(touches){
  4228. var handleTouches = this.getSetOfTouchesEndOrCancel(touches);
  4229. if(handleTouches.length > 0) {
  4230. this._glView._convertTouchesWithScale(handleTouches);
  4231. var touchEvent = new cc.EventTouch(handleTouches);
  4232. touchEvent._eventCode = cc.EventTouch.EventCode.ENDED;
  4233. cc.eventManager.dispatchEvent(touchEvent);
  4234. }
  4235. },
  4236. handleTouchesCancel: function(touches){
  4237. var handleTouches = this.getSetOfTouchesEndOrCancel(touches);
  4238. if(handleTouches.length > 0) {
  4239. this._glView._convertTouchesWithScale(handleTouches);
  4240. var touchEvent = new cc.EventTouch(handleTouches);
  4241. touchEvent._eventCode = cc.EventTouch.EventCode.CANCELLED;
  4242. cc.eventManager.dispatchEvent(touchEvent);
  4243. }
  4244. },
  4245. getSetOfTouchesEndOrCancel: function(touches) {
  4246. var selTouch, index, touchID, handleTouches = [], locTouches = this._touches, locTouchesIntDict = this._touchesIntegerDict;
  4247. for(var i = 0, len = touches.length; i< len; i ++){
  4248. selTouch = touches[i];
  4249. touchID = selTouch.getID();
  4250. index = locTouchesIntDict[touchID];
  4251. if(index == null){
  4252. continue;
  4253. }
  4254. if(locTouches[index]){
  4255. locTouches[index]._setPoint(selTouch._point);
  4256. locTouches[index]._setPrevPoint(selTouch._prevPoint);
  4257. handleTouches.push(locTouches[index]);
  4258. this._removeUsedIndexBit(index);
  4259. delete locTouchesIntDict[touchID];
  4260. }
  4261. }
  4262. return handleTouches;
  4263. },
  4264. getHTMLElementPosition: function (element) {
  4265. var docElem = document.documentElement;
  4266. var win = window;
  4267. var box = null;
  4268. if (cc.isFunction(element.getBoundingClientRect)) {
  4269. box = element.getBoundingClientRect();
  4270. } else {
  4271. box = {
  4272. left: 0,
  4273. top: 0,
  4274. width: parseInt(element.style.width),
  4275. height: parseInt(element.style.height)
  4276. };
  4277. }
  4278. return {
  4279. left: box.left + win.pageXOffset - docElem.clientLeft,
  4280. top: box.top + win.pageYOffset - docElem.clientTop,
  4281. width: box.width,
  4282. height: box.height
  4283. };
  4284. },
  4285. getPreTouch: function(touch){
  4286. var preTouch = null;
  4287. var locPreTouchPool = this._preTouchPool;
  4288. var id = touch.getID();
  4289. for (var i = locPreTouchPool.length - 1; i >= 0; i--) {
  4290. if (locPreTouchPool[i].getID() === id) {
  4291. preTouch = locPreTouchPool[i];
  4292. break;
  4293. }
  4294. }
  4295. if (!preTouch)
  4296. preTouch = touch;
  4297. return preTouch;
  4298. },
  4299. setPreTouch: function(touch){
  4300. var find = false;
  4301. var locPreTouchPool = this._preTouchPool;
  4302. var id = touch.getID();
  4303. for (var i = locPreTouchPool.length - 1; i >= 0; i--) {
  4304. if (locPreTouchPool[i].getID() === id) {
  4305. locPreTouchPool[i] = touch;
  4306. find = true;
  4307. break;
  4308. }
  4309. }
  4310. if (!find) {
  4311. if (locPreTouchPool.length <= 50) {
  4312. locPreTouchPool.push(touch);
  4313. } else {
  4314. locPreTouchPool[this._preTouchPoolPointer] = touch;
  4315. this._preTouchPoolPointer = (this._preTouchPoolPointer + 1) % 50;
  4316. }
  4317. }
  4318. },
  4319. getTouchByXY: function(tx, ty, pos){
  4320. var locPreTouch = this._preTouchPoint;
  4321. var location = this._glView.convertToLocationInView(tx, ty, pos);
  4322. var touch = new cc.Touch(location.x, location.y);
  4323. touch._setPrevPoint(locPreTouch.x, locPreTouch.y);
  4324. locPreTouch.x = location.x;
  4325. locPreTouch.y = location.y;
  4326. return touch;
  4327. },
  4328. getMouseEvent: function(location, pos, eventType){
  4329. var locPreMouse = this._prevMousePoint;
  4330. this._glView._convertMouseToLocationInView(location, pos);
  4331. var mouseEvent = new cc.EventMouse(eventType);
  4332. mouseEvent.setLocation(location.x, location.y);
  4333. mouseEvent._setPrevCursor(locPreMouse.x, locPreMouse.y);
  4334. locPreMouse.x = location.x;
  4335. locPreMouse.y = location.y;
  4336. return mouseEvent;
  4337. },
  4338. getPointByEvent: function(event, pos){
  4339. if (event.pageX != null)
  4340. return {x: event.pageX, y: event.pageY};
  4341. pos.left -= document.body.scrollLeft;
  4342. pos.top -= document.body.scrollTop;
  4343. return {x: event.clientX, y: event.clientY};
  4344. },
  4345. getTouchesByEvent: function(event, pos){
  4346. var touchArr = [], locView = this._glView;
  4347. var touch_event, touch, preLocation;
  4348. var locPreTouch = this._preTouchPoint;
  4349. var length = event.changedTouches.length;
  4350. for (var i = 0; i < length; i++) {
  4351. touch_event = event.changedTouches[i];
  4352. if (touch_event) {
  4353. var location;
  4354. if (cc.sys.BROWSER_TYPE_FIREFOX === cc.sys.browserType)
  4355. location = locView.convertToLocationInView(touch_event.pageX, touch_event.pageY, pos);
  4356. else
  4357. location = locView.convertToLocationInView(touch_event.clientX, touch_event.clientY, pos);
  4358. if (touch_event.identifier != null) {
  4359. touch = new cc.Touch(location.x, location.y, touch_event.identifier);
  4360. preLocation = this.getPreTouch(touch).getLocation();
  4361. touch._setPrevPoint(preLocation.x, preLocation.y);
  4362. this.setPreTouch(touch);
  4363. } else {
  4364. touch = new cc.Touch(location.x, location.y);
  4365. touch._setPrevPoint(locPreTouch.x, locPreTouch.y);
  4366. }
  4367. locPreTouch.x = location.x;
  4368. locPreTouch.y = location.y;
  4369. touchArr.push(touch);
  4370. }
  4371. }
  4372. return touchArr;
  4373. },
  4374. registerSystemEvent: function(element){
  4375. if(this._isRegisterEvent) return;
  4376. var locView = this._glView = cc.view;
  4377. var selfPointer = this;
  4378. var supportMouse = ('mouse' in cc.sys.capabilities), supportTouches = ('touches' in cc.sys.capabilities);
  4379. var prohibition = false;
  4380. if( cc.sys.isMobile)
  4381. prohibition = true;
  4382. if (supportMouse) {
  4383. window.addEventListener('mousedown', function () {
  4384. selfPointer._mousePressed = true;
  4385. }, false);
  4386. window.addEventListener('mouseup', function (event) {
  4387. if(prohibition) return;
  4388. var savePressed = selfPointer._mousePressed;
  4389. selfPointer._mousePressed = false;
  4390. if(!savePressed)
  4391. return;
  4392. var pos = selfPointer.getHTMLElementPosition(element);
  4393. var location = selfPointer.getPointByEvent(event, pos);
  4394. if (!cc.rectContainsPoint(new cc.Rect(pos.left, pos.top, pos.width, pos.height), location)){
  4395. selfPointer.handleTouchesEnd([selfPointer.getTouchByXY(location.x, location.y, pos)]);
  4396. var mouseEvent = selfPointer.getMouseEvent(location,pos,cc.EventMouse.UP);
  4397. mouseEvent.setButton(event.button);
  4398. cc.eventManager.dispatchEvent(mouseEvent);
  4399. }
  4400. }, false);
  4401. element.addEventListener("mousedown", function (event) {
  4402. if(prohibition) return;
  4403. selfPointer._mousePressed = true;
  4404. var pos = selfPointer.getHTMLElementPosition(element);
  4405. var location = selfPointer.getPointByEvent(event, pos);
  4406. selfPointer.handleTouchesBegin([selfPointer.getTouchByXY(location.x, location.y, pos)]);
  4407. var mouseEvent = selfPointer.getMouseEvent(location,pos,cc.EventMouse.DOWN);
  4408. mouseEvent.setButton(event.button);
  4409. cc.eventManager.dispatchEvent(mouseEvent);
  4410. event.stopPropagation();
  4411. event.preventDefault();
  4412. element.focus();
  4413. }, false);
  4414. element.addEventListener("mouseup", function (event) {
  4415. if(prohibition) return;
  4416. selfPointer._mousePressed = false;
  4417. var pos = selfPointer.getHTMLElementPosition(element);
  4418. var location = selfPointer.getPointByEvent(event, pos);
  4419. selfPointer.handleTouchesEnd([selfPointer.getTouchByXY(location.x, location.y, pos)]);
  4420. var mouseEvent = selfPointer.getMouseEvent(location,pos,cc.EventMouse.UP);
  4421. mouseEvent.setButton(event.button);
  4422. cc.eventManager.dispatchEvent(mouseEvent);
  4423. event.stopPropagation();
  4424. event.preventDefault();
  4425. }, false);
  4426. element.addEventListener("mousemove", function (event) {
  4427. if(prohibition) return;
  4428. var pos = selfPointer.getHTMLElementPosition(element);
  4429. var location = selfPointer.getPointByEvent(event, pos);
  4430. selfPointer.handleTouchesMove([selfPointer.getTouchByXY(location.x, location.y, pos)]);
  4431. var mouseEvent = selfPointer.getMouseEvent(location,pos,cc.EventMouse.MOVE);
  4432. if(selfPointer._mousePressed)
  4433. mouseEvent.setButton(event.button);
  4434. else
  4435. mouseEvent.setButton(null);
  4436. cc.eventManager.dispatchEvent(mouseEvent);
  4437. event.stopPropagation();
  4438. event.preventDefault();
  4439. }, false);
  4440. element.addEventListener("mousewheel", function (event) {
  4441. var pos = selfPointer.getHTMLElementPosition(element);
  4442. var location = selfPointer.getPointByEvent(event, pos);
  4443. var mouseEvent = selfPointer.getMouseEvent(location,pos,cc.EventMouse.SCROLL);
  4444. mouseEvent.setButton(event.button);
  4445. mouseEvent.setScrollData(0, event.wheelDelta);
  4446. cc.eventManager.dispatchEvent(mouseEvent);
  4447. event.stopPropagation();
  4448. event.preventDefault();
  4449. }, false);
  4450. element.addEventListener("DOMMouseScroll", function(event) {
  4451. var pos = selfPointer.getHTMLElementPosition(element);
  4452. var location = selfPointer.getPointByEvent(event, pos);
  4453. var mouseEvent = selfPointer.getMouseEvent(location,pos,cc.EventMouse.SCROLL);
  4454. mouseEvent.setButton(event.button);
  4455. mouseEvent.setScrollData(0, event.detail * -120);
  4456. cc.eventManager.dispatchEvent(mouseEvent);
  4457. event.stopPropagation();
  4458. event.preventDefault();
  4459. }, false);
  4460. }
  4461. if(window.navigator.msPointerEnabled){
  4462. var _pointerEventsMap = {
  4463. "MSPointerDown" : selfPointer.handleTouchesBegin,
  4464. "MSPointerMove" : selfPointer.handleTouchesMove,
  4465. "MSPointerUp" : selfPointer.handleTouchesEnd,
  4466. "MSPointerCancel" : selfPointer.handleTouchesCancel
  4467. };
  4468. for(var eventName in _pointerEventsMap){
  4469. (function(_pointerEvent, _touchEvent){
  4470. element.addEventListener(_pointerEvent, function (event){
  4471. var pos = selfPointer.getHTMLElementPosition(element);
  4472. pos.left -= document.documentElement.scrollLeft;
  4473. pos.top -= document.documentElement.scrollTop;
  4474. _touchEvent.call(selfPointer, [selfPointer.getTouchByXY(event.clientX, event.clientY, pos)]);
  4475. event.stopPropagation();
  4476. }, false);
  4477. })(eventName, _pointerEventsMap[eventName]);
  4478. }
  4479. }
  4480. if(supportTouches) {
  4481. element.addEventListener("touchstart", function (event) {
  4482. if (!event.changedTouches) return;
  4483. var pos = selfPointer.getHTMLElementPosition(element);
  4484. pos.left -= document.body.scrollLeft;
  4485. pos.top -= document.body.scrollTop;
  4486. selfPointer.handleTouchesBegin(selfPointer.getTouchesByEvent(event, pos));
  4487. event.stopPropagation();
  4488. event.preventDefault();
  4489. element.focus();
  4490. }, false);
  4491. element.addEventListener("touchmove", function (event) {
  4492. if (!event.changedTouches) return;
  4493. var pos = selfPointer.getHTMLElementPosition(element);
  4494. pos.left -= document.body.scrollLeft;
  4495. pos.top -= document.body.scrollTop;
  4496. selfPointer.handleTouchesMove(selfPointer.getTouchesByEvent(event, pos));
  4497. event.stopPropagation();
  4498. event.preventDefault();
  4499. }, false);
  4500. element.addEventListener("touchend", function (event) {
  4501. if (!event.changedTouches) return;
  4502. var pos = selfPointer.getHTMLElementPosition(element);
  4503. pos.left -= document.body.scrollLeft;
  4504. pos.top -= document.body.scrollTop;
  4505. selfPointer.handleTouchesEnd(selfPointer.getTouchesByEvent(event, pos));
  4506. event.stopPropagation();
  4507. event.preventDefault();
  4508. }, false);
  4509. element.addEventListener("touchcancel", function (event) {
  4510. if (!event.changedTouches) return;
  4511. var pos = selfPointer.getHTMLElementPosition(element);
  4512. pos.left -= document.body.scrollLeft;
  4513. pos.top -= document.body.scrollTop;
  4514. selfPointer.handleTouchesCancel(selfPointer.getTouchesByEvent(event, pos));
  4515. event.stopPropagation();
  4516. event.preventDefault();
  4517. }, false);
  4518. }
  4519. this._registerKeyboardEvent();
  4520. this._registerAccelerometerEvent();
  4521. this._isRegisterEvent = true;
  4522. },
  4523. _registerKeyboardEvent: function(){},
  4524. _registerAccelerometerEvent: function(){},
  4525. update:function(dt){
  4526. if(this._accelCurTime > this._accelInterval){
  4527. this._accelCurTime -= this._accelInterval;
  4528. cc.eventManager.dispatchEvent(new cc.EventAcceleration(this._acceleration));
  4529. }
  4530. this._accelCurTime += dt;
  4531. }
  4532. };
  4533. cc.AffineTransform = function (a, b, c, d, tx, ty) {
  4534. this.a = a;
  4535. this.b = b;
  4536. this.c = c;
  4537. this.d = d;
  4538. this.tx = tx;
  4539. this.ty = ty;
  4540. };
  4541. cc.affineTransformMake = function (a, b, c, d, tx, ty) {
  4542. return {a: a, b: b, c: c, d: d, tx: tx, ty: ty};
  4543. };
  4544. cc.pointApplyAffineTransform = function (point, transOrY, t) {
  4545. var x, y;
  4546. if (t === undefined) {
  4547. t = transOrY;
  4548. x = point.x;
  4549. y = point.y;
  4550. } else {
  4551. x = point;
  4552. y = transOrY;
  4553. }
  4554. return {x: t.a * x + t.c * y + t.tx, y: t.b * x + t.d * y + t.ty};
  4555. };
  4556. cc._pointApplyAffineTransform = function (x, y, t) {
  4557. return cc.pointApplyAffineTransform(x, y, t);
  4558. };
  4559. cc.sizeApplyAffineTransform = function (size, t) {
  4560. return {width: t.a * size.width + t.c * size.height, height: t.b * size.width + t.d * size.height};
  4561. };
  4562. cc.affineTransformMakeIdentity = function () {
  4563. return {a: 1.0, b: 0.0, c: 0.0, d: 1.0, tx: 0.0, ty: 0.0};
  4564. };
  4565. cc.affineTransformIdentity = function () {
  4566. return {a: 1.0, b: 0.0, c: 0.0, d: 1.0, tx: 0.0, ty: 0.0};
  4567. };
  4568. cc.rectApplyAffineTransform = function (rect, anAffineTransform) {
  4569. var top = cc.rectGetMinY(rect);
  4570. var left = cc.rectGetMinX(rect);
  4571. var right = cc.rectGetMaxX(rect);
  4572. var bottom = cc.rectGetMaxY(rect);
  4573. var topLeft = cc.pointApplyAffineTransform(left, top, anAffineTransform);
  4574. var topRight = cc.pointApplyAffineTransform(right, top, anAffineTransform);
  4575. var bottomLeft = cc.pointApplyAffineTransform(left, bottom, anAffineTransform);
  4576. var bottomRight = cc.pointApplyAffineTransform(right, bottom, anAffineTransform);
  4577. var minX = Math.min(topLeft.x, topRight.x, bottomLeft.x, bottomRight.x);
  4578. var maxX = Math.max(topLeft.x, topRight.x, bottomLeft.x, bottomRight.x);
  4579. var minY = Math.min(topLeft.y, topRight.y, bottomLeft.y, bottomRight.y);
  4580. var maxY = Math.max(topLeft.y, topRight.y, bottomLeft.y, bottomRight.y);
  4581. return cc.rect(minX, minY, (maxX - minX), (maxY - minY));
  4582. };
  4583. cc._rectApplyAffineTransformIn = function(rect, anAffineTransform){
  4584. var top = cc.rectGetMinY(rect);
  4585. var left = cc.rectGetMinX(rect);
  4586. var right = cc.rectGetMaxX(rect);
  4587. var bottom = cc.rectGetMaxY(rect);
  4588. var topLeft = cc.pointApplyAffineTransform(left, top, anAffineTransform);
  4589. var topRight = cc.pointApplyAffineTransform(right, top, anAffineTransform);
  4590. var bottomLeft = cc.pointApplyAffineTransform(left, bottom, anAffineTransform);
  4591. var bottomRight = cc.pointApplyAffineTransform(right, bottom, anAffineTransform);
  4592. var minX = Math.min(topLeft.x, topRight.x, bottomLeft.x, bottomRight.x);
  4593. var maxX = Math.max(topLeft.x, topRight.x, bottomLeft.x, bottomRight.x);
  4594. var minY = Math.min(topLeft.y, topRight.y, bottomLeft.y, bottomRight.y);
  4595. var maxY = Math.max(topLeft.y, topRight.y, bottomLeft.y, bottomRight.y);
  4596. rect.x = minX;
  4597. rect.y = minY;
  4598. rect.width = maxX - minX;
  4599. rect.height = maxY - minY;
  4600. return rect;
  4601. };
  4602. cc.affineTransformTranslate = function (t, tx, ty) {
  4603. return {
  4604. a: t.a,
  4605. b: t.b,
  4606. c: t.c,
  4607. d: t.d,
  4608. tx: t.tx + t.a * tx + t.c * ty,
  4609. ty: t.ty + t.b * tx + t.d * ty
  4610. };
  4611. };
  4612. cc.affineTransformScale = function (t, sx, sy) {
  4613. return {a: t.a * sx, b: t.b * sx, c: t.c * sy, d: t.d * sy, tx: t.tx, ty: t.ty};
  4614. };
  4615. cc.affineTransformRotate = function (aTransform, anAngle) {
  4616. var fSin = Math.sin(anAngle);
  4617. var fCos = Math.cos(anAngle);
  4618. return {a: aTransform.a * fCos + aTransform.c * fSin,
  4619. b: aTransform.b * fCos + aTransform.d * fSin,
  4620. c: aTransform.c * fCos - aTransform.a * fSin,
  4621. d: aTransform.d * fCos - aTransform.b * fSin,
  4622. tx: aTransform.tx,
  4623. ty: aTransform.ty};
  4624. };
  4625. cc.affineTransformConcat = function (t1, t2) {
  4626. return {a: t1.a * t2.a + t1.b * t2.c,
  4627. b: t1.a * t2.b + t1.b * t2.d,
  4628. c: t1.c * t2.a + t1.d * t2.c,
  4629. d: t1.c * t2.b + t1.d * t2.d,
  4630. tx: t1.tx * t2.a + t1.ty * t2.c + t2.tx,
  4631. ty: t1.tx * t2.b + t1.ty * t2.d + t2.ty};
  4632. };
  4633. cc.affineTransformConcatIn = function (t1, t2) {
  4634. var a = t1.a, b = t1.b, c = t1.c, d = t1.d, tx = t1.tx, ty = t1.ty;
  4635. t1.a = a * t2.a + b * t2.c;
  4636. t1.b = a * t2.b + b * t2.d;
  4637. t1.c = c * t2.a + d * t2.c;
  4638. t1.d = c * t2.b + d * t2.d;
  4639. t1.tx = tx * t2.a + ty * t2.c + t2.tx;
  4640. t1.ty = tx * t2.b + ty * t2.d + t2.ty;
  4641. return t1;
  4642. };
  4643. cc.affineTransformEqualToTransform = function (t1, t2) {
  4644. return ((t1.a === t2.a) && (t1.b === t2.b) && (t1.c === t2.c) && (t1.d === t2.d) && (t1.tx === t2.tx) && (t1.ty === t2.ty));
  4645. };
  4646. cc.affineTransformInvert = function (t) {
  4647. var determinant = 1 / (t.a * t.d - t.b * t.c);
  4648. return {a: determinant * t.d, b: -determinant * t.b, c: -determinant * t.c, d: determinant * t.a,
  4649. tx: determinant * (t.c * t.ty - t.d * t.tx), ty: determinant * (t.b * t.tx - t.a * t.ty)};
  4650. };
  4651. cc.POINT_EPSILON = parseFloat('1.192092896e-07F');
  4652. cc.pNeg = function (point) {
  4653. return cc.p(-point.x, -point.y);
  4654. };
  4655. cc.pAdd = function (v1, v2) {
  4656. return cc.p(v1.x + v2.x, v1.y + v2.y);
  4657. };
  4658. cc.pSub = function (v1, v2) {
  4659. return cc.p(v1.x - v2.x, v1.y - v2.y);
  4660. };
  4661. cc.pMult = function (point, floatVar) {
  4662. return cc.p(point.x * floatVar, point.y * floatVar);
  4663. };
  4664. cc.pMidpoint = function (v1, v2) {
  4665. return cc.pMult(cc.pAdd(v1, v2), 0.5);
  4666. };
  4667. cc.pDot = function (v1, v2) {
  4668. return v1.x * v2.x + v1.y * v2.y;
  4669. };
  4670. cc.pCross = function (v1, v2) {
  4671. return v1.x * v2.y - v1.y * v2.x;
  4672. };
  4673. cc.pPerp = function (point) {
  4674. return cc.p(-point.y, point.x);
  4675. };
  4676. cc.pRPerp = function (point) {
  4677. return cc.p(point.y, -point.x);
  4678. };
  4679. cc.pProject = function (v1, v2) {
  4680. return cc.pMult(v2, cc.pDot(v1, v2) / cc.pDot(v2, v2));
  4681. };
  4682. cc.pRotate = function (v1, v2) {
  4683. return cc.p(v1.x * v2.x - v1.y * v2.y, v1.x * v2.y + v1.y * v2.x);
  4684. };
  4685. cc.pUnrotate = function (v1, v2) {
  4686. return cc.p(v1.x * v2.x + v1.y * v2.y, v1.y * v2.x - v1.x * v2.y);
  4687. };
  4688. cc.pLengthSQ = function (v) {
  4689. return cc.pDot(v, v);
  4690. };
  4691. cc.pDistanceSQ = function(point1, point2){
  4692. return cc.pLengthSQ(cc.pSub(point1,point2));
  4693. };
  4694. cc.pLength = function (v) {
  4695. return Math.sqrt(cc.pLengthSQ(v));
  4696. };
  4697. cc.pDistance = function (v1, v2) {
  4698. return cc.pLength(cc.pSub(v1, v2));
  4699. };
  4700. cc.pNormalize = function (v) {
  4701. var n = cc.pLength(v);
  4702. return n === 0 ? cc.p(v) : cc.pMult(v, 1.0 / n);
  4703. };
  4704. cc.pForAngle = function (a) {
  4705. return cc.p(Math.cos(a), Math.sin(a));
  4706. };
  4707. cc.pToAngle = function (v) {
  4708. return Math.atan2(v.y, v.x);
  4709. };
  4710. cc.clampf = function (value, min_inclusive, max_inclusive) {
  4711. if (min_inclusive > max_inclusive) {
  4712. var temp = min_inclusive;
  4713. min_inclusive = max_inclusive;
  4714. max_inclusive = temp;
  4715. }
  4716. return value < min_inclusive ? min_inclusive : value < max_inclusive ? value : max_inclusive;
  4717. };
  4718. cc.pClamp = function (p, min_inclusive, max_inclusive) {
  4719. return cc.p(cc.clampf(p.x, min_inclusive.x, max_inclusive.x), cc.clampf(p.y, min_inclusive.y, max_inclusive.y));
  4720. };
  4721. cc.pFromSize = function (s) {
  4722. return cc.p(s.width, s.height);
  4723. };
  4724. cc.pCompOp = function (p, opFunc) {
  4725. return cc.p(opFunc(p.x), opFunc(p.y));
  4726. };
  4727. cc.pLerp = function (a, b, alpha) {
  4728. return cc.pAdd(cc.pMult(a, 1 - alpha), cc.pMult(b, alpha));
  4729. };
  4730. cc.pFuzzyEqual = function (a, b, variance) {
  4731. if (a.x - variance <= b.x && b.x <= a.x + variance) {
  4732. if (a.y - variance <= b.y && b.y <= a.y + variance)
  4733. return true;
  4734. }
  4735. return false;
  4736. };
  4737. cc.pCompMult = function (a, b) {
  4738. return cc.p(a.x * b.x, a.y * b.y);
  4739. };
  4740. cc.pAngleSigned = function (a, b) {
  4741. var a2 = cc.pNormalize(a);
  4742. var b2 = cc.pNormalize(b);
  4743. var angle = Math.atan2(a2.x * b2.y - a2.y * b2.x, cc.pDot(a2, b2));
  4744. if (Math.abs(angle) < cc.POINT_EPSILON)
  4745. return 0.0;
  4746. return angle;
  4747. };
  4748. cc.pAngle = function (a, b) {
  4749. var angle = Math.acos(cc.pDot(cc.pNormalize(a), cc.pNormalize(b)));
  4750. if (Math.abs(angle) < cc.POINT_EPSILON) return 0.0;
  4751. return angle;
  4752. };
  4753. cc.pRotateByAngle = function (v, pivot, angle) {
  4754. var r = cc.pSub(v, pivot);
  4755. var cosa = Math.cos(angle), sina = Math.sin(angle);
  4756. var t = r.x;
  4757. r.x = t * cosa - r.y * sina + pivot.x;
  4758. r.y = t * sina + r.y * cosa + pivot.y;
  4759. return r;
  4760. };
  4761. cc.pLineIntersect = function (A, B, C, D, retP) {
  4762. if ((A.x === B.x && A.y === B.y) || (C.x === D.x && C.y === D.y)) {
  4763. return false;
  4764. }
  4765. var BAx = B.x - A.x;
  4766. var BAy = B.y - A.y;
  4767. var DCx = D.x - C.x;
  4768. var DCy = D.y - C.y;
  4769. var ACx = A.x - C.x;
  4770. var ACy = A.y - C.y;
  4771. var denom = DCy * BAx - DCx * BAy;
  4772. retP.x = DCx * ACy - DCy * ACx;
  4773. retP.y = BAx * ACy - BAy * ACx;
  4774. if (denom === 0) {
  4775. if (retP.x === 0 || retP.y === 0) {
  4776. return true;
  4777. }
  4778. return false;
  4779. }
  4780. retP.x = retP.x / denom;
  4781. retP.y = retP.y / denom;
  4782. return true;
  4783. };
  4784. cc.pSegmentIntersect = function (A, B, C, D) {
  4785. var retP = cc.p(0, 0);
  4786. if (cc.pLineIntersect(A, B, C, D, retP))
  4787. if (retP.x >= 0.0 && retP.x <= 1.0 && retP.y >= 0.0 && retP.y <= 1.0)
  4788. return true;
  4789. return false;
  4790. };
  4791. cc.pIntersectPoint = function (A, B, C, D) {
  4792. var retP = cc.p(0, 0);
  4793. if (cc.pLineIntersect(A, B, C, D, retP)) {
  4794. var P = cc.p(0, 0);
  4795. P.x = A.x + retP.x * (B.x - A.x);
  4796. P.y = A.y + retP.x * (B.y - A.y);
  4797. return P;
  4798. }
  4799. return cc.p(0,0);
  4800. };
  4801. cc.pSameAs = function (A, B) {
  4802. if ((A != null) && (B != null)) {
  4803. return (A.x === B.x && A.y === B.y);
  4804. }
  4805. return false;
  4806. };
  4807. cc.pZeroIn = function(v) {
  4808. v.x = 0;
  4809. v.y = 0;
  4810. };
  4811. cc.pIn = function(v1, v2) {
  4812. v1.x = v2.x;
  4813. v1.y = v2.y;
  4814. };
  4815. cc.pMultIn = function(point, floatVar) {
  4816. point.x *= floatVar;
  4817. point.y *= floatVar;
  4818. };
  4819. cc.pSubIn = function(v1, v2) {
  4820. v1.x -= v2.x;
  4821. v1.y -= v2.y;
  4822. };
  4823. cc.pAddIn = function(v1, v2) {
  4824. v1.x += v2.x;
  4825. v1.y += v2.y;
  4826. };
  4827. cc.pNormalizeIn = function(v) {
  4828. cc.pMultIn(v, 1.0 / Math.sqrt(v.x * v.x + v.y * v.y));
  4829. };
  4830. cc.Touch = cc.Class.extend({
  4831. _point:null,
  4832. _prevPoint:null,
  4833. _id:0,
  4834. _startPointCaptured: false,
  4835. _startPoint:null,
  4836. ctor:function (x, y, id) {
  4837. this.setTouchInfo(id, x, y);
  4838. },
  4839. getLocation:function () {
  4840. return {x: this._point.x, y: this._point.y};
  4841. },
  4842. getLocationX: function () {
  4843. return this._point.x;
  4844. },
  4845. getLocationY: function () {
  4846. return this._point.y;
  4847. },
  4848. getPreviousLocation:function () {
  4849. return {x: this._prevPoint.x, y: this._prevPoint.y};
  4850. },
  4851. getStartLocation: function() {
  4852. return {x: this._startPoint.x, y: this._startPoint.y};
  4853. },
  4854. getDelta:function () {
  4855. return cc.pSub(this._point, this._prevPoint);
  4856. },
  4857. getLocationInView: function() {
  4858. return {x: this._point.x, y: this._point.y};
  4859. },
  4860. getPreviousLocationInView: function(){
  4861. return {x: this._prevPoint.x, y: this._prevPoint.y};
  4862. },
  4863. getStartLocationInView: function(){
  4864. return {x: this._startPoint.x, y: this._startPoint.y};
  4865. },
  4866. getID:function () {
  4867. return this._id;
  4868. },
  4869. getId:function () {
  4870. cc.log("getId is deprecated. Please use getID instead.");
  4871. return this._id;
  4872. },
  4873. setTouchInfo:function (id, x, y) {
  4874. this._prevPoint = this._point;
  4875. this._point = cc.p(x || 0, y || 0);
  4876. this._id = id;
  4877. if (!this._startPointCaptured) {
  4878. this._startPoint = cc.p(this._point);
  4879. cc.view._convertPointWithScale(this._startPoint);
  4880. this._startPointCaptured = true;
  4881. }
  4882. },
  4883. _setPoint: function(x, y){
  4884. if(y === undefined){
  4885. this._point.x = x.x;
  4886. this._point.y = x.y;
  4887. }else{
  4888. this._point.x = x;
  4889. this._point.y = y;
  4890. }
  4891. },
  4892. _setPrevPoint:function (x, y) {
  4893. if(y === undefined)
  4894. this._prevPoint = cc.p(x.x, x.y);
  4895. else
  4896. this._prevPoint = cc.p(x || 0, y || 0);
  4897. }
  4898. });
  4899. cc.Event = cc.Class.extend({
  4900. _type: 0,
  4901. _isStopped: false,
  4902. _currentTarget: null,
  4903. _setCurrentTarget: function (target) {
  4904. this._currentTarget = target;
  4905. },
  4906. ctor: function (type) {
  4907. this._type = type;
  4908. },
  4909. getType: function () {
  4910. return this._type;
  4911. },
  4912. stopPropagation: function () {
  4913. this._isStopped = true;
  4914. },
  4915. isStopped: function () {
  4916. return this._isStopped;
  4917. },
  4918. getCurrentTarget: function () {
  4919. return this._currentTarget;
  4920. }
  4921. });
  4922. cc.Event.TOUCH = 0;
  4923. cc.Event.KEYBOARD = 1;
  4924. cc.Event.ACCELERATION = 2;
  4925. cc.Event.MOUSE = 3;
  4926. cc.Event.FOCUS = 4;
  4927. cc.Event.CUSTOM = 6;
  4928. cc.EventCustom = cc.Event.extend({
  4929. _eventName: null,
  4930. _userData: null,
  4931. ctor: function (eventName) {
  4932. cc.Event.prototype.ctor.call(this, cc.Event.CUSTOM);
  4933. this._eventName = eventName;
  4934. },
  4935. setUserData: function (data) {
  4936. this._userData = data;
  4937. },
  4938. getUserData: function () {
  4939. return this._userData;
  4940. },
  4941. getEventName: function () {
  4942. return this._eventName;
  4943. }
  4944. });
  4945. cc.EventMouse = cc.Event.extend({
  4946. _eventType: 0,
  4947. _button: 0,
  4948. _x: 0,
  4949. _y: 0,
  4950. _prevX: 0,
  4951. _prevY: 0,
  4952. _scrollX: 0,
  4953. _scrollY: 0,
  4954. ctor: function (eventType) {
  4955. cc.Event.prototype.ctor.call(this, cc.Event.MOUSE);
  4956. this._eventType = eventType;
  4957. },
  4958. setScrollData: function (scrollX, scrollY) {
  4959. this._scrollX = scrollX;
  4960. this._scrollY = scrollY;
  4961. },
  4962. getScrollX: function () {
  4963. return this._scrollX;
  4964. },
  4965. getScrollY: function () {
  4966. return this._scrollY;
  4967. },
  4968. setLocation: function (x, y) {
  4969. this._x = x;
  4970. this._y = y;
  4971. },
  4972. getLocation: function () {
  4973. return {x: this._x, y: this._y};
  4974. },
  4975. getLocationInView: function() {
  4976. return {x: this._x, y: cc.view._designResolutionSize.height - this._y};
  4977. },
  4978. _setPrevCursor: function (x, y) {
  4979. this._prevX = x;
  4980. this._prevY = y;
  4981. },
  4982. getDelta: function () {
  4983. return {x: this._x - this._prevX, y: this._y - this._prevY};
  4984. },
  4985. getDeltaX: function () {
  4986. return this._x - this._prevX;
  4987. },
  4988. getDeltaY: function () {
  4989. return this._y - this._prevY;
  4990. },
  4991. setButton: function (button) {
  4992. this._button = button;
  4993. },
  4994. getButton: function () {
  4995. return this._button;
  4996. },
  4997. getLocationX: function () {
  4998. return this._x;
  4999. },
  5000. getLocationY: function () {
  5001. return this._y;
  5002. }
  5003. });
  5004. cc.EventMouse.NONE = 0;
  5005. cc.EventMouse.DOWN = 1;
  5006. cc.EventMouse.UP = 2;
  5007. cc.EventMouse.MOVE = 3;
  5008. cc.EventMouse.SCROLL = 4;
  5009. cc.EventMouse.BUTTON_LEFT = 0;
  5010. cc.EventMouse.BUTTON_RIGHT = 2;
  5011. cc.EventMouse.BUTTON_MIDDLE = 1;
  5012. cc.EventMouse.BUTTON_4 = 3;
  5013. cc.EventMouse.BUTTON_5 = 4;
  5014. cc.EventMouse.BUTTON_6 = 5;
  5015. cc.EventMouse.BUTTON_7 = 6;
  5016. cc.EventMouse.BUTTON_8 = 7;
  5017. cc.EventTouch = cc.Event.extend({
  5018. _eventCode: 0,
  5019. _touches: null,
  5020. ctor: function (arr) {
  5021. cc.Event.prototype.ctor.call(this, cc.Event.TOUCH);
  5022. this._touches = arr || [];
  5023. },
  5024. getEventCode: function () {
  5025. return this._eventCode;
  5026. },
  5027. getTouches: function () {
  5028. return this._touches;
  5029. },
  5030. _setEventCode: function (eventCode) {
  5031. this._eventCode = eventCode;
  5032. },
  5033. _setTouches: function (touches) {
  5034. this._touches = touches;
  5035. }
  5036. });
  5037. cc.EventTouch.MAX_TOUCHES = 5;
  5038. cc.EventTouch.EventCode = {BEGAN: 0, MOVED: 1, ENDED: 2, CANCELLED: 3};
  5039. cc.EventFocus = cc.Event.extend({
  5040. _widgetGetFocus: null,
  5041. _widgetLoseFocus: null,
  5042. ctor: function(widgetLoseFocus, widgetGetFocus){
  5043. cc.Event.prototype.ctor.call(this, cc.Event.FOCUS);
  5044. this._widgetGetFocus = widgetGetFocus;
  5045. this._widgetLoseFocus = widgetLoseFocus;
  5046. }
  5047. });
  5048. cc.EventListener = cc.Class.extend({
  5049. _onEvent: null,
  5050. _type: 0,
  5051. _listenerID: null,
  5052. _registered: false,
  5053. _fixedPriority: 0,
  5054. _node: null,
  5055. _paused: true,
  5056. _isEnabled: true,
  5057. ctor: function (type, listenerID, callback) {
  5058. this._onEvent = callback;
  5059. this._type = type || 0;
  5060. this._listenerID = listenerID || "";
  5061. },
  5062. _setPaused: function (paused) {
  5063. this._paused = paused;
  5064. },
  5065. _isPaused: function () {
  5066. return this._paused;
  5067. },
  5068. _setRegistered: function (registered) {
  5069. this._registered = registered;
  5070. },
  5071. _isRegistered: function () {
  5072. return this._registered;
  5073. },
  5074. _getType: function () {
  5075. return this._type;
  5076. },
  5077. _getListenerID: function () {
  5078. return this._listenerID;
  5079. },
  5080. _setFixedPriority: function (fixedPriority) {
  5081. this._fixedPriority = fixedPriority;
  5082. },
  5083. _getFixedPriority: function () {
  5084. return this._fixedPriority;
  5085. },
  5086. _setSceneGraphPriority: function (node) {
  5087. this._node = node;
  5088. },
  5089. _getSceneGraphPriority: function () {
  5090. return this._node;
  5091. },
  5092. checkAvailable: function () {
  5093. return this._onEvent !== null;
  5094. },
  5095. clone: function () {
  5096. return null;
  5097. },
  5098. setEnabled: function(enabled){
  5099. this._isEnabled = enabled;
  5100. },
  5101. isEnabled: function(){
  5102. return this._isEnabled;
  5103. },
  5104. retain:function () {
  5105. },
  5106. release:function () {
  5107. }
  5108. });
  5109. cc.EventListener.UNKNOWN = 0;
  5110. cc.EventListener.TOUCH_ONE_BY_ONE = 1;
  5111. cc.EventListener.TOUCH_ALL_AT_ONCE = 2;
  5112. cc.EventListener.KEYBOARD = 3;
  5113. cc.EventListener.MOUSE = 4;
  5114. cc.EventListener.ACCELERATION = 6;
  5115. cc.EventListener.FOCUS = 7;
  5116. cc.EventListener.CUSTOM = 8;
  5117. cc._EventListenerCustom = cc.EventListener.extend({
  5118. _onCustomEvent: null,
  5119. ctor: function (listenerId, callback) {
  5120. this._onCustomEvent = callback;
  5121. var selfPointer = this;
  5122. var listener = function (event) {
  5123. if (selfPointer._onCustomEvent !== null)
  5124. selfPointer._onCustomEvent(event);
  5125. };
  5126. cc.EventListener.prototype.ctor.call(this, cc.EventListener.CUSTOM, listenerId, listener);
  5127. },
  5128. checkAvailable: function () {
  5129. return (cc.EventListener.prototype.checkAvailable.call(this) && this._onCustomEvent !== null);
  5130. },
  5131. clone: function () {
  5132. return new cc._EventListenerCustom(this._listenerID, this._onCustomEvent);
  5133. }
  5134. });
  5135. cc._EventListenerCustom.create = function (eventName, callback) {
  5136. return new cc._EventListenerCustom(eventName, callback);
  5137. };
  5138. cc._EventListenerMouse = cc.EventListener.extend({
  5139. onMouseDown: null,
  5140. onMouseUp: null,
  5141. onMouseMove: null,
  5142. onMouseScroll: null,
  5143. ctor: function () {
  5144. var selfPointer = this;
  5145. var listener = function (event) {
  5146. var eventType = cc.EventMouse;
  5147. switch (event._eventType) {
  5148. case eventType.DOWN:
  5149. if (selfPointer.onMouseDown)
  5150. selfPointer.onMouseDown(event);
  5151. break;
  5152. case eventType.UP:
  5153. if (selfPointer.onMouseUp)
  5154. selfPointer.onMouseUp(event);
  5155. break;
  5156. case eventType.MOVE:
  5157. if (selfPointer.onMouseMove)
  5158. selfPointer.onMouseMove(event);
  5159. break;
  5160. case eventType.SCROLL:
  5161. if (selfPointer.onMouseScroll)
  5162. selfPointer.onMouseScroll(event);
  5163. break;
  5164. default:
  5165. break;
  5166. }
  5167. };
  5168. cc.EventListener.prototype.ctor.call(this, cc.EventListener.MOUSE, cc._EventListenerMouse.LISTENER_ID, listener);
  5169. },
  5170. clone: function () {
  5171. var eventListener = new cc._EventListenerMouse();
  5172. eventListener.onMouseDown = this.onMouseDown;
  5173. eventListener.onMouseUp = this.onMouseUp;
  5174. eventListener.onMouseMove = this.onMouseMove;
  5175. eventListener.onMouseScroll = this.onMouseScroll;
  5176. return eventListener;
  5177. },
  5178. checkAvailable: function () {
  5179. return true;
  5180. }
  5181. });
  5182. cc._EventListenerMouse.LISTENER_ID = "__cc_mouse";
  5183. cc._EventListenerMouse.create = function () {
  5184. return new cc._EventListenerMouse();
  5185. };
  5186. cc._EventListenerTouchOneByOne = cc.EventListener.extend({
  5187. _claimedTouches: null,
  5188. swallowTouches: false,
  5189. onTouchBegan: null,
  5190. onTouchMoved: null,
  5191. onTouchEnded: null,
  5192. onTouchCancelled: null,
  5193. ctor: function () {
  5194. cc.EventListener.prototype.ctor.call(this, cc.EventListener.TOUCH_ONE_BY_ONE, cc._EventListenerTouchOneByOne.LISTENER_ID, null);
  5195. this._claimedTouches = [];
  5196. },
  5197. setSwallowTouches: function (needSwallow) {
  5198. this.swallowTouches = needSwallow;
  5199. },
  5200. isSwallowTouches: function(){
  5201. return this.swallowTouches;
  5202. },
  5203. clone: function () {
  5204. var eventListener = new cc._EventListenerTouchOneByOne();
  5205. eventListener.onTouchBegan = this.onTouchBegan;
  5206. eventListener.onTouchMoved = this.onTouchMoved;
  5207. eventListener.onTouchEnded = this.onTouchEnded;
  5208. eventListener.onTouchCancelled = this.onTouchCancelled;
  5209. eventListener.swallowTouches = this.swallowTouches;
  5210. return eventListener;
  5211. },
  5212. checkAvailable: function () {
  5213. if(!this.onTouchBegan){
  5214. cc.log(cc._LogInfos._EventListenerTouchOneByOne_checkAvailable);
  5215. return false;
  5216. }
  5217. return true;
  5218. }
  5219. });
  5220. cc._EventListenerTouchOneByOne.LISTENER_ID = "__cc_touch_one_by_one";
  5221. cc._EventListenerTouchOneByOne.create = function () {
  5222. return new cc._EventListenerTouchOneByOne();
  5223. };
  5224. cc._EventListenerTouchAllAtOnce = cc.EventListener.extend({
  5225. onTouchesBegan: null,
  5226. onTouchesMoved: null,
  5227. onTouchesEnded: null,
  5228. onTouchesCancelled: null,
  5229. ctor: function(){
  5230. cc.EventListener.prototype.ctor.call(this, cc.EventListener.TOUCH_ALL_AT_ONCE, cc._EventListenerTouchAllAtOnce.LISTENER_ID, null);
  5231. },
  5232. clone: function(){
  5233. var eventListener = new cc._EventListenerTouchAllAtOnce();
  5234. eventListener.onTouchesBegan = this.onTouchesBegan;
  5235. eventListener.onTouchesMoved = this.onTouchesMoved;
  5236. eventListener.onTouchesEnded = this.onTouchesEnded;
  5237. eventListener.onTouchesCancelled = this.onTouchesCancelled;
  5238. return eventListener;
  5239. },
  5240. checkAvailable: function(){
  5241. if (this.onTouchesBegan === null && this.onTouchesMoved === null
  5242. && this.onTouchesEnded === null && this.onTouchesCancelled === null) {
  5243. cc.log(cc._LogInfos._EventListenerTouchAllAtOnce_checkAvailable);
  5244. return false;
  5245. }
  5246. return true;
  5247. }
  5248. });
  5249. cc._EventListenerTouchAllAtOnce.LISTENER_ID = "__cc_touch_all_at_once";
  5250. cc._EventListenerTouchAllAtOnce.create = function(){
  5251. return new cc._EventListenerTouchAllAtOnce();
  5252. };
  5253. cc.EventListener.create = function(argObj){
  5254. cc.assert(argObj&&argObj.event, cc._LogInfos.EventListener_create);
  5255. var listenerType = argObj.event;
  5256. delete argObj.event;
  5257. var listener = null;
  5258. if(listenerType === cc.EventListener.TOUCH_ONE_BY_ONE)
  5259. listener = new cc._EventListenerTouchOneByOne();
  5260. else if(listenerType === cc.EventListener.TOUCH_ALL_AT_ONCE)
  5261. listener = new cc._EventListenerTouchAllAtOnce();
  5262. else if(listenerType === cc.EventListener.MOUSE)
  5263. listener = new cc._EventListenerMouse();
  5264. else if(listenerType === cc.EventListener.CUSTOM){
  5265. listener = new cc._EventListenerCustom(argObj.eventName, argObj.callback);
  5266. delete argObj.eventName;
  5267. delete argObj.callback;
  5268. } else if(listenerType === cc.EventListener.KEYBOARD)
  5269. listener = new cc._EventListenerKeyboard();
  5270. else if(listenerType === cc.EventListener.ACCELERATION){
  5271. listener = new cc._EventListenerAcceleration(argObj.callback);
  5272. delete argObj.callback;
  5273. } else if(listenerType === cc.EventListener.FOCUS)
  5274. listener = new cc._EventListenerFocus();
  5275. for(var key in argObj) {
  5276. listener[key] = argObj[key];
  5277. }
  5278. return listener;
  5279. };
  5280. cc._EventListenerFocus = cc.EventListener.extend({
  5281. clone: function(){
  5282. var listener = new cc._EventListenerFocus();
  5283. listener.onFocusChanged = this.onFocusChanged;
  5284. return listener;
  5285. },
  5286. checkAvailable: function(){
  5287. if(!this.onFocusChanged){
  5288. cc.log("Invalid EventListenerFocus!");
  5289. return false;
  5290. }
  5291. return true;
  5292. },
  5293. onFocusChanged: null,
  5294. ctor: function(){
  5295. var listener = function(event){
  5296. if(this.onFocusChanged)
  5297. this.onFocusChanged(event._widgetLoseFocus, event._widgetGetFocus);
  5298. };
  5299. cc.EventListener.prototype.ctor.call(this, cc.EventListener.FOCUS, cc._EventListenerFocus.LISTENER_ID, listener);
  5300. }
  5301. });
  5302. cc._EventListenerFocus.LISTENER_ID = "__cc_focus_event";
  5303. cc._EventListenerVector = cc.Class.extend({
  5304. _fixedListeners: null,
  5305. _sceneGraphListeners: null,
  5306. gt0Index: 0,
  5307. ctor: function () {
  5308. this._fixedListeners = [];
  5309. this._sceneGraphListeners = [];
  5310. },
  5311. size: function () {
  5312. return this._fixedListeners.length + this._sceneGraphListeners.length;
  5313. },
  5314. empty: function () {
  5315. return (this._fixedListeners.length === 0) && (this._sceneGraphListeners.length === 0);
  5316. },
  5317. push: function (listener) {
  5318. if (listener._getFixedPriority() === 0)
  5319. this._sceneGraphListeners.push(listener);
  5320. else
  5321. this._fixedListeners.push(listener);
  5322. },
  5323. clearSceneGraphListeners: function () {
  5324. this._sceneGraphListeners.length = 0;
  5325. },
  5326. clearFixedListeners: function () {
  5327. this._fixedListeners.length = 0;
  5328. },
  5329. clear: function () {
  5330. this._sceneGraphListeners.length = 0;
  5331. this._fixedListeners.length = 0;
  5332. },
  5333. getFixedPriorityListeners: function () {
  5334. return this._fixedListeners;
  5335. },
  5336. getSceneGraphPriorityListeners: function () {
  5337. return this._sceneGraphListeners;
  5338. }
  5339. });
  5340. cc.__getListenerID = function (event) {
  5341. var eventType = cc.Event, getType = event.getType();
  5342. if(getType === eventType.ACCELERATION)
  5343. return cc._EventListenerAcceleration.LISTENER_ID;
  5344. if(getType === eventType.CUSTOM)
  5345. return event.getEventName();
  5346. if(getType === eventType.KEYBOARD)
  5347. return cc._EventListenerKeyboard.LISTENER_ID;
  5348. if(getType === eventType.MOUSE)
  5349. return cc._EventListenerMouse.LISTENER_ID;
  5350. if(getType === eventType.FOCUS)
  5351. return cc._EventListenerFocus.LISTENER_ID;
  5352. if(getType === eventType.TOUCH){
  5353. cc.log(cc._LogInfos.__getListenerID);
  5354. }
  5355. return "";
  5356. };
  5357. cc.eventManager = {
  5358. DIRTY_NONE:0,
  5359. DIRTY_FIXED_PRIORITY:1 <<0,
  5360. DIRTY_SCENE_GRAPH_PRIORITY : 1<< 1,
  5361. DIRTY_ALL: 3,
  5362. _listenersMap: {},
  5363. _priorityDirtyFlagMap: {},
  5364. _nodeListenersMap: {},
  5365. _nodePriorityMap: {},
  5366. _globalZOrderNodeMap: {},
  5367. _toAddedListeners: [],
  5368. _toRemovedListeners: [],
  5369. _dirtyNodes: [],
  5370. _inDispatch: 0,
  5371. _isEnabled: false,
  5372. _nodePriorityIndex: 0,
  5373. _internalCustomListenerIDs:[cc.game.EVENT_HIDE, cc.game.EVENT_SHOW],
  5374. _setDirtyForNode: function (node) {
  5375. if (this._nodeListenersMap[node.__instanceId] != null)
  5376. this._dirtyNodes.push(node);
  5377. var _children = node.getChildren();
  5378. for(var i = 0, len = _children.length; i < len; i++)
  5379. this._setDirtyForNode(_children[i]);
  5380. },
  5381. pauseTarget: function (node, recursive) {
  5382. var listeners = this._nodeListenersMap[node.__instanceId], i, len;
  5383. if (listeners) {
  5384. for ( i = 0, len = listeners.length; i < len; i++)
  5385. listeners[i]._setPaused(true);
  5386. }
  5387. if (recursive === true) {
  5388. var locChildren = node.getChildren();
  5389. for ( i = 0, len = locChildren.length; i< len; i++)
  5390. this.pauseTarget(locChildren[i], true);
  5391. }
  5392. },
  5393. resumeTarget: function (node, recursive) {
  5394. var listeners = this._nodeListenersMap[node.__instanceId], i, len;
  5395. if (listeners){
  5396. for ( i = 0, len = listeners.length; i < len; i++)
  5397. listeners[i]._setPaused(false);
  5398. }
  5399. this._setDirtyForNode(node);
  5400. if (recursive === true) {
  5401. var locChildren = node.getChildren();
  5402. for ( i = 0, len = locChildren.length; i< len; i++)
  5403. this.resumeTarget(locChildren[i], true);
  5404. }
  5405. },
  5406. _addListener: function (listener) {
  5407. if (this._inDispatch === 0)
  5408. this._forceAddEventListener(listener);
  5409. else
  5410. this._toAddedListeners.push(listener);
  5411. },
  5412. _forceAddEventListener: function (listener) {
  5413. var listenerID = listener._getListenerID();
  5414. var listeners = this._listenersMap[listenerID];
  5415. if (!listeners) {
  5416. listeners = new cc._EventListenerVector();
  5417. this._listenersMap[listenerID] = listeners;
  5418. }
  5419. listeners.push(listener);
  5420. if (listener._getFixedPriority() === 0) {
  5421. this._setDirty(listenerID, this.DIRTY_SCENE_GRAPH_PRIORITY);
  5422. var node = listener._getSceneGraphPriority();
  5423. if (node === null)
  5424. cc.log(cc._LogInfos.eventManager__forceAddEventListener);
  5425. this._associateNodeAndEventListener(node, listener);
  5426. if (node.isRunning())
  5427. this.resumeTarget(node);
  5428. } else
  5429. this._setDirty(listenerID, this.DIRTY_FIXED_PRIORITY);
  5430. },
  5431. _getListeners: function (listenerID) {
  5432. return this._listenersMap[listenerID];
  5433. },
  5434. _updateDirtyFlagForSceneGraph: function () {
  5435. if (this._dirtyNodes.length === 0)
  5436. return;
  5437. var locDirtyNodes = this._dirtyNodes, selListeners, selListener, locNodeListenersMap = this._nodeListenersMap;
  5438. for (var i = 0, len = locDirtyNodes.length; i < len; i++) {
  5439. selListeners = locNodeListenersMap[locDirtyNodes[i].__instanceId];
  5440. if (selListeners) {
  5441. for (var j = 0, listenersLen = selListeners.length; j < listenersLen; j++) {
  5442. selListener = selListeners[j];
  5443. if (selListener)
  5444. this._setDirty(selListener._getListenerID(), this.DIRTY_SCENE_GRAPH_PRIORITY);
  5445. }
  5446. }
  5447. }
  5448. this._dirtyNodes.length = 0;
  5449. },
  5450. _removeAllListenersInVector: function (listenerVector) {
  5451. if (!listenerVector)
  5452. return;
  5453. var selListener;
  5454. for (var i = 0; i < listenerVector.length;) {
  5455. selListener = listenerVector[i];
  5456. selListener._setRegistered(false);
  5457. if (selListener._getSceneGraphPriority() != null){
  5458. this._dissociateNodeAndEventListener(selListener._getSceneGraphPriority(), selListener);
  5459. selListener._setSceneGraphPriority(null);
  5460. }
  5461. if (this._inDispatch === 0)
  5462. cc.arrayRemoveObject(listenerVector, selListener);
  5463. else
  5464. ++i;
  5465. }
  5466. },
  5467. _removeListenersForListenerID: function (listenerID) {
  5468. var listeners = this._listenersMap[listenerID], i;
  5469. if (listeners) {
  5470. var fixedPriorityListeners = listeners.getFixedPriorityListeners();
  5471. var sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners();
  5472. this._removeAllListenersInVector(sceneGraphPriorityListeners);
  5473. this._removeAllListenersInVector(fixedPriorityListeners);
  5474. delete this._priorityDirtyFlagMap[listenerID];
  5475. if (!this._inDispatch) {
  5476. listeners.clear();
  5477. delete this._listenersMap[listenerID];
  5478. }
  5479. }
  5480. var locToAddedListeners = this._toAddedListeners, listener;
  5481. for (i = 0; i < locToAddedListeners.length;) {
  5482. listener = locToAddedListeners[i];
  5483. if (listener && listener._getListenerID() === listenerID)
  5484. cc.arrayRemoveObject(locToAddedListeners, listener);
  5485. else
  5486. ++i;
  5487. }
  5488. },
  5489. _sortEventListeners: function (listenerID) {
  5490. var dirtyFlag = this.DIRTY_NONE, locFlagMap = this._priorityDirtyFlagMap;
  5491. if (locFlagMap[listenerID])
  5492. dirtyFlag = locFlagMap[listenerID];
  5493. if (dirtyFlag !== this.DIRTY_NONE) {
  5494. locFlagMap[listenerID] = this.DIRTY_NONE;
  5495. if (dirtyFlag & this.DIRTY_FIXED_PRIORITY)
  5496. this._sortListenersOfFixedPriority(listenerID);
  5497. if (dirtyFlag & this.DIRTY_SCENE_GRAPH_PRIORITY){
  5498. var rootNode = cc.director.getRunningScene();
  5499. if(rootNode)
  5500. this._sortListenersOfSceneGraphPriority(listenerID, rootNode);
  5501. else
  5502. locFlagMap[listenerID] = this.DIRTY_SCENE_GRAPH_PRIORITY;
  5503. }
  5504. }
  5505. },
  5506. _sortListenersOfSceneGraphPriority: function (listenerID, rootNode) {
  5507. var listeners = this._getListeners(listenerID);
  5508. if (!listeners)
  5509. return;
  5510. var sceneGraphListener = listeners.getSceneGraphPriorityListeners();
  5511. if(!sceneGraphListener || sceneGraphListener.length === 0)
  5512. return;
  5513. this._nodePriorityIndex = 0;
  5514. this._nodePriorityMap = {};
  5515. this._visitTarget(rootNode, true);
  5516. listeners.getSceneGraphPriorityListeners().sort(this._sortEventListenersOfSceneGraphPriorityDes);
  5517. },
  5518. _sortEventListenersOfSceneGraphPriorityDes : function(l1, l2){
  5519. var locNodePriorityMap = cc.eventManager._nodePriorityMap, node1 = l1._getSceneGraphPriority(),
  5520. node2 = l2._getSceneGraphPriority();
  5521. if( !l2 || !node2 || !locNodePriorityMap[node2.__instanceId] )
  5522. return -1;
  5523. else if( !l1 || !node1 || !locNodePriorityMap[node1.__instanceId] )
  5524. return 1;
  5525. return locNodePriorityMap[l2._getSceneGraphPriority().__instanceId] - locNodePriorityMap[l1._getSceneGraphPriority().__instanceId];
  5526. },
  5527. _sortListenersOfFixedPriority: function (listenerID) {
  5528. var listeners = this._listenersMap[listenerID];
  5529. if (!listeners)
  5530. return;
  5531. var fixedListeners = listeners.getFixedPriorityListeners();
  5532. if(!fixedListeners || fixedListeners.length === 0)
  5533. return;
  5534. fixedListeners.sort(this._sortListenersOfFixedPriorityAsc);
  5535. var index = 0;
  5536. for (var len = fixedListeners.length; index < len;) {
  5537. if (fixedListeners[index]._getFixedPriority() >= 0)
  5538. break;
  5539. ++index;
  5540. }
  5541. listeners.gt0Index = index;
  5542. },
  5543. _sortListenersOfFixedPriorityAsc: function (l1, l2) {
  5544. return l1._getFixedPriority() - l2._getFixedPriority();
  5545. },
  5546. _onUpdateListeners: function (listenerID) {
  5547. var listeners = this._listenersMap[listenerID];
  5548. if (!listeners)
  5549. return;
  5550. var fixedPriorityListeners = listeners.getFixedPriorityListeners();
  5551. var sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners();
  5552. var i, selListener, idx, toRemovedListeners = this._toRemovedListeners;
  5553. if (sceneGraphPriorityListeners) {
  5554. for (i = 0; i < sceneGraphPriorityListeners.length;) {
  5555. selListener = sceneGraphPriorityListeners[i];
  5556. if (!selListener._isRegistered()) {
  5557. cc.arrayRemoveObject(sceneGraphPriorityListeners, selListener);
  5558. idx = toRemovedListeners.indexOf(selListener);
  5559. if(idx !== -1)
  5560. toRemovedListeners.splice(idx, 1);
  5561. } else
  5562. ++i;
  5563. }
  5564. }
  5565. if (fixedPriorityListeners) {
  5566. for (i = 0; i < fixedPriorityListeners.length;) {
  5567. selListener = fixedPriorityListeners[i];
  5568. if (!selListener._isRegistered()) {
  5569. cc.arrayRemoveObject(fixedPriorityListeners, selListener);
  5570. idx = toRemovedListeners.indexOf(selListener);
  5571. if(idx !== -1)
  5572. toRemovedListeners.splice(idx, 1);
  5573. } else
  5574. ++i;
  5575. }
  5576. }
  5577. if (sceneGraphPriorityListeners && sceneGraphPriorityListeners.length === 0)
  5578. listeners.clearSceneGraphListeners();
  5579. if (fixedPriorityListeners && fixedPriorityListeners.length === 0)
  5580. listeners.clearFixedListeners();
  5581. },
  5582. _updateListeners: function (event) {
  5583. var locInDispatch = this._inDispatch;
  5584. cc.assert(locInDispatch > 0, cc._LogInfos.EventManager__updateListeners);
  5585. if(locInDispatch > 1)
  5586. return;
  5587. if (event.getType() === cc.Event.TOUCH) {
  5588. this._onUpdateListeners(cc._EventListenerTouchOneByOne.LISTENER_ID);
  5589. this._onUpdateListeners(cc._EventListenerTouchAllAtOnce.LISTENER_ID);
  5590. } else
  5591. this._onUpdateListeners(cc.__getListenerID(event));
  5592. cc.assert(locInDispatch === 1, cc._LogInfos.EventManager__updateListeners_2);
  5593. var locListenersMap = this._listenersMap, locPriorityDirtyFlagMap = this._priorityDirtyFlagMap;
  5594. for (var selKey in locListenersMap) {
  5595. if (locListenersMap[selKey].empty()) {
  5596. delete locPriorityDirtyFlagMap[selKey];
  5597. delete locListenersMap[selKey];
  5598. }
  5599. }
  5600. var locToAddedListeners = this._toAddedListeners;
  5601. if (locToAddedListeners.length !== 0) {
  5602. for (var i = 0, len = locToAddedListeners.length; i < len; i++)
  5603. this._forceAddEventListener(locToAddedListeners[i]);
  5604. this._toAddedListeners.length = 0;
  5605. }
  5606. if(this._toRemovedListeners.length !== 0)
  5607. this._cleanToRemovedListeners();
  5608. },
  5609. _cleanToRemovedListeners: function(){
  5610. var toRemovedListeners = this._toRemovedListeners;
  5611. for(var i = 0; i< toRemovedListeners.length; i++){
  5612. var selListener = toRemovedListeners[i];
  5613. var listeners = this._listenersMap[selListener._getListenerID()];
  5614. if(!listeners)
  5615. continue;
  5616. var idx, fixedPriorityListeners = listeners.getFixedPriorityListeners(),
  5617. sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners();
  5618. if(sceneGraphPriorityListeners){
  5619. idx = sceneGraphPriorityListeners.indexOf(selListener);
  5620. if (idx !== -1) {
  5621. sceneGraphPriorityListeners.splice(idx, 1);
  5622. }
  5623. }
  5624. if(fixedPriorityListeners){
  5625. idx = fixedPriorityListeners.indexOf(selListener);
  5626. if (idx !== -1) {
  5627. fixedPriorityListeners.splice(idx, 1);
  5628. }
  5629. }
  5630. }
  5631. toRemovedListeners.length = 0;
  5632. },
  5633. _onTouchEventCallback: function(listener, argsObj){
  5634. if (!listener._isRegistered)
  5635. return false;
  5636. var event = argsObj.event, selTouch = argsObj.selTouch;
  5637. event._setCurrentTarget(listener._node);
  5638. var isClaimed = false, removedIdx;
  5639. var getCode = event.getEventCode(), eventCode = cc.EventTouch.EventCode;
  5640. if (getCode === eventCode.BEGAN) {
  5641. if (listener.onTouchBegan) {
  5642. isClaimed = listener.onTouchBegan(selTouch, event);
  5643. if (isClaimed && listener._registered)
  5644. listener._claimedTouches.push(selTouch);
  5645. }
  5646. } else if (listener._claimedTouches.length > 0
  5647. && ((removedIdx = listener._claimedTouches.indexOf(selTouch)) !== -1)) {
  5648. isClaimed = true;
  5649. if(getCode === eventCode.MOVED && listener.onTouchMoved){
  5650. listener.onTouchMoved(selTouch, event);
  5651. } else if(getCode === eventCode.ENDED){
  5652. if (listener.onTouchEnded)
  5653. listener.onTouchEnded(selTouch, event);
  5654. if (listener._registered)
  5655. listener._claimedTouches.splice(removedIdx, 1);
  5656. } else if(getCode === eventCode.CANCELLED){
  5657. if (listener.onTouchCancelled)
  5658. listener.onTouchCancelled(selTouch, event);
  5659. if (listener._registered)
  5660. listener._claimedTouches.splice(removedIdx, 1);
  5661. }
  5662. }
  5663. if (event.isStopped()) {
  5664. cc.eventManager._updateListeners(event);
  5665. return true;
  5666. }
  5667. if (isClaimed && listener._registered && listener.swallowTouches) {
  5668. if (argsObj.needsMutableSet)
  5669. argsObj.touches.splice(selTouch, 1);
  5670. return true;
  5671. }
  5672. return false;
  5673. },
  5674. _dispatchTouchEvent: function (event) {
  5675. this._sortEventListeners(cc._EventListenerTouchOneByOne.LISTENER_ID);
  5676. this._sortEventListeners(cc._EventListenerTouchAllAtOnce.LISTENER_ID);
  5677. var oneByOneListeners = this._getListeners(cc._EventListenerTouchOneByOne.LISTENER_ID);
  5678. var allAtOnceListeners = this._getListeners(cc._EventListenerTouchAllAtOnce.LISTENER_ID);
  5679. if (null === oneByOneListeners && null === allAtOnceListeners)
  5680. return;
  5681. var originalTouches = event.getTouches(), mutableTouches = cc.copyArray(originalTouches);
  5682. var oneByOneArgsObj = {event: event, needsMutableSet: (oneByOneListeners && allAtOnceListeners), touches: mutableTouches, selTouch: null};
  5683. if (oneByOneListeners) {
  5684. for (var i = 0; i < originalTouches.length; i++) {
  5685. oneByOneArgsObj.selTouch = originalTouches[i];
  5686. this._dispatchEventToListeners(oneByOneListeners, this._onTouchEventCallback, oneByOneArgsObj);
  5687. if (event.isStopped())
  5688. return;
  5689. }
  5690. }
  5691. if (allAtOnceListeners && mutableTouches.length > 0) {
  5692. this._dispatchEventToListeners(allAtOnceListeners, this._onTouchesEventCallback, {event: event, touches: mutableTouches});
  5693. if (event.isStopped())
  5694. return;
  5695. }
  5696. this._updateListeners(event);
  5697. },
  5698. _onTouchesEventCallback: function (listener, callbackParams) {
  5699. if (!listener._registered)
  5700. return false;
  5701. var eventCode = cc.EventTouch.EventCode, event = callbackParams.event, touches = callbackParams.touches, getCode = event.getEventCode();
  5702. event._setCurrentTarget(listener._node);
  5703. if(getCode === eventCode.BEGAN && listener.onTouchesBegan)
  5704. listener.onTouchesBegan(touches, event);
  5705. else if(getCode === eventCode.MOVED && listener.onTouchesMoved)
  5706. listener.onTouchesMoved(touches, event);
  5707. else if(getCode === eventCode.ENDED && listener.onTouchesEnded)
  5708. listener.onTouchesEnded(touches, event);
  5709. else if(getCode === eventCode.CANCELLED && listener.onTouchesCancelled)
  5710. listener.onTouchesCancelled(touches, event);
  5711. if (event.isStopped()) {
  5712. cc.eventManager._updateListeners(event);
  5713. return true;
  5714. }
  5715. return false;
  5716. },
  5717. _associateNodeAndEventListener: function (node, listener) {
  5718. var listeners = this._nodeListenersMap[node.__instanceId];
  5719. if (!listeners) {
  5720. listeners = [];
  5721. this._nodeListenersMap[node.__instanceId] = listeners;
  5722. }
  5723. listeners.push(listener);
  5724. },
  5725. _dissociateNodeAndEventListener: function (node, listener) {
  5726. var listeners = this._nodeListenersMap[node.__instanceId];
  5727. if (listeners) {
  5728. cc.arrayRemoveObject(listeners, listener);
  5729. if (listeners.length === 0)
  5730. delete this._nodeListenersMap[node.__instanceId];
  5731. }
  5732. },
  5733. _dispatchEventToListeners: function (listeners, onEvent, eventOrArgs) {
  5734. var shouldStopPropagation = false;
  5735. var fixedPriorityListeners = listeners.getFixedPriorityListeners();
  5736. var sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners();
  5737. var i = 0, j, selListener;
  5738. if (fixedPriorityListeners) {
  5739. if (fixedPriorityListeners.length !== 0) {
  5740. for (; i < listeners.gt0Index; ++i) {
  5741. selListener = fixedPriorityListeners[i];
  5742. if (selListener.isEnabled() && !selListener._isPaused() && selListener._isRegistered() && onEvent(selListener, eventOrArgs)) {
  5743. shouldStopPropagation = true;
  5744. break;
  5745. }
  5746. }
  5747. }
  5748. }
  5749. if (sceneGraphPriorityListeners && !shouldStopPropagation) {
  5750. for (j = 0; j < sceneGraphPriorityListeners.length; j++) {
  5751. selListener = sceneGraphPriorityListeners[j];
  5752. if (selListener.isEnabled() && !selListener._isPaused() && selListener._isRegistered() && onEvent(selListener, eventOrArgs)) {
  5753. shouldStopPropagation = true;
  5754. break;
  5755. }
  5756. }
  5757. }
  5758. if (fixedPriorityListeners && !shouldStopPropagation) {
  5759. for (; i < fixedPriorityListeners.length; ++i) {
  5760. selListener = fixedPriorityListeners[i];
  5761. if (selListener.isEnabled() && !selListener._isPaused() && selListener._isRegistered() && onEvent(selListener, eventOrArgs)) {
  5762. shouldStopPropagation = true;
  5763. break;
  5764. }
  5765. }
  5766. }
  5767. },
  5768. _setDirty: function (listenerID, flag) {
  5769. var locDirtyFlagMap = this._priorityDirtyFlagMap;
  5770. if (locDirtyFlagMap[listenerID] == null)
  5771. locDirtyFlagMap[listenerID] = flag;
  5772. else
  5773. locDirtyFlagMap[listenerID] = flag | locDirtyFlagMap[listenerID];
  5774. },
  5775. _visitTarget: function (node, isRootNode) {
  5776. var children = node.getChildren(), i = 0;
  5777. var childrenCount = children.length, locGlobalZOrderNodeMap = this._globalZOrderNodeMap, locNodeListenersMap = this._nodeListenersMap;
  5778. if (childrenCount > 0) {
  5779. var child;
  5780. for (; i < childrenCount; i++) {
  5781. child = children[i];
  5782. if (child && child.getLocalZOrder() < 0)
  5783. this._visitTarget(child, false);
  5784. else
  5785. break;
  5786. }
  5787. if (locNodeListenersMap[node.__instanceId] != null) {
  5788. if (!locGlobalZOrderNodeMap[node.getGlobalZOrder()])
  5789. locGlobalZOrderNodeMap[node.getGlobalZOrder()] = [];
  5790. locGlobalZOrderNodeMap[node.getGlobalZOrder()].push(node.__instanceId);
  5791. }
  5792. for (; i < childrenCount; i++) {
  5793. child = children[i];
  5794. if (child)
  5795. this._visitTarget(child, false);
  5796. }
  5797. } else {
  5798. if (locNodeListenersMap[node.__instanceId] != null) {
  5799. if (!locGlobalZOrderNodeMap[node.getGlobalZOrder()])
  5800. locGlobalZOrderNodeMap[node.getGlobalZOrder()] = [];
  5801. locGlobalZOrderNodeMap[node.getGlobalZOrder()].push(node.__instanceId);
  5802. }
  5803. }
  5804. if (isRootNode) {
  5805. var globalZOrders = [];
  5806. for (var selKey in locGlobalZOrderNodeMap)
  5807. globalZOrders.push(selKey);
  5808. globalZOrders.sort(this._sortNumberAsc);
  5809. var zOrdersLen = globalZOrders.length, selZOrders, j, locNodePriorityMap = this._nodePriorityMap;
  5810. for (i = 0; i < zOrdersLen; i++) {
  5811. selZOrders = locGlobalZOrderNodeMap[globalZOrders[i]];
  5812. for (j = 0; j < selZOrders.length; j++)
  5813. locNodePriorityMap[selZOrders[j]] = ++this._nodePriorityIndex;
  5814. }
  5815. this._globalZOrderNodeMap = {};
  5816. }
  5817. },
  5818. _sortNumberAsc : function (a, b) {
  5819. return a - b;
  5820. },
  5821. addListener: function (listener, nodeOrPriority) {
  5822. cc.assert(listener && nodeOrPriority, cc._LogInfos.eventManager_addListener_2);
  5823. if(!(listener instanceof cc.EventListener)){
  5824. cc.assert(!cc.isNumber(nodeOrPriority), cc._LogInfos.eventManager_addListener_3);
  5825. listener = cc.EventListener.create(listener);
  5826. } else {
  5827. if(listener._isRegistered()){
  5828. cc.log(cc._LogInfos.eventManager_addListener_4);
  5829. return;
  5830. }
  5831. }
  5832. if (!listener.checkAvailable())
  5833. return;
  5834. if (cc.isNumber(nodeOrPriority)) {
  5835. if (nodeOrPriority === 0) {
  5836. cc.log(cc._LogInfos.eventManager_addListener);
  5837. return;
  5838. }
  5839. listener._setSceneGraphPriority(null);
  5840. listener._setFixedPriority(nodeOrPriority);
  5841. listener._setRegistered(true);
  5842. listener._setPaused(false);
  5843. this._addListener(listener);
  5844. } else {
  5845. listener._setSceneGraphPriority(nodeOrPriority);
  5846. listener._setFixedPriority(0);
  5847. listener._setRegistered(true);
  5848. this._addListener(listener);
  5849. }
  5850. return listener;
  5851. },
  5852. addCustomListener: function (eventName, callback) {
  5853. var listener = new cc._EventListenerCustom(eventName, callback);
  5854. this.addListener(listener, 1);
  5855. return listener;
  5856. },
  5857. removeListener: function (listener) {
  5858. if (listener == null)
  5859. return;
  5860. var isFound, locListener = this._listenersMap;
  5861. for (var selKey in locListener) {
  5862. var listeners = locListener[selKey];
  5863. var fixedPriorityListeners = listeners.getFixedPriorityListeners(), sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners();
  5864. isFound = this._removeListenerInVector(sceneGraphPriorityListeners, listener);
  5865. if (isFound){
  5866. this._setDirty(listener._getListenerID(), this.DIRTY_SCENE_GRAPH_PRIORITY);
  5867. }else{
  5868. isFound = this._removeListenerInVector(fixedPriorityListeners, listener);
  5869. if (isFound)
  5870. this._setDirty(listener._getListenerID(), this.DIRTY_FIXED_PRIORITY);
  5871. }
  5872. if (listeners.empty()) {
  5873. delete this._priorityDirtyFlagMap[listener._getListenerID()];
  5874. delete locListener[selKey];
  5875. }
  5876. if (isFound)
  5877. break;
  5878. }
  5879. if (!isFound) {
  5880. var locToAddedListeners = this._toAddedListeners;
  5881. for (var i = 0, len = locToAddedListeners.length; i < len; i++) {
  5882. var selListener = locToAddedListeners[i];
  5883. if (selListener === listener) {
  5884. cc.arrayRemoveObject(locToAddedListeners, selListener);
  5885. selListener._setRegistered(false);
  5886. break;
  5887. }
  5888. }
  5889. }
  5890. },
  5891. _removeListenerInCallback: function(listeners, callback){
  5892. if (listeners == null)
  5893. return false;
  5894. for (var i = 0, len = listeners.length; i < len; i++) {
  5895. var selListener = listeners[i];
  5896. if (selListener._onCustomEvent === callback || selListener._onEvent === callback) {
  5897. selListener._setRegistered(false);
  5898. if (selListener._getSceneGraphPriority() != null){
  5899. this._dissociateNodeAndEventListener(selListener._getSceneGraphPriority(), selListener);
  5900. selListener._setSceneGraphPriority(null);
  5901. }
  5902. if (this._inDispatch === 0)
  5903. cc.arrayRemoveObject(listeners, selListener);
  5904. return true;
  5905. }
  5906. }
  5907. return false;
  5908. },
  5909. _removeListenerInVector : function(listeners, listener){
  5910. if (listeners == null)
  5911. return false;
  5912. for (var i = 0, len = listeners.length; i < len; i++) {
  5913. var selListener = listeners[i];
  5914. if (selListener === listener) {
  5915. selListener._setRegistered(false);
  5916. if (selListener._getSceneGraphPriority() != null){
  5917. this._dissociateNodeAndEventListener(selListener._getSceneGraphPriority(), selListener);
  5918. selListener._setSceneGraphPriority(null);
  5919. }
  5920. if (this._inDispatch === 0)
  5921. cc.arrayRemoveObject(listeners, selListener);
  5922. else
  5923. this._toRemovedListeners.push(selListener);
  5924. return true;
  5925. }
  5926. }
  5927. return false;
  5928. },
  5929. removeListeners: function (listenerType, recursive) {
  5930. var _t = this;
  5931. if (listenerType instanceof cc.Node) {
  5932. delete _t._nodePriorityMap[listenerType.__instanceId];
  5933. cc.arrayRemoveObject(_t._dirtyNodes, listenerType);
  5934. var listeners = _t._nodeListenersMap[listenerType.__instanceId], i;
  5935. if (listeners) {
  5936. var listenersCopy = cc.copyArray(listeners);
  5937. for (i = 0; i < listenersCopy.length; i++)
  5938. _t.removeListener(listenersCopy[i]);
  5939. listenersCopy.length = 0;
  5940. }
  5941. var locToAddedListeners = _t._toAddedListeners;
  5942. for (i = 0; i < locToAddedListeners.length; ) {
  5943. var listener = locToAddedListeners[i];
  5944. if (listener._getSceneGraphPriority() === listenerType) {
  5945. listener._setSceneGraphPriority(null);
  5946. listener._setRegistered(false);
  5947. locToAddedListeners.splice(i, 1);
  5948. } else
  5949. ++i;
  5950. }
  5951. if (recursive === true) {
  5952. var locChildren = listenerType.getChildren(), len;
  5953. for (i = 0, len = locChildren.length; i< len; i++)
  5954. _t.removeListeners(locChildren[i], true);
  5955. }
  5956. } else {
  5957. if (listenerType === cc.EventListener.TOUCH_ONE_BY_ONE)
  5958. _t._removeListenersForListenerID(cc._EventListenerTouchOneByOne.LISTENER_ID);
  5959. else if (listenerType === cc.EventListener.TOUCH_ALL_AT_ONCE)
  5960. _t._removeListenersForListenerID(cc._EventListenerTouchAllAtOnce.LISTENER_ID);
  5961. else if (listenerType === cc.EventListener.MOUSE)
  5962. _t._removeListenersForListenerID(cc._EventListenerMouse.LISTENER_ID);
  5963. else if (listenerType === cc.EventListener.ACCELERATION)
  5964. _t._removeListenersForListenerID(cc._EventListenerAcceleration.LISTENER_ID);
  5965. else if (listenerType === cc.EventListener.KEYBOARD)
  5966. _t._removeListenersForListenerID(cc._EventListenerKeyboard.LISTENER_ID);
  5967. else
  5968. cc.log(cc._LogInfos.eventManager_removeListeners);
  5969. }
  5970. },
  5971. removeCustomListeners: function (customEventName) {
  5972. this._removeListenersForListenerID(customEventName);
  5973. },
  5974. removeAllListeners: function () {
  5975. var locListeners = this._listenersMap, locInternalCustomEventIDs = this._internalCustomListenerIDs;
  5976. for (var selKey in locListeners){
  5977. if(locInternalCustomEventIDs.indexOf(selKey) === -1)
  5978. this._removeListenersForListenerID(selKey);
  5979. }
  5980. },
  5981. setPriority: function (listener, fixedPriority) {
  5982. if (listener == null)
  5983. return;
  5984. var locListeners = this._listenersMap;
  5985. for (var selKey in locListeners) {
  5986. var selListeners = locListeners[selKey];
  5987. var fixedPriorityListeners = selListeners.getFixedPriorityListeners();
  5988. if (fixedPriorityListeners) {
  5989. var found = fixedPriorityListeners.indexOf(listener);
  5990. if (found !== -1) {
  5991. if(listener._getSceneGraphPriority() != null)
  5992. cc.log(cc._LogInfos.eventManager_setPriority);
  5993. if (listener._getFixedPriority() !== fixedPriority) {
  5994. listener._setFixedPriority(fixedPriority);
  5995. this._setDirty(listener._getListenerID(), this.DIRTY_FIXED_PRIORITY);
  5996. }
  5997. return;
  5998. }
  5999. }
  6000. }
  6001. },
  6002. setEnabled: function (enabled) {
  6003. this._isEnabled = enabled;
  6004. },
  6005. isEnabled: function () {
  6006. return this._isEnabled;
  6007. },
  6008. dispatchEvent: function (event) {
  6009. if (!this._isEnabled)
  6010. return;
  6011. this._updateDirtyFlagForSceneGraph();
  6012. this._inDispatch++;
  6013. if(!event || !event.getType)
  6014. throw new Error("event is undefined");
  6015. if (event.getType() === cc.Event.TOUCH) {
  6016. this._dispatchTouchEvent(event);
  6017. this._inDispatch--;
  6018. return;
  6019. }
  6020. var listenerID = cc.__getListenerID(event);
  6021. this._sortEventListeners(listenerID);
  6022. var selListeners = this._listenersMap[listenerID];
  6023. if (selListeners != null)
  6024. this._dispatchEventToListeners(selListeners, this._onListenerCallback, event);
  6025. this._updateListeners(event);
  6026. this._inDispatch--;
  6027. },
  6028. _onListenerCallback: function(listener, event){
  6029. event._setCurrentTarget(listener._getSceneGraphPriority());
  6030. listener._onEvent(event);
  6031. return event.isStopped();
  6032. },
  6033. dispatchCustomEvent: function (eventName, optionalUserData) {
  6034. var ev = new cc.EventCustom(eventName);
  6035. ev.setUserData(optionalUserData);
  6036. this.dispatchEvent(ev);
  6037. }
  6038. };
  6039. cc._tmp.PrototypeCCNode = function () {
  6040. var _p = cc.Node.prototype;
  6041. cc.defineGetterSetter(_p, "x", _p.getPositionX, _p.setPositionX);
  6042. cc.defineGetterSetter(_p, "y", _p.getPositionY, _p.setPositionY);
  6043. _p.width;
  6044. cc.defineGetterSetter(_p, "width", _p._getWidth, _p._setWidth);
  6045. _p.height;
  6046. cc.defineGetterSetter(_p, "height", _p._getHeight, _p._setHeight);
  6047. _p.anchorX;
  6048. cc.defineGetterSetter(_p, "anchorX", _p._getAnchorX, _p._setAnchorX);
  6049. _p.anchorY;
  6050. cc.defineGetterSetter(_p, "anchorY", _p._getAnchorY, _p._setAnchorY);
  6051. _p.skewX;
  6052. cc.defineGetterSetter(_p, "skewX", _p.getSkewX, _p.setSkewX);
  6053. _p.skewY;
  6054. cc.defineGetterSetter(_p, "skewY", _p.getSkewY, _p.setSkewY);
  6055. _p.zIndex;
  6056. cc.defineGetterSetter(_p, "zIndex", _p.getLocalZOrder, _p.setLocalZOrder);
  6057. _p.vertexZ;
  6058. cc.defineGetterSetter(_p, "vertexZ", _p.getVertexZ, _p.setVertexZ);
  6059. _p.rotation;
  6060. cc.defineGetterSetter(_p, "rotation", _p.getRotation, _p.setRotation);
  6061. _p.rotationX;
  6062. cc.defineGetterSetter(_p, "rotationX", _p.getRotationX, _p.setRotationX);
  6063. _p.rotationY;
  6064. cc.defineGetterSetter(_p, "rotationY", _p.getRotationY, _p.setRotationY);
  6065. _p.scale;
  6066. cc.defineGetterSetter(_p, "scale", _p.getScale, _p.setScale);
  6067. _p.scaleX;
  6068. cc.defineGetterSetter(_p, "scaleX", _p.getScaleX, _p.setScaleX);
  6069. _p.scaleY;
  6070. cc.defineGetterSetter(_p, "scaleY", _p.getScaleY, _p.setScaleY);
  6071. _p.children;
  6072. cc.defineGetterSetter(_p, "children", _p.getChildren);
  6073. _p.childrenCount;
  6074. cc.defineGetterSetter(_p, "childrenCount", _p.getChildrenCount);
  6075. _p.parent;
  6076. cc.defineGetterSetter(_p, "parent", _p.getParent, _p.setParent);
  6077. _p.visible;
  6078. cc.defineGetterSetter(_p, "visible", _p.isVisible, _p.setVisible);
  6079. _p.running;
  6080. cc.defineGetterSetter(_p, "running", _p.isRunning);
  6081. _p.ignoreAnchor;
  6082. cc.defineGetterSetter(_p, "ignoreAnchor", _p.isIgnoreAnchorPointForPosition, _p.ignoreAnchorPointForPosition);
  6083. _p.tag;
  6084. _p.userData;
  6085. _p.userObject;
  6086. _p.arrivalOrder;
  6087. _p.actionManager;
  6088. cc.defineGetterSetter(_p, "actionManager", _p.getActionManager, _p.setActionManager);
  6089. _p.scheduler;
  6090. cc.defineGetterSetter(_p, "scheduler", _p.getScheduler, _p.setScheduler);
  6091. _p.shaderProgram;
  6092. cc.defineGetterSetter(_p, "shaderProgram", _p.getShaderProgram, _p.setShaderProgram);
  6093. _p.opacity;
  6094. cc.defineGetterSetter(_p, "opacity", _p.getOpacity, _p.setOpacity);
  6095. _p.opacityModifyRGB;
  6096. cc.defineGetterSetter(_p, "opacityModifyRGB", _p.isOpacityModifyRGB);
  6097. _p.cascadeOpacity;
  6098. cc.defineGetterSetter(_p, "cascadeOpacity", _p.isCascadeOpacityEnabled, _p.setCascadeOpacityEnabled);
  6099. _p.color;
  6100. cc.defineGetterSetter(_p, "color", _p.getColor, _p.setColor);
  6101. _p.cascadeColor;
  6102. cc.defineGetterSetter(_p, "cascadeColor", _p.isCascadeColorEnabled, _p.setCascadeColorEnabled);
  6103. };
  6104. cc.NODE_TAG_INVALID = -1;
  6105. cc.s_globalOrderOfArrival = 1;
  6106. cc.Node = cc.Class.extend({
  6107. _localZOrder: 0,
  6108. _globalZOrder: 0,
  6109. _vertexZ: 0.0,
  6110. _customZ: NaN,
  6111. _rotationX: 0,
  6112. _rotationY: 0.0,
  6113. _scaleX: 1.0,
  6114. _scaleY: 1.0,
  6115. _position: null,
  6116. _normalizedPosition:null,
  6117. _usingNormalizedPosition: false,
  6118. _normalizedPositionDirty: false,
  6119. _skewX: 0.0,
  6120. _skewY: 0.0,
  6121. _children: null,
  6122. _visible: true,
  6123. _anchorPoint: null,
  6124. _contentSize: null,
  6125. _running: false,
  6126. _parent: null,
  6127. _ignoreAnchorPointForPosition: false,
  6128. tag: cc.NODE_TAG_INVALID,
  6129. userData: null,
  6130. userObject: null,
  6131. _reorderChildDirty: false,
  6132. _shaderProgram: null,
  6133. arrivalOrder: 0,
  6134. _actionManager: null,
  6135. _scheduler: null,
  6136. _eventDispatcher: null,
  6137. _additionalTransformDirty: false,
  6138. _additionalTransform: null,
  6139. _componentContainer: null,
  6140. _isTransitionFinished: false,
  6141. _className: "Node",
  6142. _showNode: false,
  6143. _name: "",
  6144. _realOpacity: 255,
  6145. _realColor: null,
  6146. _cascadeColorEnabled: false,
  6147. _cascadeOpacityEnabled: false,
  6148. _renderCmd:null,
  6149. ctor: function(){
  6150. this._initNode();
  6151. this._initRendererCmd();
  6152. },
  6153. _initNode: function () {
  6154. var _t = this;
  6155. _t._anchorPoint = cc.p(0, 0);
  6156. _t._contentSize = cc.size(0, 0);
  6157. _t._position = cc.p(0, 0);
  6158. _t._normalizedPosition = cc.p(0,0);
  6159. _t._children = [];
  6160. var director = cc.director;
  6161. _t._actionManager = director.getActionManager();
  6162. _t._scheduler = director.getScheduler();
  6163. _t._additionalTransform = cc.affineTransformMakeIdentity();
  6164. if (cc.ComponentContainer) {
  6165. _t._componentContainer = new cc.ComponentContainer(_t);
  6166. }
  6167. this._realOpacity = 255;
  6168. this._realColor = cc.color(255, 255, 255, 255);
  6169. this._cascadeColorEnabled = false;
  6170. this._cascadeOpacityEnabled = false;
  6171. },
  6172. init: function () {
  6173. return true;
  6174. },
  6175. _arrayMakeObjectsPerformSelector: function (array, callbackType) {
  6176. if (!array || array.length === 0)
  6177. return;
  6178. var i, len = array.length, node;
  6179. var nodeCallbackType = cc.Node._stateCallbackType;
  6180. switch (callbackType) {
  6181. case nodeCallbackType.onEnter:
  6182. for (i = 0; i < len; i++) {
  6183. node = array[i];
  6184. if (node)
  6185. node.onEnter();
  6186. }
  6187. break;
  6188. case nodeCallbackType.onExit:
  6189. for (i = 0; i < len; i++) {
  6190. node = array[i];
  6191. if (node)
  6192. node.onExit();
  6193. }
  6194. break;
  6195. case nodeCallbackType.onEnterTransitionDidFinish:
  6196. for (i = 0; i < len; i++) {
  6197. node = array[i];
  6198. if (node)
  6199. node.onEnterTransitionDidFinish();
  6200. }
  6201. break;
  6202. case nodeCallbackType.cleanup:
  6203. for (i = 0; i < len; i++) {
  6204. node = array[i];
  6205. if (node)
  6206. node.cleanup();
  6207. }
  6208. break;
  6209. case nodeCallbackType.updateTransform:
  6210. for (i = 0; i < len; i++) {
  6211. node = array[i];
  6212. if (node)
  6213. node.updateTransform();
  6214. }
  6215. break;
  6216. case nodeCallbackType.onExitTransitionDidStart:
  6217. for (i = 0; i < len; i++) {
  6218. node = array[i];
  6219. if (node)
  6220. node.onExitTransitionDidStart();
  6221. }
  6222. break;
  6223. case nodeCallbackType.sortAllChildren:
  6224. for (i = 0; i < len; i++) {
  6225. node = array[i];
  6226. if (node)
  6227. node.sortAllChildren();
  6228. }
  6229. break;
  6230. default :
  6231. cc.assert(0, cc._LogInfos.Node__arrayMakeObjectsPerformSelector);
  6232. break;
  6233. }
  6234. },
  6235. attr: function (attrs) {
  6236. for (var key in attrs) {
  6237. this[key] = attrs[key];
  6238. }
  6239. },
  6240. getSkewX: function () {
  6241. return this._skewX;
  6242. },
  6243. setSkewX: function (newSkewX) {
  6244. this._skewX = newSkewX;
  6245. this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
  6246. },
  6247. getSkewY: function () {
  6248. return this._skewY;
  6249. },
  6250. setSkewY: function (newSkewY) {
  6251. this._skewY = newSkewY;
  6252. this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
  6253. },
  6254. setLocalZOrder: function (localZOrder) {
  6255. this._localZOrder = localZOrder;
  6256. if (this._parent)
  6257. this._parent.reorderChild(this, localZOrder);
  6258. cc.eventManager._setDirtyForNode(this);
  6259. },
  6260. _setLocalZOrder: function (localZOrder) {
  6261. this._localZOrder = localZOrder;
  6262. },
  6263. getLocalZOrder: function () {
  6264. return this._localZOrder;
  6265. },
  6266. getZOrder: function () {
  6267. cc.log(cc._LogInfos.Node_getZOrder);
  6268. return this.getLocalZOrder();
  6269. },
  6270. setZOrder: function (z) {
  6271. cc.log(cc._LogInfos.Node_setZOrder);
  6272. this.setLocalZOrder(z);
  6273. },
  6274. setGlobalZOrder: function (globalZOrder) {
  6275. if (this._globalZOrder !== globalZOrder) {
  6276. this._globalZOrder = globalZOrder;
  6277. cc.eventManager._setDirtyForNode(this);
  6278. }
  6279. },
  6280. getGlobalZOrder: function () {
  6281. return this._globalZOrder;
  6282. },
  6283. getVertexZ: function () {
  6284. return this._vertexZ;
  6285. },
  6286. setVertexZ: function (Var) {
  6287. this._customZ = this._vertexZ = Var;
  6288. },
  6289. getRotation: function () {
  6290. if (this._rotationX !== this._rotationY)
  6291. cc.log(cc._LogInfos.Node_getRotation);
  6292. return this._rotationX;
  6293. },
  6294. setRotation: function (newRotation) {
  6295. this._rotationX = this._rotationY = newRotation;
  6296. this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
  6297. },
  6298. getRotationX: function () {
  6299. return this._rotationX;
  6300. },
  6301. setRotationX: function (rotationX) {
  6302. this._rotationX = rotationX;
  6303. this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
  6304. },
  6305. getRotationY: function () {
  6306. return this._rotationY;
  6307. },
  6308. setRotationY: function (rotationY) {
  6309. this._rotationY = rotationY;
  6310. this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
  6311. },
  6312. getScale: function () {
  6313. if (this._scaleX !== this._scaleY)
  6314. cc.log(cc._LogInfos.Node_getScale);
  6315. return this._scaleX;
  6316. },
  6317. setScale: function (scale, scaleY) {
  6318. this._scaleX = scale;
  6319. this._scaleY = (scaleY || scaleY === 0) ? scaleY : scale;
  6320. this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
  6321. },
  6322. getScaleX: function () {
  6323. return this._scaleX;
  6324. },
  6325. setScaleX: function (newScaleX) {
  6326. this._scaleX = newScaleX;
  6327. this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
  6328. },
  6329. getScaleY: function () {
  6330. return this._scaleY;
  6331. },
  6332. setScaleY: function (newScaleY) {
  6333. this._scaleY = newScaleY;
  6334. this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
  6335. },
  6336. setPosition: function (newPosOrxValue, yValue) {
  6337. var locPosition = this._position;
  6338. if (yValue === undefined) {
  6339. if(locPosition.x === newPosOrxValue.x && locPosition.y === newPosOrxValue.y)
  6340. return;
  6341. locPosition.x = newPosOrxValue.x;
  6342. locPosition.y = newPosOrxValue.y;
  6343. } else {
  6344. if(locPosition.x === newPosOrxValue && locPosition.y === yValue)
  6345. return;
  6346. locPosition.x = newPosOrxValue;
  6347. locPosition.y = yValue;
  6348. }
  6349. this._usingNormalizedPosition = false;
  6350. this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
  6351. },
  6352. setNormalizedPosition: function(posOrX, y){
  6353. var locPosition = this._normalizedPosition;
  6354. if (y === undefined) {
  6355. locPosition.x = posOrX.x;
  6356. locPosition.y = posOrX.y;
  6357. } else {
  6358. locPosition.x = posOrX;
  6359. locPosition.y = y;
  6360. }
  6361. this._normalizedPositionDirty = this._usingNormalizedPosition = true;
  6362. this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
  6363. },
  6364. getPosition: function () {
  6365. return cc.p(this._position);
  6366. },
  6367. getNormalizedPosition: function(){
  6368. return cc.p(this._normalizedPosition);
  6369. },
  6370. getPositionX: function () {
  6371. return this._position.x;
  6372. },
  6373. setPositionX: function (x) {
  6374. this._position.x = x;
  6375. this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
  6376. },
  6377. getPositionY: function () {
  6378. return this._position.y;
  6379. },
  6380. setPositionY: function (y) {
  6381. this._position.y = y;
  6382. this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
  6383. },
  6384. getChildrenCount: function () {
  6385. return this._children.length;
  6386. },
  6387. getChildren: function () {
  6388. return this._children;
  6389. },
  6390. isVisible: function () {
  6391. return this._visible;
  6392. },
  6393. setVisible: function (visible) {
  6394. if(this._visible !== visible){
  6395. this._visible = visible;
  6396. this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
  6397. cc.renderer.childrenOrderDirty = true;
  6398. }
  6399. },
  6400. getAnchorPoint: function () {
  6401. return cc.p(this._anchorPoint);
  6402. },
  6403. setAnchorPoint: function (point, y) {
  6404. var locAnchorPoint = this._anchorPoint;
  6405. if (y === undefined) {
  6406. if ((point.x === locAnchorPoint.x) && (point.y === locAnchorPoint.y))
  6407. return;
  6408. locAnchorPoint.x = point.x;
  6409. locAnchorPoint.y = point.y;
  6410. } else {
  6411. if ((point === locAnchorPoint.x) && (y === locAnchorPoint.y))
  6412. return;
  6413. locAnchorPoint.x = point;
  6414. locAnchorPoint.y = y;
  6415. }
  6416. this._renderCmd._updateAnchorPointInPoint();
  6417. },
  6418. _getAnchorX: function () {
  6419. return this._anchorPoint.x;
  6420. },
  6421. _setAnchorX: function (x) {
  6422. if (this._anchorPoint.x === x) return;
  6423. this._anchorPoint.x = x;
  6424. this._renderCmd._updateAnchorPointInPoint();
  6425. },
  6426. _getAnchorY: function () {
  6427. return this._anchorPoint.y;
  6428. },
  6429. _setAnchorY: function (y) {
  6430. if (this._anchorPoint.y === y) return;
  6431. this._anchorPoint.y = y;
  6432. this._renderCmd._updateAnchorPointInPoint();
  6433. },
  6434. getAnchorPointInPoints: function () {
  6435. return this._renderCmd.getAnchorPointInPoints();
  6436. },
  6437. _getWidth: function () {
  6438. return this._contentSize.width;
  6439. },
  6440. _setWidth: function (width) {
  6441. this._contentSize.width = width;
  6442. this._renderCmd._updateAnchorPointInPoint();
  6443. },
  6444. _getHeight: function () {
  6445. return this._contentSize.height;
  6446. },
  6447. _setHeight: function (height) {
  6448. this._contentSize.height = height;
  6449. this._renderCmd._updateAnchorPointInPoint();
  6450. },
  6451. getContentSize: function () {
  6452. return cc.size(this._contentSize);
  6453. },
  6454. setContentSize: function (size, height) {
  6455. var locContentSize = this._contentSize;
  6456. if (height === undefined) {
  6457. if ((size.width === locContentSize.width) && (size.height === locContentSize.height))
  6458. return;
  6459. locContentSize.width = size.width;
  6460. locContentSize.height = size.height;
  6461. } else {
  6462. if ((size === locContentSize.width) && (height === locContentSize.height))
  6463. return;
  6464. locContentSize.width = size;
  6465. locContentSize.height = height;
  6466. }
  6467. this._renderCmd._updateAnchorPointInPoint();
  6468. },
  6469. isRunning: function () {
  6470. return this._running;
  6471. },
  6472. getParent: function () {
  6473. return this._parent;
  6474. },
  6475. setParent: function (parent) {
  6476. this._parent = parent;
  6477. this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
  6478. },
  6479. isIgnoreAnchorPointForPosition: function () {
  6480. return this._ignoreAnchorPointForPosition;
  6481. },
  6482. ignoreAnchorPointForPosition: function (newValue) {
  6483. if (newValue !== this._ignoreAnchorPointForPosition) {
  6484. this._ignoreAnchorPointForPosition = newValue;
  6485. this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
  6486. }
  6487. },
  6488. getTag: function () {
  6489. return this.tag;
  6490. },
  6491. setTag: function (tag) {
  6492. this.tag = tag;
  6493. },
  6494. setName: function(name){
  6495. this._name = name;
  6496. },
  6497. getName: function(){
  6498. return this._name;
  6499. },
  6500. getUserData: function () {
  6501. return this.userData;
  6502. },
  6503. setUserData: function (Var) {
  6504. this.userData = Var;
  6505. },
  6506. getUserObject: function () {
  6507. return this.userObject;
  6508. },
  6509. setUserObject: function (newValue) {
  6510. if (this.userObject !== newValue)
  6511. this.userObject = newValue;
  6512. },
  6513. getOrderOfArrival: function () {
  6514. return this.arrivalOrder;
  6515. },
  6516. setOrderOfArrival: function (Var) {
  6517. this.arrivalOrder = Var;
  6518. },
  6519. getActionManager: function () {
  6520. if (!this._actionManager)
  6521. this._actionManager = cc.director.getActionManager();
  6522. return this._actionManager;
  6523. },
  6524. setActionManager: function (actionManager) {
  6525. if (this._actionManager !== actionManager) {
  6526. this.stopAllActions();
  6527. this._actionManager = actionManager;
  6528. }
  6529. },
  6530. getScheduler: function () {
  6531. if (!this._scheduler)
  6532. this._scheduler = cc.director.getScheduler();
  6533. return this._scheduler;
  6534. },
  6535. setScheduler: function (scheduler) {
  6536. if (this._scheduler !== scheduler) {
  6537. this.unscheduleAllCallbacks();
  6538. this._scheduler = scheduler;
  6539. }
  6540. },
  6541. boundingBox: function(){
  6542. cc.log(cc._LogInfos.Node_boundingBox);
  6543. return this.getBoundingBox();
  6544. },
  6545. getBoundingBox: function () {
  6546. var rect = cc.rect(0, 0, this._contentSize.width, this._contentSize.height);
  6547. return cc._rectApplyAffineTransformIn(rect, this.getNodeToParentTransform());
  6548. },
  6549. cleanup: function () {
  6550. this.stopAllActions();
  6551. this.unscheduleAllCallbacks();
  6552. cc.eventManager.removeListeners(this);
  6553. this._arrayMakeObjectsPerformSelector(this._children, cc.Node._stateCallbackType.cleanup);
  6554. },
  6555. getChildByTag: function (aTag) {
  6556. var __children = this._children;
  6557. if (__children !== null) {
  6558. for (var i = 0; i < __children.length; i++) {
  6559. var node = __children[i];
  6560. if (node && node.tag === aTag)
  6561. return node;
  6562. }
  6563. }
  6564. return null;
  6565. },
  6566. getChildByName: function(name){
  6567. if(!name){
  6568. cc.log("Invalid name");
  6569. return null;
  6570. }
  6571. var locChildren = this._children;
  6572. for(var i = 0, len = locChildren.length; i < len; i++){
  6573. if(locChildren[i]._name === name)
  6574. return locChildren[i];
  6575. }
  6576. return null;
  6577. },
  6578. addChild: function (child, localZOrder, tag) {
  6579. localZOrder = localZOrder === undefined ? child._localZOrder : localZOrder;
  6580. var name, setTag = false;
  6581. if(cc.isUndefined(tag)){
  6582. tag = undefined;
  6583. name = child._name;
  6584. } else if(cc.isString(tag)){
  6585. name = tag;
  6586. tag = undefined;
  6587. } else if(cc.isNumber(tag)){
  6588. setTag = true;
  6589. name = "";
  6590. }
  6591. cc.assert(child, cc._LogInfos.Node_addChild_3);
  6592. cc.assert(child._parent === null, "child already added. It can't be added again");
  6593. this._addChildHelper(child, localZOrder, tag, name, setTag);
  6594. },
  6595. _addChildHelper: function(child, localZOrder, tag, name, setTag){
  6596. if(!this._children)
  6597. this._children = [];
  6598. this._insertChild(child, localZOrder);
  6599. if(setTag)
  6600. child.setTag(tag);
  6601. else
  6602. child.setName(name);
  6603. child.setParent(this);
  6604. child.setOrderOfArrival(cc.s_globalOrderOfArrival++);
  6605. if( this._running ){
  6606. child.onEnter();
  6607. if (this._isTransitionFinished)
  6608. child.onEnterTransitionDidFinish();
  6609. }
  6610. child._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
  6611. if (this._cascadeColorEnabled)
  6612. child._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.colorDirty);
  6613. if (this._cascadeOpacityEnabled)
  6614. child._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.opacityDirty);
  6615. },
  6616. removeFromParent: function (cleanup) {
  6617. if (this._parent) {
  6618. if (cleanup === undefined)
  6619. cleanup = true;
  6620. this._parent.removeChild(this, cleanup);
  6621. }
  6622. },
  6623. removeFromParentAndCleanup: function (cleanup) {
  6624. cc.log(cc._LogInfos.Node_removeFromParentAndCleanup);
  6625. this.removeFromParent(cleanup);
  6626. },
  6627. removeChild: function (child, cleanup) {
  6628. if (this._children.length === 0)
  6629. return;
  6630. if (cleanup === undefined)
  6631. cleanup = true;
  6632. if (this._children.indexOf(child) > -1)
  6633. this._detachChild(child, cleanup);
  6634. cc.renderer.childrenOrderDirty = true;
  6635. },
  6636. removeChildByTag: function (tag, cleanup) {
  6637. if (tag === cc.NODE_TAG_INVALID)
  6638. cc.log(cc._LogInfos.Node_removeChildByTag);
  6639. var child = this.getChildByTag(tag);
  6640. if (!child)
  6641. cc.log(cc._LogInfos.Node_removeChildByTag_2, tag);
  6642. else
  6643. this.removeChild(child, cleanup);
  6644. },
  6645. removeAllChildrenWithCleanup: function (cleanup) {
  6646. this.removeAllChildren(cleanup);
  6647. },
  6648. removeAllChildren: function (cleanup) {
  6649. var __children = this._children;
  6650. if (__children !== null) {
  6651. if (cleanup === undefined)
  6652. cleanup = true;
  6653. for (var i = 0; i < __children.length; i++) {
  6654. var node = __children[i];
  6655. if (node) {
  6656. if (this._running) {
  6657. node.onExitTransitionDidStart();
  6658. node.onExit();
  6659. }
  6660. if (cleanup)
  6661. node.cleanup();
  6662. node.parent = null;
  6663. node._renderCmd.detachFromParent();
  6664. }
  6665. }
  6666. this._children.length = 0;
  6667. cc.renderer.childrenOrderDirty = true;
  6668. }
  6669. },
  6670. _detachChild: function (child, doCleanup) {
  6671. if (this._running) {
  6672. child.onExitTransitionDidStart();
  6673. child.onExit();
  6674. }
  6675. if (doCleanup)
  6676. child.cleanup();
  6677. child.parent = null;
  6678. child._renderCmd.detachFromParent();
  6679. cc.arrayRemoveObject(this._children, child);
  6680. },
  6681. _insertChild: function (child, z) {
  6682. cc.renderer.childrenOrderDirty = this._reorderChildDirty = true;
  6683. this._children.push(child);
  6684. child._setLocalZOrder(z);
  6685. },
  6686. setNodeDirty: function(){
  6687. this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
  6688. },
  6689. reorderChild: function (child, zOrder) {
  6690. cc.assert(child, cc._LogInfos.Node_reorderChild);
  6691. cc.renderer.childrenOrderDirty = this._reorderChildDirty = true;
  6692. child.arrivalOrder = cc.s_globalOrderOfArrival;
  6693. cc.s_globalOrderOfArrival++;
  6694. child._setLocalZOrder(zOrder);
  6695. this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.orderDirty);
  6696. },
  6697. sortAllChildren: function () {
  6698. if (this._reorderChildDirty) {
  6699. var _children = this._children;
  6700. var len = _children.length, i, j, tmp;
  6701. for(i=1; i<len; i++){
  6702. tmp = _children[i];
  6703. j = i - 1;
  6704. while(j >= 0){
  6705. if(tmp._localZOrder < _children[j]._localZOrder){
  6706. _children[j+1] = _children[j];
  6707. }else if(tmp._localZOrder === _children[j]._localZOrder && tmp.arrivalOrder < _children[j].arrivalOrder){
  6708. _children[j+1] = _children[j];
  6709. }else{
  6710. break;
  6711. }
  6712. j--;
  6713. }
  6714. _children[j+1] = tmp;
  6715. }
  6716. this._reorderChildDirty = false;
  6717. }
  6718. },
  6719. draw: function (ctx) {
  6720. },
  6721. transformAncestors: function () {
  6722. if (this._parent !== null) {
  6723. this._parent.transformAncestors();
  6724. this._parent.transform();
  6725. }
  6726. },
  6727. onEnter: function () {
  6728. this._isTransitionFinished = false;
  6729. this._running = true;//should be running before resumeSchedule
  6730. this._arrayMakeObjectsPerformSelector(this._children, cc.Node._stateCallbackType.onEnter);
  6731. this.resume();
  6732. },
  6733. onEnterTransitionDidFinish: function () {
  6734. this._isTransitionFinished = true;
  6735. this._arrayMakeObjectsPerformSelector(this._children, cc.Node._stateCallbackType.onEnterTransitionDidFinish);
  6736. },
  6737. onExitTransitionDidStart: function () {
  6738. this._arrayMakeObjectsPerformSelector(this._children, cc.Node._stateCallbackType.onExitTransitionDidStart);
  6739. },
  6740. onExit: function () {
  6741. this._running = false;
  6742. this.pause();
  6743. this._arrayMakeObjectsPerformSelector(this._children, cc.Node._stateCallbackType.onExit);
  6744. this.removeAllComponents();
  6745. },
  6746. runAction: function (action) {
  6747. cc.assert(action, cc._LogInfos.Node_runAction);
  6748. this.actionManager.addAction(action, this, !this._running);
  6749. return action;
  6750. },
  6751. stopAllActions: function () {
  6752. this.actionManager && this.actionManager.removeAllActionsFromTarget(this);
  6753. },
  6754. stopAction: function (action) {
  6755. this.actionManager.removeAction(action);
  6756. },
  6757. stopActionByTag: function (tag) {
  6758. if (tag === cc.ACTION_TAG_INVALID) {
  6759. cc.log(cc._LogInfos.Node_stopActionByTag);
  6760. return;
  6761. }
  6762. this.actionManager.removeActionByTag(tag, this);
  6763. },
  6764. getActionByTag: function (tag) {
  6765. if (tag === cc.ACTION_TAG_INVALID) {
  6766. cc.log(cc._LogInfos.Node_getActionByTag);
  6767. return null;
  6768. }
  6769. return this.actionManager.getActionByTag(tag, this);
  6770. },
  6771. getNumberOfRunningActions: function () {
  6772. return this.actionManager.numberOfRunningActionsInTarget(this);
  6773. },
  6774. scheduleUpdate: function () {
  6775. this.scheduleUpdateWithPriority(0);
  6776. },
  6777. scheduleUpdateWithPriority: function (priority) {
  6778. this.scheduler.scheduleUpdate(this, priority, !this._running);
  6779. },
  6780. unscheduleUpdate: function () {
  6781. this.scheduler.unscheduleUpdate(this);
  6782. },
  6783. schedule: function (callback, interval, repeat, delay, key) {
  6784. var len = arguments.length;
  6785. if(typeof callback === "function"){
  6786. if(len === 1){
  6787. interval = 0;
  6788. repeat = cc.REPEAT_FOREVER;
  6789. delay = 0;
  6790. key = this.__instanceId;
  6791. }else if(len === 2){
  6792. if(typeof interval === "number"){
  6793. repeat = cc.REPEAT_FOREVER;
  6794. delay = 0;
  6795. key = this.__instanceId;
  6796. }else{
  6797. key = interval;
  6798. interval = 0;
  6799. repeat = cc.REPEAT_FOREVER;
  6800. delay = 0;
  6801. }
  6802. }else if(len === 3){
  6803. if(typeof repeat === "string"){
  6804. key = repeat;
  6805. repeat = cc.REPEAT_FOREVER;
  6806. }else{
  6807. key = this.__instanceId;
  6808. }
  6809. delay = 0;
  6810. }else if(len === 4){
  6811. key = this.__instanceId;
  6812. }
  6813. }else{
  6814. if(len === 1){
  6815. interval = 0;
  6816. repeat = cc.REPEAT_FOREVER;
  6817. delay = 0;
  6818. }else if(len === 2){
  6819. repeat = cc.REPEAT_FOREVER;
  6820. delay = 0;
  6821. }
  6822. }
  6823. cc.assert(callback, cc._LogInfos.Node_schedule);
  6824. cc.assert(interval >= 0, cc._LogInfos.Node_schedule_2);
  6825. interval = interval || 0;
  6826. repeat = (repeat == null) ? cc.REPEAT_FOREVER : repeat;
  6827. delay = delay || 0;
  6828. this.scheduler.schedule(callback, this, interval, repeat, delay, !this._running, key);
  6829. },
  6830. scheduleOnce: function (callback, delay, key) {
  6831. if(key === undefined)
  6832. key = this.__instanceId;
  6833. this.schedule(callback, 0, 0, delay, key);
  6834. },
  6835. unschedule: function (callback_fn) {
  6836. if (!callback_fn)
  6837. return;
  6838. this.scheduler.unschedule(callback_fn, this);
  6839. },
  6840. unscheduleAllCallbacks: function () {
  6841. this.scheduler.unscheduleAllForTarget(this);
  6842. },
  6843. resumeSchedulerAndActions: function () {
  6844. cc.log(cc._LogInfos.Node_resumeSchedulerAndActions);
  6845. this.resume();
  6846. },
  6847. resume: function () {
  6848. this.scheduler.resumeTarget(this);
  6849. this.actionManager && this.actionManager.resumeTarget(this);
  6850. cc.eventManager.resumeTarget(this);
  6851. },
  6852. pauseSchedulerAndActions: function () {
  6853. cc.log(cc._LogInfos.Node_pauseSchedulerAndActions);
  6854. this.pause();
  6855. },
  6856. pause: function () {
  6857. this.scheduler.pauseTarget(this);
  6858. this.actionManager && this.actionManager.pauseTarget(this);
  6859. cc.eventManager.pauseTarget(this);
  6860. },
  6861. setAdditionalTransform: function (additionalTransform) {
  6862. if(additionalTransform === undefined)
  6863. return this._additionalTransformDirty = false;
  6864. this._additionalTransform = additionalTransform;
  6865. this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
  6866. this._additionalTransformDirty = true;
  6867. },
  6868. getParentToNodeTransform: function () {
  6869. return this._renderCmd.getParentToNodeTransform();
  6870. },
  6871. parentToNodeTransform: function () {
  6872. return this.getParentToNodeTransform();
  6873. },
  6874. getNodeToWorldTransform: function () {
  6875. var t = this.getNodeToParentTransform();
  6876. for (var p = this._parent; p !== null; p = p.parent)
  6877. t = cc.affineTransformConcat(t, p.getNodeToParentTransform());
  6878. return t;
  6879. },
  6880. nodeToWorldTransform: function(){
  6881. return this.getNodeToWorldTransform();
  6882. },
  6883. getWorldToNodeTransform: function () {
  6884. return cc.affineTransformInvert(this.getNodeToWorldTransform());
  6885. },
  6886. worldToNodeTransform: function () {
  6887. return this.getWorldToNodeTransform();
  6888. },
  6889. convertToNodeSpace: function (worldPoint) {
  6890. return cc.pointApplyAffineTransform(worldPoint, this.getWorldToNodeTransform());
  6891. },
  6892. convertToWorldSpace: function (nodePoint) {
  6893. nodePoint = nodePoint || cc.p(0,0);
  6894. return cc.pointApplyAffineTransform(nodePoint, this.getNodeToWorldTransform());
  6895. },
  6896. convertToNodeSpaceAR: function (worldPoint) {
  6897. return cc.pSub(this.convertToNodeSpace(worldPoint), this._renderCmd.getAnchorPointInPoints());
  6898. },
  6899. convertToWorldSpaceAR: function (nodePoint) {
  6900. nodePoint = nodePoint || cc.p(0,0);
  6901. var pt = cc.pAdd(nodePoint, this._renderCmd.getAnchorPointInPoints());
  6902. return this.convertToWorldSpace(pt);
  6903. },
  6904. _convertToWindowSpace: function (nodePoint) {
  6905. var worldPoint = this.convertToWorldSpace(nodePoint);
  6906. return cc.director.convertToUI(worldPoint);
  6907. },
  6908. convertTouchToNodeSpace: function (touch) {
  6909. var point = touch.getLocation();
  6910. return this.convertToNodeSpace(point);
  6911. },
  6912. convertTouchToNodeSpaceAR: function (touch) {
  6913. var point = cc.director.convertToGL(touch.getLocation());
  6914. return this.convertToNodeSpaceAR(point);
  6915. },
  6916. update: function (dt) {
  6917. if (this._componentContainer && !this._componentContainer.isEmpty())
  6918. this._componentContainer.visit(dt);
  6919. },
  6920. updateTransform: function () {
  6921. this._arrayMakeObjectsPerformSelector(this._children, cc.Node._stateCallbackType.updateTransform);
  6922. },
  6923. retain: function () {
  6924. },
  6925. release: function () {
  6926. },
  6927. getComponent: function (name) {
  6928. if(this._componentContainer)
  6929. return this._componentContainer.getComponent(name);
  6930. return null;
  6931. },
  6932. addComponent: function (component) {
  6933. if(this._componentContainer)
  6934. this._componentContainer.add(component);
  6935. },
  6936. removeComponent: function (component) {
  6937. if(this._componentContainer)
  6938. return this._componentContainer.remove(component);
  6939. return false;
  6940. },
  6941. removeAllComponents: function () {
  6942. if(this._componentContainer)
  6943. this._componentContainer.removeAll();
  6944. },
  6945. grid: null,
  6946. visit: function(parentCmd){
  6947. this._renderCmd.visit(parentCmd);
  6948. },
  6949. transform: function(parentCmd, recursive){
  6950. this._renderCmd.transform(parentCmd, recursive);
  6951. },
  6952. nodeToParentTransform: function(){
  6953. return this.getNodeToParentTransform();
  6954. },
  6955. getNodeToParentTransform: function(ancestor){
  6956. var t = this._renderCmd.getNodeToParentTransform();
  6957. if(ancestor){
  6958. var T = {a: t.a, b: t.b, c: t.c, d: t.d, tx: t.tx, ty: t.ty};
  6959. for(var p = this._parent; p != null && p != ancestor ; p = p.getParent()){
  6960. cc.affineTransformConcatIn(T, p.getNodeToParentTransform());
  6961. }
  6962. return T;
  6963. }else{
  6964. return t;
  6965. }
  6966. },
  6967. getNodeToParentAffineTransform: function(ancestor){
  6968. return this.getNodeToParentTransform(ancestor);
  6969. },
  6970. getCamera: function () {
  6971. return null;
  6972. },
  6973. getGrid: function () {
  6974. return this.grid;
  6975. },
  6976. setGrid: function (grid) {
  6977. this.grid = grid;
  6978. },
  6979. getShaderProgram: function () {
  6980. return this._renderCmd.getShaderProgram();
  6981. },
  6982. setShaderProgram: function (newShaderProgram) {
  6983. this._renderCmd.setShaderProgram(newShaderProgram);
  6984. },
  6985. getGLServerState: function () {
  6986. return 0;
  6987. },
  6988. setGLServerState: function (state) {
  6989. },
  6990. getBoundingBoxToWorld: function () {
  6991. var rect = cc.rect(0, 0, this._contentSize.width, this._contentSize.height);
  6992. var trans = this.getNodeToWorldTransform();
  6993. rect = cc.rectApplyAffineTransform(rect, trans);
  6994. if (!this._children)
  6995. return rect;
  6996. var locChildren = this._children;
  6997. for (var i = 0; i < locChildren.length; i++) {
  6998. var child = locChildren[i];
  6999. if (child && child._visible) {
  7000. var childRect = child._getBoundingBoxToCurrentNode(trans);
  7001. if (childRect)
  7002. rect = cc.rectUnion(rect, childRect);
  7003. }
  7004. }
  7005. return rect;
  7006. },
  7007. _getBoundingBoxToCurrentNode: function (parentTransform) {
  7008. var rect = cc.rect(0, 0, this._contentSize.width, this._contentSize.height);
  7009. var trans = (parentTransform === undefined) ? this.getNodeToParentTransform() : cc.affineTransformConcat(this.getNodeToParentTransform(), parentTransform);
  7010. rect = cc.rectApplyAffineTransform(rect, trans);
  7011. if (!this._children)
  7012. return rect;
  7013. var locChildren = this._children;
  7014. for (var i = 0; i < locChildren.length; i++) {
  7015. var child = locChildren[i];
  7016. if (child && child._visible) {
  7017. var childRect = child._getBoundingBoxToCurrentNode(trans);
  7018. if (childRect)
  7019. rect = cc.rectUnion(rect, childRect);
  7020. }
  7021. }
  7022. return rect;
  7023. },
  7024. getOpacity: function () {
  7025. return this._realOpacity;
  7026. },
  7027. getDisplayedOpacity: function () {
  7028. return this._renderCmd.getDisplayedOpacity();
  7029. },
  7030. setOpacity: function (opacity) {
  7031. this._realOpacity = opacity;
  7032. this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.opacityDirty);
  7033. },
  7034. updateDisplayedOpacity: function (parentOpacity) {
  7035. this._renderCmd._updateDisplayOpacity(parentOpacity);
  7036. },
  7037. isCascadeOpacityEnabled: function () {
  7038. return this._cascadeOpacityEnabled;
  7039. },
  7040. setCascadeOpacityEnabled: function (cascadeOpacityEnabled) {
  7041. if (this._cascadeOpacityEnabled === cascadeOpacityEnabled)
  7042. return;
  7043. this._cascadeOpacityEnabled = cascadeOpacityEnabled;
  7044. this._renderCmd.setCascadeOpacityEnabledDirty();
  7045. },
  7046. getColor: function () {
  7047. var locRealColor = this._realColor;
  7048. return cc.color(locRealColor.r, locRealColor.g, locRealColor.b, locRealColor.a);
  7049. },
  7050. getDisplayedColor: function () {
  7051. return this._renderCmd.getDisplayedColor();
  7052. },
  7053. setColor: function (color) {
  7054. var locRealColor = this._realColor;
  7055. locRealColor.r = color.r;
  7056. locRealColor.g = color.g;
  7057. locRealColor.b = color.b;
  7058. this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.colorDirty);
  7059. },
  7060. updateDisplayedColor: function (parentColor) {
  7061. this._renderCmd._updateDisplayColor(parentColor);
  7062. },
  7063. isCascadeColorEnabled: function () {
  7064. return this._cascadeColorEnabled;
  7065. },
  7066. setCascadeColorEnabled: function (cascadeColorEnabled) {
  7067. if (this._cascadeColorEnabled === cascadeColorEnabled)
  7068. return;
  7069. this._cascadeColorEnabled = cascadeColorEnabled;
  7070. this._renderCmd.setCascadeColorEnabledDirty();
  7071. },
  7072. setOpacityModifyRGB: function (opacityValue) {
  7073. },
  7074. isOpacityModifyRGB: function () {
  7075. return false;
  7076. },
  7077. _initRendererCmd: function(){
  7078. this._renderCmd = cc.renderer.getRenderCmd(this);
  7079. },
  7080. _createRenderCmd: function(){
  7081. if(cc._renderType === cc.game.RENDER_TYPE_CANVAS)
  7082. return new cc.Node.CanvasRenderCmd(this);
  7083. else
  7084. return new cc.Node.WebGLRenderCmd(this);
  7085. },
  7086. enumerateChildren: function(name, callback){
  7087. cc.assert(name && name.length != 0, "Invalid name");
  7088. cc.assert(callback != null, "Invalid callback function");
  7089. var length = name.length;
  7090. var subStrStartPos = 0;
  7091. var subStrlength = length;
  7092. var searchRecursively = false;
  7093. if(length > 2 && name[0] === "/" && name[1] === "/"){
  7094. searchRecursively = true;
  7095. subStrStartPos = 2;
  7096. subStrlength -= 2;
  7097. }
  7098. var searchFromParent = false;
  7099. if(length > 3 && name[length-3] === "/" && name[length-2] === "." && name[length-1] === "."){
  7100. searchFromParent = true;
  7101. subStrlength -= 3;
  7102. }
  7103. var newName = name.substr(subStrStartPos, subStrlength);
  7104. if(searchFromParent)
  7105. newName = "[[:alnum:]]+/" + newName;
  7106. if(searchRecursively)
  7107. this.doEnumerateRecursive(this, newName, callback);
  7108. else
  7109. this.doEnumerate(newName, callback);
  7110. },
  7111. doEnumerateRecursive: function(node, name, callback){
  7112. var ret = false;
  7113. if(node.doEnumerate(name,callback)){
  7114. ret = true;
  7115. }else{
  7116. var child,
  7117. children = node.getChildren(),
  7118. length = children.length;
  7119. for (var i=0; i<length; i++) {
  7120. child = children[i];
  7121. if (this.doEnumerateRecursive(child, name, callback)) {
  7122. ret = true;
  7123. break;
  7124. }
  7125. }
  7126. }
  7127. },
  7128. doEnumerate: function(name, callback){
  7129. var pos = name.indexOf('/');
  7130. var searchName = name;
  7131. var needRecursive = false;
  7132. if (pos !== -1){
  7133. searchName = name.substr(0, pos);
  7134. needRecursive = true;
  7135. }
  7136. var ret = false;
  7137. var child,
  7138. children = this._children,
  7139. length = children.length;
  7140. for (var i=0; i<length; i++){
  7141. child = children[i];
  7142. if (child._name.indexOf(searchName) !== -1){
  7143. if (!needRecursive){
  7144. if (callback(child)){
  7145. ret = true;
  7146. break;
  7147. }
  7148. }else{
  7149. ret = child.doEnumerate(name, callback);
  7150. if (ret)
  7151. break;
  7152. }
  7153. }
  7154. }
  7155. return ret;
  7156. }
  7157. });
  7158. cc.Node.create = function () {
  7159. return new cc.Node();
  7160. };
  7161. cc.Node._stateCallbackType = {onEnter: 1, onExit: 2, cleanup: 3, onEnterTransitionDidFinish: 4, updateTransform: 5, onExitTransitionDidStart: 6, sortAllChildren: 7};
  7162. cc.assert(cc.isFunction(cc._tmp.PrototypeCCNode), cc._LogInfos.MissingFile, "BaseNodesPropertyDefine.js");
  7163. cc._tmp.PrototypeCCNode();
  7164. delete cc._tmp.PrototypeCCNode;
  7165. cc.CustomRenderCmd = function (target, func) {
  7166. this._needDraw = true;
  7167. this._target = target;
  7168. this._callback = func;
  7169. this.rendering = function (ctx, scaleX, scaleY) {
  7170. if (!this._callback)
  7171. return;
  7172. this._callback.call(this._target, ctx, scaleX, scaleY);
  7173. };
  7174. this.needDraw = function () {
  7175. return this._needDraw;
  7176. };
  7177. };
  7178. cc.Node._dirtyFlags = {
  7179. transformDirty: 1 << 0, visibleDirty: 1 << 1, colorDirty: 1 << 2, opacityDirty: 1 << 3, cacheDirty: 1 << 4,
  7180. orderDirty: 1 << 5, textDirty: 1 << 6, gradientDirty: 1 << 7, textureDirty: 1 << 8,
  7181. contentDirty: 1 << 9,
  7182. COUNT: 10,
  7183. all: (1 << 10) - 1
  7184. };
  7185. cc.Node.RenderCmd = function (renderable) {
  7186. this._dirtyFlag = 1;
  7187. this._savedDirtyFlag = true;
  7188. this._node = renderable;
  7189. this._needDraw = false;
  7190. this._anchorPointInPoints = new cc.Point(0, 0);
  7191. this._transform = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0};
  7192. this._worldTransform = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0};
  7193. this._inverse = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0};
  7194. this._displayedOpacity = 255;
  7195. this._displayedColor = cc.color(255, 255, 255, 255);
  7196. this._cascadeColorEnabledDirty = false;
  7197. this._cascadeOpacityEnabledDirty = false;
  7198. this._curLevel = -1;
  7199. };
  7200. cc.Node.RenderCmd.prototype = {
  7201. constructor: cc.Node.RenderCmd,
  7202. needDraw: function () {
  7203. return this._needDraw;
  7204. },
  7205. getAnchorPointInPoints: function () {
  7206. return cc.p(this._anchorPointInPoints);
  7207. },
  7208. getDisplayedColor: function () {
  7209. var tmpColor = this._displayedColor;
  7210. return cc.color(tmpColor.r, tmpColor.g, tmpColor.b, tmpColor.a);
  7211. },
  7212. getDisplayedOpacity: function () {
  7213. return this._displayedOpacity;
  7214. },
  7215. setCascadeColorEnabledDirty: function () {
  7216. this._cascadeColorEnabledDirty = true;
  7217. this.setDirtyFlag(cc.Node._dirtyFlags.colorDirty);
  7218. },
  7219. setCascadeOpacityEnabledDirty: function () {
  7220. this._cascadeOpacityEnabledDirty = true;
  7221. this.setDirtyFlag(cc.Node._dirtyFlags.opacityDirty);
  7222. },
  7223. getParentToNodeTransform: function () {
  7224. if (this._dirtyFlag & cc.Node._dirtyFlags.transformDirty)
  7225. this._inverse = cc.affineTransformInvert(this.getNodeToParentTransform());
  7226. return this._inverse;
  7227. },
  7228. detachFromParent: function () {
  7229. },
  7230. _updateAnchorPointInPoint: function () {
  7231. var locAPP = this._anchorPointInPoints, locSize = this._node._contentSize, locAnchorPoint = this._node._anchorPoint;
  7232. locAPP.x = locSize.width * locAnchorPoint.x;
  7233. locAPP.y = locSize.height * locAnchorPoint.y;
  7234. this.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
  7235. },
  7236. setDirtyFlag: function (dirtyFlag) {
  7237. if (this._dirtyFlag === 0 && dirtyFlag !== 0)
  7238. cc.renderer.pushDirtyNode(this);
  7239. this._dirtyFlag |= dirtyFlag;
  7240. },
  7241. getParentRenderCmd: function () {
  7242. if (this._node && this._node._parent && this._node._parent._renderCmd)
  7243. return this._node._parent._renderCmd;
  7244. return null;
  7245. },
  7246. transform: function (parentCmd, recursive) {
  7247. var node = this._node,
  7248. pt = parentCmd ? parentCmd._worldTransform : null,
  7249. t = this._transform,
  7250. wt = this._worldTransform;
  7251. if (node._usingNormalizedPosition && node._parent) {
  7252. var conSize = node._parent._contentSize;
  7253. node._position.x = node._normalizedPosition.x * conSize.width;
  7254. node._position.y = node._normalizedPosition.y * conSize.height;
  7255. node._normalizedPositionDirty = false;
  7256. }
  7257. var hasRotation = node._rotationX || node._rotationY;
  7258. var hasSkew = node._skewX || node._skewY;
  7259. var sx = node._scaleX, sy = node._scaleY;
  7260. var appX = this._anchorPointInPoints.x, appY = this._anchorPointInPoints.y;
  7261. var a = 1, b = 0, c = 0, d = 1;
  7262. if (hasRotation || hasSkew) {
  7263. t.tx = node._position.x;
  7264. t.ty = node._position.y;
  7265. if (hasRotation) {
  7266. var rotationRadiansX = node._rotationX * 0.017453292519943295;
  7267. c = Math.sin(rotationRadiansX);
  7268. d = Math.cos(rotationRadiansX);
  7269. if (node._rotationY === node._rotationX) {
  7270. a = d;
  7271. b = -c;
  7272. }
  7273. else {
  7274. var rotationRadiansY = node._rotationY * 0.017453292519943295;
  7275. a = Math.cos(rotationRadiansY);
  7276. b = -Math.sin(rotationRadiansY);
  7277. }
  7278. }
  7279. t.a = a *= sx;
  7280. t.b = b *= sx;
  7281. t.c = c *= sy;
  7282. t.d = d *= sy;
  7283. if (hasSkew) {
  7284. var skx = Math.tan(node._skewX * Math.PI / 180);
  7285. var sky = Math.tan(node._skewY * Math.PI / 180);
  7286. if (skx === Infinity)
  7287. skx = 99999999;
  7288. if (sky === Infinity)
  7289. sky = 99999999;
  7290. t.a = a + c * sky;
  7291. t.b = b + d * sky;
  7292. t.c = c + a * skx;
  7293. t.d = d + b * skx;
  7294. }
  7295. if (appX || appY) {
  7296. t.tx -= t.a * appX + t.c * appY;
  7297. t.ty -= t.b * appX + t.d * appY;
  7298. if (node._ignoreAnchorPointForPosition) {
  7299. t.tx += appX;
  7300. t.ty += appY;
  7301. }
  7302. }
  7303. if (pt) {
  7304. wt.a = t.a * pt.a + t.b * pt.c;
  7305. wt.b = t.a * pt.b + t.b * pt.d;
  7306. wt.c = t.c * pt.a + t.d * pt.c;
  7307. wt.d = t.c * pt.b + t.d * pt.d;
  7308. wt.tx = pt.a * t.tx + pt.c * t.ty + pt.tx;
  7309. wt.ty = pt.d * t.ty + pt.ty + pt.b * t.tx;
  7310. } else {
  7311. wt.a = t.a;
  7312. wt.b = t.b;
  7313. wt.c = t.c;
  7314. wt.d = t.d;
  7315. wt.tx = t.tx;
  7316. wt.ty = t.ty;
  7317. }
  7318. }
  7319. else {
  7320. t.a = sx;
  7321. t.b = 0;
  7322. t.c = 0;
  7323. t.d = sy;
  7324. t.tx = node._position.x;
  7325. t.ty = node._position.y;
  7326. if (appX || appY) {
  7327. t.tx -= t.a * appX;
  7328. t.ty -= t.d * appY;
  7329. if (node._ignoreAnchorPointForPosition) {
  7330. t.tx += appX;
  7331. t.ty += appY;
  7332. }
  7333. }
  7334. if (pt) {
  7335. wt.a = t.a * pt.a + t.b * pt.c;
  7336. wt.b = t.a * pt.b + t.b * pt.d;
  7337. wt.c = t.c * pt.a + t.d * pt.c;
  7338. wt.d = t.c * pt.b + t.d * pt.d;
  7339. wt.tx = t.tx * pt.a + t.ty * pt.c + pt.tx;
  7340. wt.ty = t.tx * pt.b + t.ty * pt.d + pt.ty;
  7341. } else {
  7342. wt.a = t.a;
  7343. wt.b = t.b;
  7344. wt.c = t.c;
  7345. wt.d = t.d;
  7346. wt.tx = t.tx;
  7347. wt.ty = t.ty;
  7348. }
  7349. }
  7350. if (node._additionalTransformDirty) {
  7351. this._transform = cc.affineTransformConcat(t, node._additionalTransform);
  7352. }
  7353. this._updateCurrentRegions && this._updateCurrentRegions();
  7354. this._notifyRegionStatus && this._notifyRegionStatus(cc.Node.CanvasRenderCmd.RegionStatus.DirtyDouble);
  7355. if (recursive) {
  7356. var locChildren = this._node._children;
  7357. if (!locChildren || locChildren.length === 0)
  7358. return;
  7359. var i, len;
  7360. for (i = 0, len = locChildren.length; i < len; i++) {
  7361. locChildren[i]._renderCmd.transform(this, recursive);
  7362. }
  7363. }
  7364. this._cacheDirty = true;
  7365. },
  7366. getNodeToParentTransform: function () {
  7367. if (this._dirtyFlag & cc.Node._dirtyFlags.transformDirty) {
  7368. this.transform();
  7369. }
  7370. return this._transform;
  7371. },
  7372. visit: function (parentCmd) {
  7373. var node = this._node, renderer = cc.renderer;
  7374. if (!node._visible)
  7375. return;
  7376. parentCmd = parentCmd || this.getParentRenderCmd();
  7377. if (parentCmd)
  7378. this._curLevel = parentCmd._curLevel + 1;
  7379. if (isNaN(node._customZ)) {
  7380. node._vertexZ = renderer.assignedZ;
  7381. renderer.assignedZ += renderer.assignedZStep;
  7382. }
  7383. this._syncStatus(parentCmd);
  7384. this.visitChildren();
  7385. },
  7386. _updateDisplayColor: function (parentColor) {
  7387. var node = this._node;
  7388. var locDispColor = this._displayedColor, locRealColor = node._realColor;
  7389. var i, len, selChildren, item;
  7390. this._notifyRegionStatus && this._notifyRegionStatus(cc.Node.CanvasRenderCmd.RegionStatus.Dirty);
  7391. if (this._cascadeColorEnabledDirty && !node._cascadeColorEnabled) {
  7392. locDispColor.r = locRealColor.r;
  7393. locDispColor.g = locRealColor.g;
  7394. locDispColor.b = locRealColor.b;
  7395. var whiteColor = new cc.Color(255, 255, 255, 255);
  7396. selChildren = node._children;
  7397. for (i = 0, len = selChildren.length; i < len; i++) {
  7398. item = selChildren[i];
  7399. if (item && item._renderCmd)
  7400. item._renderCmd._updateDisplayColor(whiteColor);
  7401. }
  7402. this._cascadeColorEnabledDirty = false;
  7403. } else {
  7404. if (parentColor === undefined) {
  7405. var locParent = node._parent;
  7406. if (locParent && locParent._cascadeColorEnabled)
  7407. parentColor = locParent.getDisplayedColor();
  7408. else
  7409. parentColor = cc.color.WHITE;
  7410. }
  7411. locDispColor.r = 0 | (locRealColor.r * parentColor.r / 255.0);
  7412. locDispColor.g = 0 | (locRealColor.g * parentColor.g / 255.0);
  7413. locDispColor.b = 0 | (locRealColor.b * parentColor.b / 255.0);
  7414. if (node._cascadeColorEnabled) {
  7415. selChildren = node._children;
  7416. for (i = 0, len = selChildren.length; i < len; i++) {
  7417. item = selChildren[i];
  7418. if (item && item._renderCmd) {
  7419. item._renderCmd._updateDisplayColor(locDispColor);
  7420. item._renderCmd._updateColor();
  7421. }
  7422. }
  7423. }
  7424. }
  7425. this._dirtyFlag = this._dirtyFlag & cc.Node._dirtyFlags.colorDirty ^ this._dirtyFlag;
  7426. },
  7427. _updateDisplayOpacity: function (parentOpacity) {
  7428. var node = this._node;
  7429. var i, len, selChildren, item;
  7430. this._notifyRegionStatus && this._notifyRegionStatus(cc.Node.CanvasRenderCmd.RegionStatus.Dirty);
  7431. if (this._cascadeOpacityEnabledDirty && !node._cascadeOpacityEnabled) {
  7432. this._displayedOpacity = node._realOpacity;
  7433. selChildren = node._children;
  7434. for (i = 0, len = selChildren.length; i < len; i++) {
  7435. item = selChildren[i];
  7436. if (item && item._renderCmd)
  7437. item._renderCmd._updateDisplayOpacity(255);
  7438. }
  7439. this._cascadeOpacityEnabledDirty = false;
  7440. } else {
  7441. if (parentOpacity === undefined) {
  7442. var locParent = node._parent;
  7443. parentOpacity = 255;
  7444. if (locParent && locParent._cascadeOpacityEnabled)
  7445. parentOpacity = locParent.getDisplayedOpacity();
  7446. }
  7447. this._displayedOpacity = node._realOpacity * parentOpacity / 255.0;
  7448. if (node._cascadeOpacityEnabled) {
  7449. selChildren = node._children;
  7450. for (i = 0, len = selChildren.length; i < len; i++) {
  7451. item = selChildren[i];
  7452. if (item && item._renderCmd) {
  7453. item._renderCmd._updateDisplayOpacity(this._displayedOpacity);
  7454. item._renderCmd._updateColor();
  7455. }
  7456. }
  7457. }
  7458. }
  7459. this._dirtyFlag = this._dirtyFlag & cc.Node._dirtyFlags.opacityDirty ^ this._dirtyFlag;
  7460. },
  7461. _syncDisplayColor: function (parentColor) {
  7462. var node = this._node, locDispColor = this._displayedColor, locRealColor = node._realColor;
  7463. if (parentColor === undefined) {
  7464. var locParent = node._parent;
  7465. if (locParent && locParent._cascadeColorEnabled)
  7466. parentColor = locParent.getDisplayedColor();
  7467. else
  7468. parentColor = cc.color.WHITE;
  7469. }
  7470. locDispColor.r = 0 | (locRealColor.r * parentColor.r / 255.0);
  7471. locDispColor.g = 0 | (locRealColor.g * parentColor.g / 255.0);
  7472. locDispColor.b = 0 | (locRealColor.b * parentColor.b / 255.0);
  7473. },
  7474. _syncDisplayOpacity: function (parentOpacity) {
  7475. var node = this._node;
  7476. if (parentOpacity === undefined) {
  7477. var locParent = node._parent;
  7478. parentOpacity = 255;
  7479. if (locParent && locParent._cascadeOpacityEnabled)
  7480. parentOpacity = locParent.getDisplayedOpacity();
  7481. }
  7482. this._displayedOpacity = node._realOpacity * parentOpacity / 255.0;
  7483. },
  7484. _updateColor: function () {
  7485. },
  7486. updateStatus: function () {
  7487. var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag;
  7488. var colorDirty = locFlag & flags.colorDirty,
  7489. opacityDirty = locFlag & flags.opacityDirty;
  7490. this._savedDirtyFlag = this._savedDirtyFlag || locFlag;
  7491. if (colorDirty)
  7492. this._updateDisplayColor();
  7493. if (opacityDirty)
  7494. this._updateDisplayOpacity();
  7495. if (colorDirty || opacityDirty)
  7496. this._updateColor();
  7497. if (locFlag & flags.transformDirty) {
  7498. this.transform(this.getParentRenderCmd(), true);
  7499. this._dirtyFlag = this._dirtyFlag & flags.transformDirty ^ this._dirtyFlag;
  7500. }
  7501. if (locFlag & flags.orderDirty)
  7502. this._dirtyFlag = this._dirtyFlag & flags.orderDirty ^ this._dirtyFlag;
  7503. },
  7504. _syncStatus: function (parentCmd) {
  7505. var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag, parentNode = null;
  7506. if (parentCmd) {
  7507. parentNode = parentCmd._node;
  7508. this._savedDirtyFlag = this._savedDirtyFlag || parentCmd._savedDirtyFlag || locFlag;
  7509. }
  7510. else {
  7511. this._savedDirtyFlag = this._savedDirtyFlag || locFlag;
  7512. }
  7513. if (parentNode && parentNode._cascadeColorEnabled && (parentCmd._dirtyFlag & flags.colorDirty))
  7514. locFlag |= flags.colorDirty;
  7515. if (parentNode && parentNode._cascadeOpacityEnabled && (parentCmd._dirtyFlag & flags.opacityDirty))
  7516. locFlag |= flags.opacityDirty;
  7517. if (parentCmd && (parentCmd._dirtyFlag & flags.transformDirty))
  7518. locFlag |= flags.transformDirty;
  7519. var colorDirty = locFlag & flags.colorDirty,
  7520. opacityDirty = locFlag & flags.opacityDirty;
  7521. this._dirtyFlag = locFlag;
  7522. if (colorDirty)
  7523. this._syncDisplayColor();
  7524. if (opacityDirty)
  7525. this._syncDisplayOpacity();
  7526. if (colorDirty || opacityDirty)
  7527. this._updateColor();
  7528. if (locFlag & flags.transformDirty)
  7529. this.transform(parentCmd);
  7530. if (locFlag & flags.orderDirty)
  7531. this._dirtyFlag = this._dirtyFlag & flags.orderDirty ^ this._dirtyFlag;
  7532. },
  7533. visitChildren: function () {
  7534. var renderer = cc.renderer;
  7535. var node = this._node;
  7536. var i, children = node._children, child;
  7537. var len = children.length;
  7538. if (len > 0) {
  7539. node.sortAllChildren();
  7540. for (i = 0; i < len; i++) {
  7541. child = children[i];
  7542. if (child._localZOrder < 0) {
  7543. child._renderCmd.visit(this);
  7544. }
  7545. else {
  7546. break;
  7547. }
  7548. }
  7549. renderer.pushRenderCommand(this);
  7550. for (; i < len; i++) {
  7551. children[i]._renderCmd.visit(this);
  7552. }
  7553. } else {
  7554. renderer.pushRenderCommand(this);
  7555. }
  7556. this._dirtyFlag = 0;
  7557. }
  7558. };
  7559. cc.Node.RenderCmd.prototype.originVisit = cc.Node.RenderCmd.prototype.visit;
  7560. cc.Node.RenderCmd.prototype.originTransform = cc.Node.RenderCmd.prototype.transform;
  7561. (function () {
  7562. cc.Node.CanvasRenderCmd = function (renderable) {
  7563. cc.Node.RenderCmd.call(this, renderable);
  7564. this._cachedParent = null;
  7565. this._cacheDirty = false;
  7566. this._currentRegion = new cc.Region();
  7567. this._oldRegion = new cc.Region();
  7568. this._regionFlag = 0;
  7569. this._canUseDirtyRegion = false;
  7570. };
  7571. cc.Node.CanvasRenderCmd.RegionStatus = {
  7572. NotDirty: 0,
  7573. Dirty: 1,
  7574. DirtyDouble: 2
  7575. };
  7576. var proto = cc.Node.CanvasRenderCmd.prototype = Object.create(cc.Node.RenderCmd.prototype);
  7577. proto.constructor = cc.Node.CanvasRenderCmd;
  7578. proto._notifyRegionStatus = function (status) {
  7579. if (this._needDraw && this._regionFlag < status) {
  7580. this._regionFlag = status;
  7581. }
  7582. };
  7583. var localBB = new cc.Rect();
  7584. proto.getLocalBB = function () {
  7585. var node = this._node;
  7586. localBB.x = localBB.y = 0;
  7587. localBB.width = node._contentSize.width;
  7588. localBB.height = node._contentSize.height;
  7589. return localBB;
  7590. };
  7591. proto._updateCurrentRegions = function () {
  7592. var temp = this._currentRegion;
  7593. this._currentRegion = this._oldRegion;
  7594. this._oldRegion = temp;
  7595. if (cc.Node.CanvasRenderCmd.RegionStatus.DirtyDouble === this._regionFlag && (!this._currentRegion.isEmpty())) {
  7596. this._oldRegion.union(this._currentRegion);
  7597. }
  7598. this._currentRegion.updateRegion(this.getLocalBB(), this._worldTransform);
  7599. };
  7600. proto.setDirtyFlag = function (dirtyFlag, child) {
  7601. cc.Node.RenderCmd.prototype.setDirtyFlag.call(this, dirtyFlag, child);
  7602. this._setCacheDirty(child);
  7603. if (this._cachedParent)
  7604. this._cachedParent.setDirtyFlag(dirtyFlag, true);
  7605. };
  7606. proto._setCacheDirty = function () {
  7607. if (this._cacheDirty === false) {
  7608. this._cacheDirty = true;
  7609. var cachedP = this._cachedParent;
  7610. cachedP && cachedP !== this && cachedP._setNodeDirtyForCache && cachedP._setNodeDirtyForCache();
  7611. }
  7612. };
  7613. proto._setCachedParent = function (cachedParent) {
  7614. if (this._cachedParent === cachedParent)
  7615. return;
  7616. this._cachedParent = cachedParent;
  7617. var children = this._node._children;
  7618. for (var i = 0, len = children.length; i < len; i++)
  7619. children[i]._renderCmd._setCachedParent(cachedParent);
  7620. };
  7621. proto.detachFromParent = function () {
  7622. this._cachedParent = null;
  7623. var selChildren = this._node._children, item;
  7624. for (var i = 0, len = selChildren.length; i < len; i++) {
  7625. item = selChildren[i];
  7626. if (item && item._renderCmd)
  7627. item._renderCmd.detachFromParent();
  7628. }
  7629. };
  7630. proto.setShaderProgram = function (shaderProgram) {
  7631. };
  7632. proto.getShaderProgram = function () {
  7633. return null;
  7634. };
  7635. cc.Node.CanvasRenderCmd._getCompositeOperationByBlendFunc = function (blendFunc) {
  7636. if (!blendFunc)
  7637. return "source-over";
  7638. else {
  7639. if (( blendFunc.src === cc.SRC_ALPHA && blendFunc.dst === cc.ONE) || (blendFunc.src === cc.ONE && blendFunc.dst === cc.ONE))
  7640. return "lighter";
  7641. else if (blendFunc.src === cc.ZERO && blendFunc.dst === cc.SRC_ALPHA)
  7642. return "destination-in";
  7643. else if (blendFunc.src === cc.ZERO && blendFunc.dst === cc.ONE_MINUS_SRC_ALPHA)
  7644. return "destination-out";
  7645. else
  7646. return "source-over";
  7647. }
  7648. };
  7649. })();
  7650. cc._tmp.PrototypeTexture2D = function () {
  7651. var _c = cc.Texture2D;
  7652. _c.PVRImagesHavePremultipliedAlpha = function (haveAlphaPremultiplied) {
  7653. cc.PVRHaveAlphaPremultiplied_ = haveAlphaPremultiplied;
  7654. };
  7655. _c.PIXEL_FORMAT_RGBA8888 = 2;
  7656. _c.PIXEL_FORMAT_RGB888 = 3;
  7657. _c.PIXEL_FORMAT_RGB565 = 4;
  7658. _c.PIXEL_FORMAT_A8 = 5;
  7659. _c.PIXEL_FORMAT_I8 = 6;
  7660. _c.PIXEL_FORMAT_AI88 = 7;
  7661. _c.PIXEL_FORMAT_RGBA4444 = 8;
  7662. _c.PIXEL_FORMAT_RGB5A1 = 7;
  7663. _c.PIXEL_FORMAT_PVRTC4 = 9;
  7664. _c.PIXEL_FORMAT_PVRTC2 = 10;
  7665. _c.PIXEL_FORMAT_DEFAULT = _c.PIXEL_FORMAT_RGBA8888;
  7666. _c.defaultPixelFormat = _c.PIXEL_FORMAT_DEFAULT;
  7667. var _M = cc.Texture2D._M = {};
  7668. _M[_c.PIXEL_FORMAT_RGBA8888] = "RGBA8888";
  7669. _M[_c.PIXEL_FORMAT_RGB888] = "RGB888";
  7670. _M[_c.PIXEL_FORMAT_RGB565] = "RGB565";
  7671. _M[_c.PIXEL_FORMAT_A8] = "A8";
  7672. _M[_c.PIXEL_FORMAT_I8] = "I8";
  7673. _M[_c.PIXEL_FORMAT_AI88] = "AI88";
  7674. _M[_c.PIXEL_FORMAT_RGBA4444] = "RGBA4444";
  7675. _M[_c.PIXEL_FORMAT_RGB5A1] = "RGB5A1";
  7676. _M[_c.PIXEL_FORMAT_PVRTC4] = "PVRTC4";
  7677. _M[_c.PIXEL_FORMAT_PVRTC2] = "PVRTC2";
  7678. var _B = cc.Texture2D._B = {};
  7679. _B[_c.PIXEL_FORMAT_RGBA8888] = 32;
  7680. _B[_c.PIXEL_FORMAT_RGB888] = 24;
  7681. _B[_c.PIXEL_FORMAT_RGB565] = 16;
  7682. _B[_c.PIXEL_FORMAT_A8] = 8;
  7683. _B[_c.PIXEL_FORMAT_I8] = 8;
  7684. _B[_c.PIXEL_FORMAT_AI88] = 16;
  7685. _B[_c.PIXEL_FORMAT_RGBA4444] = 16;
  7686. _B[_c.PIXEL_FORMAT_RGB5A1] = 16;
  7687. _B[_c.PIXEL_FORMAT_PVRTC4] = 4;
  7688. _B[_c.PIXEL_FORMAT_PVRTC2] = 3;
  7689. var _p = cc.Texture2D.prototype;
  7690. _p.name;
  7691. cc.defineGetterSetter(_p, "name", _p.getName);
  7692. _p.pixelFormat;
  7693. cc.defineGetterSetter(_p, "pixelFormat", _p.getPixelFormat);
  7694. _p.pixelsWidth;
  7695. cc.defineGetterSetter(_p, "pixelsWidth", _p.getPixelsWide);
  7696. _p.pixelsHeight;
  7697. cc.defineGetterSetter(_p, "pixelsHeight", _p.getPixelsHigh);
  7698. _p.width;
  7699. cc.defineGetterSetter(_p, "width", _p._getWidth);
  7700. _p.height;
  7701. cc.defineGetterSetter(_p, "height", _p._getHeight);
  7702. };
  7703. cc._tmp.PrototypeTextureAtlas = function () {
  7704. var _p = cc.TextureAtlas.prototype;
  7705. _p.totalQuads;
  7706. cc.defineGetterSetter(_p, "totalQuads", _p.getTotalQuads);
  7707. _p.capacity;
  7708. cc.defineGetterSetter(_p, "capacity", _p.getCapacity);
  7709. _p.quads;
  7710. cc.defineGetterSetter(_p, "quads", _p.getQuads, _p.setQuads);
  7711. };
  7712. cc._tmp.WebGLTexture2D = function () {
  7713. cc.Texture2D = cc.Class.extend({
  7714. _pVRHaveAlphaPremultiplied: true,
  7715. _pixelFormat: null,
  7716. _pixelsWide: 0,
  7717. _pixelsHigh: 0,
  7718. _name: "",
  7719. _contentSize: null,
  7720. maxS: 0,
  7721. maxT: 0,
  7722. _hasPremultipliedAlpha: false,
  7723. _hasMipmaps: false,
  7724. shaderProgram: null,
  7725. _textureLoaded: false,
  7726. _htmlElementObj: null,
  7727. _webTextureObj: null,
  7728. url: null,
  7729. ctor: function () {
  7730. this._contentSize = cc.size(0, 0);
  7731. this._pixelFormat = cc.Texture2D.defaultPixelFormat;
  7732. },
  7733. releaseTexture: function () {
  7734. if (this._webTextureObj)
  7735. cc._renderContext.deleteTexture(this._webTextureObj);
  7736. cc.loader.release(this.url);
  7737. },
  7738. getPixelFormat: function () {
  7739. return this._pixelFormat;
  7740. },
  7741. getPixelsWide: function () {
  7742. return this._pixelsWide;
  7743. },
  7744. getPixelsHigh: function () {
  7745. return this._pixelsHigh;
  7746. },
  7747. getName: function () {
  7748. return this._webTextureObj;
  7749. },
  7750. getContentSize: function () {
  7751. return cc.size(this._contentSize.width / cc.contentScaleFactor(), this._contentSize.height / cc.contentScaleFactor());
  7752. },
  7753. _getWidth: function () {
  7754. return this._contentSize.width / cc.contentScaleFactor();
  7755. },
  7756. _getHeight: function () {
  7757. return this._contentSize.height / cc.contentScaleFactor();
  7758. },
  7759. getContentSizeInPixels: function () {
  7760. return this._contentSize;
  7761. },
  7762. getMaxS: function () {
  7763. return this.maxS;
  7764. },
  7765. setMaxS: function (maxS) {
  7766. this.maxS = maxS;
  7767. },
  7768. getMaxT: function () {
  7769. return this.maxT;
  7770. },
  7771. setMaxT: function (maxT) {
  7772. this.maxT = maxT;
  7773. },
  7774. getShaderProgram: function () {
  7775. return this.shaderProgram;
  7776. },
  7777. setShaderProgram: function (shaderProgram) {
  7778. this.shaderProgram = shaderProgram;
  7779. },
  7780. hasPremultipliedAlpha: function () {
  7781. return this._hasPremultipliedAlpha;
  7782. },
  7783. hasMipmaps: function () {
  7784. return this._hasMipmaps;
  7785. },
  7786. description: function () {
  7787. var _t = this;
  7788. return "<cc.Texture2D | Name = " + _t._name + " | Dimensions = " + _t._pixelsWide + " x " + _t._pixelsHigh
  7789. + " | Coordinates = (" + _t.maxS + ", " + _t.maxT + ")>";
  7790. },
  7791. releaseData: function (data) {
  7792. data = null;
  7793. },
  7794. keepData: function (data, length) {
  7795. return data;
  7796. },
  7797. initWithData: function (data, pixelFormat, pixelsWide, pixelsHigh, contentSize) {
  7798. var self = this, tex2d = cc.Texture2D;
  7799. var gl = cc._renderContext;
  7800. var format = gl.RGBA, type = gl.UNSIGNED_BYTE;
  7801. var bitsPerPixel = cc.Texture2D._B[pixelFormat];
  7802. var bytesPerRow = pixelsWide * bitsPerPixel / 8;
  7803. if (bytesPerRow % 8 === 0) {
  7804. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 8);
  7805. } else if (bytesPerRow % 4 === 0) {
  7806. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
  7807. } else if (bytesPerRow % 2 === 0) {
  7808. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 2);
  7809. } else {
  7810. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  7811. }
  7812. self._webTextureObj = gl.createTexture();
  7813. cc.glBindTexture2D(self);
  7814. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  7815. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  7816. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7817. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7818. switch (pixelFormat) {
  7819. case tex2d.PIXEL_FORMAT_RGBA8888:
  7820. format = gl.RGBA;
  7821. break;
  7822. case tex2d.PIXEL_FORMAT_RGB888:
  7823. format = gl.RGB;
  7824. break;
  7825. case tex2d.PIXEL_FORMAT_RGBA4444:
  7826. type = gl.UNSIGNED_SHORT_4_4_4_4;
  7827. break;
  7828. case tex2d.PIXEL_FORMAT_RGB5A1:
  7829. type = gl.UNSIGNED_SHORT_5_5_5_1;
  7830. break;
  7831. case tex2d.PIXEL_FORMAT_RGB565:
  7832. type = gl.UNSIGNED_SHORT_5_6_5;
  7833. break;
  7834. case tex2d.PIXEL_FORMAT_AI88:
  7835. format = gl.LUMINANCE_ALPHA;
  7836. break;
  7837. case tex2d.PIXEL_FORMAT_A8:
  7838. format = gl.ALPHA;
  7839. break;
  7840. case tex2d.PIXEL_FORMAT_I8:
  7841. format = gl.LUMINANCE;
  7842. break;
  7843. default:
  7844. cc.assert(0, cc._LogInfos.Texture2D_initWithData);
  7845. }
  7846. gl.texImage2D(gl.TEXTURE_2D, 0, format, pixelsWide, pixelsHigh, 0, format, type, data);
  7847. self._contentSize.width = contentSize.width;
  7848. self._contentSize.height = contentSize.height;
  7849. self._pixelsWide = pixelsWide;
  7850. self._pixelsHigh = pixelsHigh;
  7851. self._pixelFormat = pixelFormat;
  7852. self.maxS = contentSize.width / pixelsWide;
  7853. self.maxT = contentSize.height / pixelsHigh;
  7854. self._hasPremultipliedAlpha = false;
  7855. self._hasMipmaps = false;
  7856. self.shaderProgram = cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURE);
  7857. self._textureLoaded = true;
  7858. return true;
  7859. },
  7860. drawAtPoint: function (point) {
  7861. var self = this;
  7862. var coordinates = [
  7863. 0.0, self.maxT,
  7864. self.maxS, self.maxT,
  7865. 0.0, 0.0,
  7866. self.maxS, 0.0 ],
  7867. gl = cc._renderContext;
  7868. var width = self._pixelsWide * self.maxS,
  7869. height = self._pixelsHigh * self.maxT;
  7870. var vertices = [
  7871. point.x, point.y, 0.0,
  7872. width + point.x, point.y, 0.0,
  7873. point.x, height + point.y, 0.0,
  7874. width + point.x, height + point.y, 0.0 ];
  7875. self._shaderProgram.use();
  7876. self._shaderProgram.setUniformsForBuiltins();
  7877. cc.glBindTexture2D(self);
  7878. gl.enableVertexAttribArray(cc.VERTEX_ATTRIB_POSITION);
  7879. gl.enableVertexAttribArray(cc.VERTEX_ATTRIB_TEX_COORDS);
  7880. gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, vertices);
  7881. gl.vertexAttribPointer(cc.VERTEX_ATTRIB_TEX_COORDS, 2, gl.FLOAT, false, 0, coordinates);
  7882. gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
  7883. },
  7884. drawInRect: function (rect) {
  7885. var self = this;
  7886. var coordinates = [
  7887. 0.0, self.maxT,
  7888. self.maxS, self.maxT,
  7889. 0.0, 0.0,
  7890. self.maxS, 0.0];
  7891. var vertices = [ rect.x, rect.y,
  7892. rect.x + rect.width, rect.y,
  7893. rect.x, rect.y + rect.height,
  7894. rect.x + rect.width, rect.y + rect.height ];
  7895. self._shaderProgram.use();
  7896. self._shaderProgram.setUniformsForBuiltins();
  7897. cc.glBindTexture2D(self);
  7898. var gl = cc._renderContext;
  7899. gl.enableVertexAttribArray(cc.VERTEX_ATTRIB_POSITION);
  7900. gl.enableVertexAttribArray(cc.VERTEX_ATTRIB_TEX_COORDS);
  7901. gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, vertices);
  7902. gl.vertexAttribPointer(cc.VERTEX_ATTRIB_TEX_COORDS, 2, gl.FLOAT, false, 0, coordinates);
  7903. gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
  7904. },
  7905. initWithImage: function (uiImage) {
  7906. if (uiImage == null) {
  7907. cc.log(cc._LogInfos.Texture2D_initWithImage);
  7908. return false;
  7909. }
  7910. var imageWidth = uiImage.getWidth();
  7911. var imageHeight = uiImage.getHeight();
  7912. var maxTextureSize = cc.configuration.getMaxTextureSize();
  7913. if (imageWidth > maxTextureSize || imageHeight > maxTextureSize) {
  7914. cc.log(cc._LogInfos.Texture2D_initWithImage_2, imageWidth, imageHeight, maxTextureSize, maxTextureSize);
  7915. return false;
  7916. }
  7917. this._textureLoaded = true;
  7918. return this._initPremultipliedATextureWithImage(uiImage, imageWidth, imageHeight);
  7919. },
  7920. initWithElement: function (element) {
  7921. if (!element)
  7922. return;
  7923. this._webTextureObj = cc._renderContext.createTexture();
  7924. this._htmlElementObj = element;
  7925. this._textureLoaded = true;
  7926. this._hasPremultipliedAlpha = true;
  7927. },
  7928. getHtmlElementObj: function () {
  7929. return this._htmlElementObj;
  7930. },
  7931. isLoaded: function () {
  7932. return this._textureLoaded;
  7933. },
  7934. handleLoadedTexture: function (premultiplied) {
  7935. var self = this;
  7936. premultiplied =
  7937. (premultiplied !== undefined)
  7938. ? premultiplied
  7939. : self._hasPremultipliedAlpha;
  7940. if (!cc.game._rendererInitialized)
  7941. return;
  7942. if (!self._htmlElementObj) {
  7943. var img = cc.loader.getRes(self.url);
  7944. if (!img) return;
  7945. self.initWithElement(img);
  7946. }
  7947. if (!self._htmlElementObj.width || !self._htmlElementObj.height)
  7948. return;
  7949. var gl = cc._renderContext;
  7950. cc.glBindTexture2D(self);
  7951. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
  7952. if(premultiplied)
  7953. gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  7954. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, self._htmlElementObj);
  7955. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  7956. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  7957. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7958. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7959. self.shaderProgram = cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURE);
  7960. cc.glBindTexture2D(null);
  7961. if(premultiplied)
  7962. gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  7963. var pixelsWide = self._htmlElementObj.width;
  7964. var pixelsHigh = self._htmlElementObj.height;
  7965. self._pixelsWide = self._contentSize.width = pixelsWide;
  7966. self._pixelsHigh = self._contentSize.height = pixelsHigh;
  7967. self._pixelFormat = cc.Texture2D.PIXEL_FORMAT_RGBA8888;
  7968. self.maxS = 1;
  7969. self.maxT = 1;
  7970. self._hasPremultipliedAlpha = premultiplied;
  7971. self._hasMipmaps = false;
  7972. self.dispatchEvent("load");
  7973. },
  7974. initWithString: function (text, fontName, fontSize, dimensions, hAlignment, vAlignment) {
  7975. cc.log(cc._LogInfos.Texture2D_initWithString);
  7976. return null;
  7977. },
  7978. initWithETCFile: function (file) {
  7979. cc.log(cc._LogInfos.Texture2D_initWithETCFile_2);
  7980. return false;
  7981. },
  7982. initWithPVRFile: function (file) {
  7983. cc.log(cc._LogInfos.Texture2D_initWithPVRFile_2);
  7984. return false;
  7985. },
  7986. initWithPVRTCData: function (data, level, bpp, hasAlpha, length, pixelFormat) {
  7987. cc.log(cc._LogInfos.Texture2D_initWithPVRTCData_2);
  7988. return false;
  7989. },
  7990. setTexParameters: function (texParams, magFilter, wrapS, wrapT) {
  7991. var _t = this;
  7992. var gl = cc._renderContext;
  7993. if(magFilter !== undefined)
  7994. texParams = {minFilter: texParams, magFilter: magFilter, wrapS: wrapS, wrapT: wrapT};
  7995. cc.assert((_t._pixelsWide === cc.NextPOT(_t._pixelsWide) && _t._pixelsHigh === cc.NextPOT(_t._pixelsHigh)) ||
  7996. (texParams.wrapS === gl.CLAMP_TO_EDGE && texParams.wrapT === gl.CLAMP_TO_EDGE),
  7997. "WebGLRenderingContext.CLAMP_TO_EDGE should be used in NPOT textures");
  7998. cc.glBindTexture2D(_t);
  7999. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, texParams.minFilter);
  8000. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, texParams.magFilter);
  8001. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, texParams.wrapS);
  8002. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, texParams.wrapT);
  8003. },
  8004. setAntiAliasTexParameters: function () {
  8005. var gl = cc._renderContext;
  8006. cc.glBindTexture2D(this);
  8007. if (!this._hasMipmaps)
  8008. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  8009. else
  8010. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST);
  8011. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8012. },
  8013. setAliasTexParameters: function () {
  8014. var gl = cc._renderContext;
  8015. cc.glBindTexture2D(this);
  8016. if (!this._hasMipmaps)
  8017. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8018. else
  8019. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST_MIPMAP_NEAREST);
  8020. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8021. },
  8022. generateMipmap: function () {
  8023. var _t = this;
  8024. cc.assert(_t._pixelsWide === cc.NextPOT(_t._pixelsWide) && _t._pixelsHigh === cc.NextPOT(_t._pixelsHigh), "Mimpap texture only works in POT textures");
  8025. cc.glBindTexture2D(_t);
  8026. cc._renderContext.generateMipmap(cc._renderContext.TEXTURE_2D);
  8027. _t._hasMipmaps = true;
  8028. },
  8029. stringForFormat: function () {
  8030. return cc.Texture2D._M[this._pixelFormat];
  8031. },
  8032. bitsPerPixelForFormat: function (format) {//TODO I want to delete the format argument, use this._pixelFormat
  8033. format = format || this._pixelFormat;
  8034. var value = cc.Texture2D._B[format];
  8035. if (value != null) return value;
  8036. cc.log(cc._LogInfos.Texture2D_bitsPerPixelForFormat, format);
  8037. return -1;
  8038. },
  8039. _initPremultipliedATextureWithImage: function (uiImage, width, height) {
  8040. var tex2d = cc.Texture2D;
  8041. var tempData = uiImage.getData();
  8042. var inPixel32 = null;
  8043. var inPixel8 = null;
  8044. var outPixel16 = null;
  8045. var hasAlpha = uiImage.hasAlpha();
  8046. var imageSize = cc.size(uiImage.getWidth(), uiImage.getHeight());
  8047. var pixelFormat = tex2d.defaultPixelFormat;
  8048. var bpp = uiImage.getBitsPerComponent();
  8049. var i;
  8050. if (!hasAlpha) {
  8051. if (bpp >= 8) {
  8052. pixelFormat = tex2d.PIXEL_FORMAT_RGB888;
  8053. } else {
  8054. cc.log(cc._LogInfos.Texture2D__initPremultipliedATextureWithImage);
  8055. pixelFormat = tex2d.PIXEL_FORMAT_RGB565;
  8056. }
  8057. }
  8058. var length = width * height;
  8059. if (pixelFormat === tex2d.PIXEL_FORMAT_RGB565) {
  8060. if (hasAlpha) {
  8061. tempData = new Uint16Array(width * height);
  8062. inPixel32 = uiImage.getData();
  8063. for (i = 0; i < length; ++i) {
  8064. tempData[i] =
  8065. ((((inPixel32[i] >> 0) & 0xFF) >> 3) << 11) |
  8066. ((((inPixel32[i] >> 8) & 0xFF) >> 2) << 5) |
  8067. ((((inPixel32[i] >> 16) & 0xFF) >> 3) << 0);
  8068. }
  8069. } else {
  8070. tempData = new Uint16Array(width * height);
  8071. inPixel8 = uiImage.getData();
  8072. for (i = 0; i < length; ++i) {
  8073. tempData[i] =
  8074. (((inPixel8[i] & 0xFF) >> 3) << 11) |
  8075. (((inPixel8[i] & 0xFF) >> 2) << 5) |
  8076. (((inPixel8[i] & 0xFF) >> 3) << 0);
  8077. }
  8078. }
  8079. } else if (pixelFormat === tex2d.PIXEL_FORMAT_RGBA4444) {
  8080. tempData = new Uint16Array(width * height);
  8081. inPixel32 = uiImage.getData();
  8082. for (i = 0; i < length; ++i) {
  8083. tempData[i] =
  8084. ((((inPixel32[i] >> 0) & 0xFF) >> 4) << 12) |
  8085. ((((inPixel32[i] >> 8) & 0xFF) >> 4) << 8) |
  8086. ((((inPixel32[i] >> 16) & 0xFF) >> 4) << 4) |
  8087. ((((inPixel32[i] >> 24) & 0xFF) >> 4) << 0);
  8088. }
  8089. } else if (pixelFormat === tex2d.PIXEL_FORMAT_RGB5A1) {
  8090. tempData = new Uint16Array(width * height);
  8091. inPixel32 = uiImage.getData();
  8092. for (i = 0; i < length; ++i) {
  8093. tempData[i] =
  8094. ((((inPixel32[i] >> 0) & 0xFF) >> 3) << 11) |
  8095. ((((inPixel32[i] >> 8) & 0xFF) >> 3) << 6) |
  8096. ((((inPixel32[i] >> 16) & 0xFF) >> 3) << 1) |
  8097. ((((inPixel32[i] >> 24) & 0xFF) >> 7) << 0);
  8098. }
  8099. } else if (pixelFormat === tex2d.PIXEL_FORMAT_A8) {
  8100. tempData = new Uint8Array(width * height);
  8101. inPixel32 = uiImage.getData();
  8102. for (i = 0; i < length; ++i) {
  8103. tempData[i] = (inPixel32 >> 24) & 0xFF;
  8104. }
  8105. }
  8106. if (hasAlpha && pixelFormat === tex2d.PIXEL_FORMAT_RGB888) {
  8107. inPixel32 = uiImage.getData();
  8108. tempData = new Uint8Array(width * height * 3);
  8109. for (i = 0; i < length; ++i) {
  8110. tempData[i * 3] = (inPixel32 >> 0) & 0xFF;
  8111. tempData[i * 3 + 1] = (inPixel32 >> 8) & 0xFF;
  8112. tempData[i * 3 + 2] = (inPixel32 >> 16) & 0xFF;
  8113. }
  8114. }
  8115. this.initWithData(tempData, pixelFormat, width, height, imageSize);
  8116. if (tempData != uiImage.getData())
  8117. tempData = null;
  8118. this._hasPremultipliedAlpha = uiImage.isPremultipliedAlpha();
  8119. return true;
  8120. },
  8121. addLoadedEventListener: function (callback, target) {
  8122. this.addEventListener("load", callback, target);
  8123. },
  8124. removeLoadedEventListener: function (target) {
  8125. this.removeEventTarget("load", target);
  8126. }
  8127. });
  8128. };
  8129. cc._tmp.WebGLTextureAtlas = function () {
  8130. var _p = cc.TextureAtlas.prototype;
  8131. _p._setupVBO = function () {
  8132. var _t = this;
  8133. var gl = cc._renderContext;
  8134. _t._buffersVBO[0] = gl.createBuffer();
  8135. _t._buffersVBO[1] = gl.createBuffer();
  8136. _t._quadsWebBuffer = gl.createBuffer();
  8137. _t._mapBuffers();
  8138. };
  8139. _p._mapBuffers = function () {
  8140. var _t = this;
  8141. var gl = cc._renderContext;
  8142. gl.bindBuffer(gl.ARRAY_BUFFER, _t._quadsWebBuffer);
  8143. gl.bufferData(gl.ARRAY_BUFFER, _t._quadsArrayBuffer, gl.DYNAMIC_DRAW);
  8144. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, _t._buffersVBO[1]);
  8145. gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, _t._indices, gl.STATIC_DRAW);
  8146. };
  8147. _p.drawNumberOfQuads = function (n, start) {
  8148. var _t = this;
  8149. start = start || 0;
  8150. if (0 === n || !_t.texture || !_t.texture.isLoaded())
  8151. return;
  8152. var gl = cc._renderContext;
  8153. cc.glBindTexture2D(_t.texture);
  8154. gl.bindBuffer(gl.ARRAY_BUFFER, _t._quadsWebBuffer);
  8155. if (_t.dirty){
  8156. gl.bufferData(gl.ARRAY_BUFFER, _t._quadsArrayBuffer, gl.DYNAMIC_DRAW);
  8157. _t.dirty = false;
  8158. }
  8159. gl.enableVertexAttribArray(cc.VERTEX_ATTRIB_POSITION);
  8160. gl.enableVertexAttribArray(cc.VERTEX_ATTRIB_COLOR);
  8161. gl.enableVertexAttribArray(cc.VERTEX_ATTRIB_TEX_COORDS);
  8162. gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 3, gl.FLOAT, false, 24, 0);
  8163. gl.vertexAttribPointer(cc.VERTEX_ATTRIB_COLOR, 4, gl.UNSIGNED_BYTE, true, 24, 12);
  8164. gl.vertexAttribPointer(cc.VERTEX_ATTRIB_TEX_COORDS, 2, gl.FLOAT, false, 24, 16);
  8165. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, _t._buffersVBO[1]);
  8166. if (cc.TEXTURE_ATLAS_USE_TRIANGLE_STRIP)
  8167. gl.drawElements(gl.TRIANGLE_STRIP, n * 6, gl.UNSIGNED_SHORT, start * 6 * _t._indices.BYTES_PER_ELEMENT);
  8168. else
  8169. gl.drawElements(gl.TRIANGLES, n * 6, gl.UNSIGNED_SHORT, start * 6 * _t._indices.BYTES_PER_ELEMENT);
  8170. cc.g_NumberOfDraws++;
  8171. };
  8172. };
  8173. cc._tmp.WebGLTextureCache = function () {
  8174. var _p = cc.textureCache;
  8175. _p.handleLoadedTexture = function (url) {
  8176. var locTexs = this._textures, tex, ext;
  8177. if (!cc.game._rendererInitialized) {
  8178. locTexs = this._loadedTexturesBefore;
  8179. }
  8180. tex = locTexs[url];
  8181. if (!tex) {
  8182. tex = locTexs[url] = new cc.Texture2D();
  8183. tex.url = url;
  8184. }
  8185. ext = cc.path.extname(url);
  8186. if (ext === ".png") {
  8187. tex.handleLoadedTexture(true);
  8188. }
  8189. else {
  8190. tex.handleLoadedTexture();
  8191. }
  8192. };
  8193. _p.addImage = function (url, cb, target) {
  8194. cc.assert(url, cc._LogInfos.Texture2D_addImage_2);
  8195. var locTexs = this._textures;
  8196. if (!cc.game._rendererInitialized) {
  8197. locTexs = this._loadedTexturesBefore;
  8198. }
  8199. var tex = locTexs[url] || locTexs[cc.loader._getAliase(url)];
  8200. if (tex) {
  8201. if(tex.isLoaded()) {
  8202. cb && cb.call(target, tex);
  8203. return tex;
  8204. }
  8205. else
  8206. {
  8207. tex.addEventListener("load", function(){
  8208. cb && cb.call(target, tex);
  8209. }, target);
  8210. return tex;
  8211. }
  8212. }
  8213. tex = locTexs[url] = new cc.Texture2D();
  8214. tex.url = url;
  8215. var basePath = cc.loader.getBasePath ? cc.loader.getBasePath() : cc.loader.resPath;
  8216. cc.loader.loadImg(cc.path.join(basePath || "", url), function (err, img) {
  8217. if (err)
  8218. return cb && cb.call(target, err);
  8219. if (!cc.loader.cache[url]) {
  8220. cc.loader.cache[url] = img;
  8221. }
  8222. cc.textureCache.handleLoadedTexture(url);
  8223. var texResult = locTexs[url];
  8224. cb && cb.call(target, texResult);
  8225. });
  8226. return tex;
  8227. };
  8228. _p.addImageAsync = _p.addImage;
  8229. _p = null;
  8230. };
  8231. cc.ALIGN_CENTER = 0x33;
  8232. cc.ALIGN_TOP = 0x13;
  8233. cc.ALIGN_TOP_RIGHT = 0x12;
  8234. cc.ALIGN_RIGHT = 0x32;
  8235. cc.ALIGN_BOTTOM_RIGHT = 0x22;
  8236. cc.ALIGN_BOTTOM = 0x23;
  8237. cc.ALIGN_BOTTOM_LEFT = 0x21;
  8238. cc.ALIGN_LEFT = 0x31;
  8239. cc.ALIGN_TOP_LEFT = 0x11;
  8240. cc.PVRHaveAlphaPremultiplied_ = false;
  8241. cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
  8242. if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) {
  8243. var proto = {
  8244. _contentSize: null,
  8245. _textureLoaded: false,
  8246. _htmlElementObj: null,
  8247. url: null,
  8248. _pattern: null,
  8249. ctor: function () {
  8250. this._contentSize = cc.size(0, 0);
  8251. this._textureLoaded = false;
  8252. this._htmlElementObj = null;
  8253. this._pattern = "";
  8254. },
  8255. getPixelsWide: function () {
  8256. return this._contentSize.width;
  8257. },
  8258. getPixelsHigh: function () {
  8259. return this._contentSize.height;
  8260. },
  8261. getContentSize: function () {
  8262. var locScaleFactor = cc.contentScaleFactor();
  8263. return cc.size(this._contentSize.width / locScaleFactor, this._contentSize.height / locScaleFactor);
  8264. },
  8265. _getWidth: function () {
  8266. return this._contentSize.width / cc.contentScaleFactor();
  8267. },
  8268. _getHeight: function () {
  8269. return this._contentSize.height / cc.contentScaleFactor();
  8270. },
  8271. getContentSizeInPixels: function () {
  8272. return this._contentSize;
  8273. },
  8274. initWithElement: function (element) {
  8275. if (!element)
  8276. return;
  8277. this._htmlElementObj = element;
  8278. this._contentSize.width = element.width;
  8279. this._contentSize.height = element.height;
  8280. this._textureLoaded = true;
  8281. },
  8282. getHtmlElementObj: function () {
  8283. return this._htmlElementObj;
  8284. },
  8285. isLoaded: function () {
  8286. return this._textureLoaded;
  8287. },
  8288. handleLoadedTexture: function () {
  8289. var self = this;
  8290. if (self._textureLoaded) return;
  8291. if (!self._htmlElementObj) {
  8292. var img = cc.loader.getRes(self.url);
  8293. if (!img) return;
  8294. self.initWithElement(img);
  8295. }
  8296. var locElement = self._htmlElementObj;
  8297. self._contentSize.width = locElement.width;
  8298. self._contentSize.height = locElement.height;
  8299. self.dispatchEvent("load");
  8300. },
  8301. description: function () {
  8302. return "<cc.Texture2D | width = " + this._contentSize.width + " height " + this._contentSize.height + ">";
  8303. },
  8304. initWithData: function (data, pixelFormat, pixelsWide, pixelsHigh, contentSize) {
  8305. return false;
  8306. },
  8307. initWithImage: function (uiImage) {
  8308. return false;
  8309. },
  8310. initWithString: function (text, fontName, fontSize, dimensions, hAlignment, vAlignment) {
  8311. return false;
  8312. },
  8313. releaseTexture: function () {
  8314. cc.loader.release(this.url);
  8315. },
  8316. getName: function () {
  8317. return null;
  8318. },
  8319. getMaxS: function () {
  8320. return 1;
  8321. },
  8322. setMaxS: function (maxS) {
  8323. },
  8324. getMaxT: function () {
  8325. return 1;
  8326. },
  8327. setMaxT: function (maxT) {
  8328. },
  8329. getPixelFormat: function () {
  8330. return null;
  8331. },
  8332. getShaderProgram: function () {
  8333. return null;
  8334. },
  8335. setShaderProgram: function (shaderProgram) {
  8336. },
  8337. hasPremultipliedAlpha: function () {
  8338. return false;
  8339. },
  8340. hasMipmaps: function () {
  8341. return false;
  8342. },
  8343. releaseData: function (data) {
  8344. data = null;
  8345. },
  8346. keepData: function (data, length) {
  8347. return data;
  8348. },
  8349. drawAtPoint: function (point) {
  8350. },
  8351. drawInRect: function (rect) {
  8352. },
  8353. initWithETCFile: function (file) {
  8354. cc.log(cc._LogInfos.Texture2D_initWithETCFile);
  8355. return false;
  8356. },
  8357. initWithPVRFile: function (file) {
  8358. cc.log(cc._LogInfos.Texture2D_initWithPVRFile);
  8359. return false;
  8360. },
  8361. initWithPVRTCData: function (data, level, bpp, hasAlpha, length, pixelFormat) {
  8362. cc.log(cc._LogInfos.Texture2D_initWithPVRTCData);
  8363. return false;
  8364. },
  8365. setTexParameters: function (texParams, magFilter, wrapS, wrapT) {
  8366. if(magFilter !== undefined)
  8367. texParams = {minFilter: texParams, magFilter: magFilter, wrapS: wrapS, wrapT: wrapT};
  8368. if(texParams.wrapS === cc.REPEAT && texParams.wrapT === cc.REPEAT){
  8369. this._pattern = "repeat";
  8370. return;
  8371. }
  8372. if(texParams.wrapS === cc.REPEAT ){
  8373. this._pattern = "repeat-x";
  8374. return;
  8375. }
  8376. if(texParams.wrapT === cc.REPEAT){
  8377. this._pattern = "repeat-y";
  8378. return;
  8379. }
  8380. this._pattern = "";
  8381. },
  8382. setAntiAliasTexParameters: function () {
  8383. },
  8384. setAliasTexParameters: function () {
  8385. },
  8386. generateMipmap: function () {
  8387. },
  8388. stringForFormat: function () {
  8389. return "";
  8390. },
  8391. bitsPerPixelForFormat: function (format) {
  8392. return -1;
  8393. },
  8394. addLoadedEventListener: function (callback, target) {
  8395. this.addEventListener("load", callback, target);
  8396. },
  8397. removeLoadedEventListener: function (target) {
  8398. this.removeEventTarget("load", target);
  8399. },
  8400. _generateColorTexture: function(){},
  8401. _generateTextureCacheForColor: function(){
  8402. if (this.channelCache)
  8403. return this.channelCache;
  8404. var textureCache = [
  8405. document.createElement("canvas"),
  8406. document.createElement("canvas"),
  8407. document.createElement("canvas"),
  8408. document.createElement("canvas")
  8409. ];
  8410. renderToCache(this._htmlElementObj, textureCache);
  8411. return this.channelCache = textureCache;
  8412. },
  8413. _grayElementObj: null,
  8414. _backupElement: null,
  8415. _isGray: false,
  8416. _switchToGray: function(toGray){
  8417. if(!this._textureLoaded || this._isGray === toGray)
  8418. return;
  8419. this._isGray = toGray;
  8420. if(this._isGray){
  8421. this._backupElement = this._htmlElementObj;
  8422. if(!this._grayElementObj)
  8423. this._grayElementObj = cc.Texture2D._generateGrayTexture(this._htmlElementObj);
  8424. this._htmlElementObj = this._grayElementObj;
  8425. } else {
  8426. if(this._backupElement !== null)
  8427. this._htmlElementObj = this._backupElement;
  8428. }
  8429. }
  8430. };
  8431. var renderToCache = function(image, cache){
  8432. var w = image.width;
  8433. var h = image.height;
  8434. cache[0].width = w;
  8435. cache[0].height = h;
  8436. cache[1].width = w;
  8437. cache[1].height = h;
  8438. cache[2].width = w;
  8439. cache[2].height = h;
  8440. cache[3].width = w;
  8441. cache[3].height = h;
  8442. var cacheCtx = cache[3].getContext("2d");
  8443. cacheCtx.drawImage(image, 0, 0);
  8444. var pixels = cacheCtx.getImageData(0, 0, w, h).data;
  8445. var ctx;
  8446. for (var rgbI = 0; rgbI < 4; rgbI++) {
  8447. ctx = cache[rgbI].getContext("2d");
  8448. var to = ctx.getImageData(0, 0, w, h);
  8449. var data = to.data;
  8450. for (var i = 0; i < pixels.length; i += 4) {
  8451. data[i ] = (rgbI === 0) ? pixels[i ] : 0;
  8452. data[i + 1] = (rgbI === 1) ? pixels[i + 1] : 0;
  8453. data[i + 2] = (rgbI === 2) ? pixels[i + 2] : 0;
  8454. data[i + 3] = pixels[i + 3];
  8455. }
  8456. ctx.putImageData(to, 0, 0);
  8457. }
  8458. image.onload = null;
  8459. };
  8460. if(cc.sys._supportCanvasNewBlendModes){
  8461. proto._generateColorTexture = function(r, g, b, rect, canvas){
  8462. var onlyCanvas = false;
  8463. if(canvas)
  8464. onlyCanvas = true;
  8465. else
  8466. canvas = document.createElement("canvas");
  8467. var textureImage = this._htmlElementObj;
  8468. if(!rect)
  8469. rect = cc.rect(0, 0, textureImage.width, textureImage.height);
  8470. canvas.width = rect.width;
  8471. canvas.height = rect.height;
  8472. var context = canvas.getContext("2d");
  8473. context.globalCompositeOperation = "source-over";
  8474. context.fillStyle = "rgb(" + (r|0) + "," + (g|0) + "," + (b|0) + ")";
  8475. context.fillRect(0, 0, rect.width, rect.height);
  8476. context.globalCompositeOperation = "multiply";
  8477. context.drawImage(
  8478. textureImage,
  8479. rect.x, rect.y, rect.width, rect.height,
  8480. 0, 0, rect.width, rect.height
  8481. );
  8482. context.globalCompositeOperation = "destination-atop";
  8483. context.drawImage(
  8484. textureImage,
  8485. rect.x, rect.y, rect.width, rect.height,
  8486. 0, 0, rect.width, rect.height
  8487. );
  8488. if(onlyCanvas)
  8489. return canvas;
  8490. var newTexture = new cc.Texture2D();
  8491. newTexture.initWithElement(canvas);
  8492. newTexture.handleLoadedTexture();
  8493. return newTexture;
  8494. };
  8495. }else{
  8496. proto._generateColorTexture = function(r, g, b, rect, canvas){
  8497. var onlyCanvas = false;
  8498. if(canvas)
  8499. onlyCanvas = true;
  8500. else
  8501. canvas = document.createElement("canvas");
  8502. var textureImage = this._htmlElementObj;
  8503. if(!rect)
  8504. rect = cc.rect(0, 0, textureImage.width, textureImage.height);
  8505. var x, y, w, h;
  8506. x = rect.x; y = rect.y; w = rect.width; h = rect.height;
  8507. if(!w || !h)
  8508. return;
  8509. canvas.width = w;
  8510. canvas.height = h;
  8511. var context = canvas.getContext("2d");
  8512. var tintedImgCache = cc.textureCache.getTextureColors(this);
  8513. context.globalCompositeOperation = 'lighter';
  8514. context.drawImage(
  8515. tintedImgCache[3],
  8516. x, y, w, h,
  8517. 0, 0, w, h
  8518. );
  8519. if (r > 0) {
  8520. context.globalAlpha = r / 255;
  8521. context.drawImage(
  8522. tintedImgCache[0],
  8523. x, y, w, h,
  8524. 0, 0, w, h
  8525. );
  8526. }
  8527. if (g > 0) {
  8528. context.globalAlpha = g / 255;
  8529. context.drawImage(
  8530. tintedImgCache[1],
  8531. x, y, w, h,
  8532. 0, 0, w, h
  8533. );
  8534. }
  8535. if (b > 0) {
  8536. context.globalAlpha = b / 255;
  8537. context.drawImage(
  8538. tintedImgCache[2],
  8539. x, y, w, h,
  8540. 0, 0, w, h
  8541. );
  8542. }
  8543. if(onlyCanvas)
  8544. return canvas;
  8545. var newTexture = new cc.Texture2D();
  8546. newTexture.initWithElement(canvas);
  8547. newTexture.handleLoadedTexture();
  8548. return newTexture;
  8549. };
  8550. }
  8551. cc.Texture2D = cc.Class.extend(proto);
  8552. cc.Texture2D._generateGrayTexture = function(texture, rect, renderCanvas){
  8553. if (texture === null)
  8554. return null;
  8555. renderCanvas = renderCanvas || document.createElement("canvas");
  8556. rect = rect || cc.rect(0, 0, texture.width, texture.height);
  8557. renderCanvas.width = rect.width;
  8558. renderCanvas.height = rect.height;
  8559. var context = renderCanvas.getContext("2d");
  8560. context.drawImage(texture, rect.x, rect.y, rect.width, rect.height, 0, 0, rect.width, rect.height);
  8561. var imgData = context.getImageData(0, 0, rect.width, rect.height);
  8562. var data = imgData.data;
  8563. for (var i = 0, len = data.length; i < len; i += 4) {
  8564. data[i] = data[i + 1] = data[i + 2] = 0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2];
  8565. }
  8566. context.putImageData(imgData, 0, 0);
  8567. return renderCanvas;
  8568. };
  8569. } else if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) {
  8570. cc.assert(cc.isFunction(cc._tmp.WebGLTexture2D), cc._LogInfos.MissingFile, "TexturesWebGL.js");
  8571. cc._tmp.WebGLTexture2D();
  8572. delete cc._tmp.WebGLTexture2D;
  8573. }
  8574. cc.EventHelper.prototype.apply(cc.Texture2D.prototype);
  8575. cc.assert(cc.isFunction(cc._tmp.PrototypeTexture2D), cc._LogInfos.MissingFile, "TexturesPropertyDefine.js");
  8576. cc._tmp.PrototypeTexture2D();
  8577. delete cc._tmp.PrototypeTexture2D;
  8578. });
  8579. cc.textureCache = {
  8580. _textures: {},
  8581. _textureColorsCache: {},
  8582. _textureKeySeq: (0 | Math.random() * 1000),
  8583. _loadedTexturesBefore: {},
  8584. _initializingRenderer: function () {
  8585. var selPath;
  8586. var locLoadedTexturesBefore = this._loadedTexturesBefore, locTextures = this._textures;
  8587. for (selPath in locLoadedTexturesBefore) {
  8588. var tex2d = locLoadedTexturesBefore[selPath];
  8589. tex2d.handleLoadedTexture();
  8590. locTextures[selPath] = tex2d;
  8591. }
  8592. this._loadedTexturesBefore = {};
  8593. },
  8594. addPVRTCImage: function (filename) {
  8595. cc.log(cc._LogInfos.textureCache_addPVRTCImage);
  8596. },
  8597. addETCImage: function (filename) {
  8598. cc.log(cc._LogInfos.textureCache_addETCImage);
  8599. },
  8600. description: function () {
  8601. return "<TextureCache | Number of textures = " + this._textures.length + ">";
  8602. },
  8603. textureForKey: function (textureKeyName) {
  8604. cc.log(cc._LogInfos.textureCache_textureForKey);
  8605. return this.getTextureForKey(textureKeyName);
  8606. },
  8607. getTextureForKey: function(textureKeyName){
  8608. return this._textures[textureKeyName] || this._textures[cc.loader._getAliase(textureKeyName)];
  8609. },
  8610. getKeyByTexture: function (texture) {
  8611. for (var key in this._textures) {
  8612. if (this._textures[key] === texture) {
  8613. return key;
  8614. }
  8615. }
  8616. return null;
  8617. },
  8618. _generalTextureKey: function (id) {
  8619. return "_textureKey_" + id;
  8620. },
  8621. getTextureColors: function (texture) {
  8622. var image = texture._htmlElementObj;
  8623. var key = this.getKeyByTexture(image);
  8624. if (!key) {
  8625. if (image instanceof HTMLImageElement)
  8626. key = image.src;
  8627. else
  8628. key = this._generalTextureKey(texture.__instanceId);
  8629. }
  8630. if (!this._textureColorsCache[key])
  8631. this._textureColorsCache[key] = texture._generateTextureCacheForColor();
  8632. return this._textureColorsCache[key];
  8633. },
  8634. addPVRImage: function (path) {
  8635. cc.log(cc._LogInfos.textureCache_addPVRImage);
  8636. },
  8637. removeAllTextures: function () {
  8638. var locTextures = this._textures;
  8639. for (var selKey in locTextures) {
  8640. if (locTextures[selKey])
  8641. locTextures[selKey].releaseTexture();
  8642. }
  8643. this._textures = {};
  8644. },
  8645. removeTexture: function (texture) {
  8646. if (!texture)
  8647. return;
  8648. var locTextures = this._textures;
  8649. for (var selKey in locTextures) {
  8650. if (locTextures[selKey] === texture) {
  8651. locTextures[selKey].releaseTexture();
  8652. delete(locTextures[selKey]);
  8653. }
  8654. }
  8655. },
  8656. removeTextureForKey: function (textureKeyName) {
  8657. if (textureKeyName == null)
  8658. return;
  8659. if (this._textures[textureKeyName])
  8660. delete(this._textures[textureKeyName]);
  8661. },
  8662. cacheImage: function (path, texture) {
  8663. if (texture instanceof cc.Texture2D) {
  8664. this._textures[path] = texture;
  8665. return;
  8666. }
  8667. var texture2d = new cc.Texture2D();
  8668. texture2d.initWithElement(texture);
  8669. texture2d.handleLoadedTexture();
  8670. this._textures[path] = texture2d;
  8671. },
  8672. addUIImage: function (image, key) {
  8673. cc.assert(image, cc._LogInfos.textureCache_addUIImage_2);
  8674. if (key) {
  8675. if (this._textures[key])
  8676. return this._textures[key];
  8677. }
  8678. var texture = new cc.Texture2D();
  8679. texture.initWithImage(image);
  8680. if (key != null)
  8681. this._textures[key] = texture;
  8682. else
  8683. cc.log(cc._LogInfos.textureCache_addUIImage);
  8684. return texture;
  8685. },
  8686. dumpCachedTextureInfo: function () {
  8687. var count = 0;
  8688. var totalBytes = 0, locTextures = this._textures;
  8689. for (var key in locTextures) {
  8690. var selTexture = locTextures[key];
  8691. count++;
  8692. if (selTexture.getHtmlElementObj() instanceof HTMLImageElement)
  8693. cc.log(cc._LogInfos.textureCache_dumpCachedTextureInfo, key, selTexture.getHtmlElementObj().src, selTexture.pixelsWidth, selTexture.pixelsHeight);
  8694. else {
  8695. cc.log(cc._LogInfos.textureCache_dumpCachedTextureInfo_2, key, selTexture.pixelsWidth, selTexture.pixelsHeight);
  8696. }
  8697. totalBytes += selTexture.pixelsWidth * selTexture.pixelsHeight * 4;
  8698. }
  8699. var locTextureColorsCache = this._textureColorsCache;
  8700. for (key in locTextureColorsCache) {
  8701. var selCanvasColorsArr = locTextureColorsCache[key];
  8702. for (var selCanvasKey in selCanvasColorsArr) {
  8703. var selCanvas = selCanvasColorsArr[selCanvasKey];
  8704. count++;
  8705. cc.log(cc._LogInfos.textureCache_dumpCachedTextureInfo_2, key, selCanvas.width, selCanvas.height);
  8706. totalBytes += selCanvas.width * selCanvas.height * 4;
  8707. }
  8708. }
  8709. cc.log(cc._LogInfos.textureCache_dumpCachedTextureInfo_3, count, totalBytes / 1024, (totalBytes / (1024.0 * 1024.0)).toFixed(2));
  8710. },
  8711. _clear: function () {
  8712. this._textures = {};
  8713. this._textureColorsCache = {};
  8714. this._textureKeySeq = (0 | Math.random() * 1000);
  8715. this._loadedTexturesBefore = {};
  8716. }
  8717. };
  8718. cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
  8719. if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) {
  8720. var _p = cc.textureCache;
  8721. _p.handleLoadedTexture = function (url) {
  8722. var locTexs = this._textures;
  8723. var tex = locTexs[url];
  8724. if (!tex) {
  8725. tex = locTexs[url] = new cc.Texture2D();
  8726. tex.url = url;
  8727. }
  8728. tex.handleLoadedTexture();
  8729. };
  8730. _p.addImage = function (url, cb, target) {
  8731. cc.assert(url, cc._LogInfos.Texture2D_addImage);
  8732. var locTexs = this._textures;
  8733. var tex = locTexs[url] || locTexs[cc.loader._getAliase(url)];
  8734. if (tex) {
  8735. if(tex.isLoaded()) {
  8736. cb && cb.call(target, tex);
  8737. return tex;
  8738. }
  8739. else
  8740. {
  8741. tex.addEventListener("load", function(){
  8742. cb && cb.call(target, tex);
  8743. }, target);
  8744. return tex;
  8745. }
  8746. }
  8747. tex = locTexs[url] = new cc.Texture2D();
  8748. tex.url = url;
  8749. var basePath = cc.loader.getBasePath ? cc.loader.getBasePath() : cc.loader.resPath;
  8750. cc.loader.loadImg(cc.path.join(basePath || "", url), function (err, img) {
  8751. if (err)
  8752. return cb && cb.call(target, err);
  8753. if (!cc.loader.cache[url]) {
  8754. cc.loader.cache[url] = img;
  8755. }
  8756. cc.textureCache.handleLoadedTexture(url);
  8757. var texResult = locTexs[url];
  8758. cb && cb.call(target, texResult);
  8759. });
  8760. return tex;
  8761. };
  8762. _p.addImageAsync = _p.addImage;
  8763. _p = null;
  8764. } else if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) {
  8765. cc.assert(cc.isFunction(cc._tmp.WebGLTextureCache), cc._LogInfos.MissingFile, "TexturesWebGL.js");
  8766. cc._tmp.WebGLTextureCache();
  8767. delete cc._tmp.WebGLTextureCache;
  8768. }
  8769. });
  8770. cc.Scene = cc.Node.extend({
  8771. _className:"Scene",
  8772. ctor:function () {
  8773. cc.Node.prototype.ctor.call(this);
  8774. this._ignoreAnchorPointForPosition = true;
  8775. this.setAnchorPoint(0.5, 0.5);
  8776. this.setContentSize(cc.director.getWinSize());
  8777. }
  8778. });
  8779. cc.Scene.create = function () {
  8780. return new cc.Scene();
  8781. };
  8782. cc.LoaderScene = cc.Scene.extend({
  8783. _interval : null,
  8784. _label : null,
  8785. _className:"LoaderScene",
  8786. cb: null,
  8787. target: null,
  8788. init : function(){
  8789. var self = this;
  8790. var logoWidth = 160;
  8791. var logoHeight = 200;
  8792. var bgLayer = self._bgLayer = new cc.LayerColor(cc.color(32, 32, 32, 255));
  8793. self.addChild(bgLayer, 0);
  8794. var fontSize = 24, lblHeight = -logoHeight / 2 + 100;
  8795. if(cc._loaderImage){
  8796. cc.loader.loadImg(cc._loaderImage, {isCrossOrigin : false }, function(err, img){
  8797. logoWidth = img.width;
  8798. logoHeight = img.height;
  8799. self._initStage(img, cc.visibleRect.center);
  8800. });
  8801. fontSize = 14;
  8802. lblHeight = -logoHeight / 2 - 10;
  8803. }
  8804. var label = self._label = new cc.LabelTTF("Loading... 0%", "Arial", fontSize);
  8805. label.setPosition(cc.pAdd(cc.visibleRect.center, cc.p(0, lblHeight)));
  8806. label.setColor(cc.color(180, 180, 180));
  8807. bgLayer.addChild(this._label, 10);
  8808. return true;
  8809. },
  8810. _initStage: function (img, centerPos) {
  8811. var self = this;
  8812. var texture2d = self._texture2d = new cc.Texture2D();
  8813. texture2d.initWithElement(img);
  8814. texture2d.handleLoadedTexture();
  8815. var logo = self._logo = new cc.Sprite(texture2d);
  8816. logo.setScale(cc.contentScaleFactor());
  8817. logo.x = centerPos.x;
  8818. logo.y = centerPos.y;
  8819. self._bgLayer.addChild(logo, 10);
  8820. },
  8821. onEnter: function () {
  8822. var self = this;
  8823. cc.Node.prototype.onEnter.call(self);
  8824. self.schedule(self._startLoading, 0.3);
  8825. },
  8826. onExit: function () {
  8827. cc.Node.prototype.onExit.call(this);
  8828. var tmpStr = "Loading... 0%";
  8829. this._label.setString(tmpStr);
  8830. },
  8831. initWithResources: function (resources, cb, target) {
  8832. if(cc.isString(resources))
  8833. resources = [resources];
  8834. this.resources = resources || [];
  8835. this.cb = cb;
  8836. this.target = target;
  8837. },
  8838. _startLoading: function () {
  8839. var self = this;
  8840. self.unschedule(self._startLoading);
  8841. var res = self.resources;
  8842. cc.loader.load(res,
  8843. function (result, count, loadedCount) {
  8844. var percent = (loadedCount / count * 100) | 0;
  8845. percent = Math.min(percent, 100);
  8846. self._label.setString("Loading... " + percent + "%");
  8847. }, function () {
  8848. if (self.cb)
  8849. self.cb.call(self.target);
  8850. });
  8851. },
  8852. _updateTransform: function(){
  8853. this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
  8854. this._bgLayer._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
  8855. this._label._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
  8856. this._logo._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
  8857. }
  8858. });
  8859. cc.LoaderScene.preload = function(resources, cb, target){
  8860. var _cc = cc;
  8861. if(!_cc.loaderScene) {
  8862. _cc.loaderScene = new cc.LoaderScene();
  8863. _cc.loaderScene.init();
  8864. cc.eventManager.addCustomListener(cc.Director.EVENT_PROJECTION_CHANGED, function(){
  8865. _cc.loaderScene._updateTransform();
  8866. });
  8867. }
  8868. _cc.loaderScene.initWithResources(resources, cb, target);
  8869. cc.director.runScene(_cc.loaderScene);
  8870. return _cc.loaderScene;
  8871. };
  8872. cc.Layer = cc.Node.extend({
  8873. _className: "Layer",
  8874. ctor: function () {
  8875. cc.Node.prototype.ctor.call(this);
  8876. this._ignoreAnchorPointForPosition = true;
  8877. this.setAnchorPoint(0.5, 0.5);
  8878. this.setContentSize(cc.winSize);
  8879. },
  8880. init: function(){
  8881. var _t = this;
  8882. _t._ignoreAnchorPointForPosition = true;
  8883. _t.setAnchorPoint(0.5, 0.5);
  8884. _t.setContentSize(cc.winSize);
  8885. _t._cascadeColorEnabled = false;
  8886. _t._cascadeOpacityEnabled = false;
  8887. return true;
  8888. },
  8889. bake: function(){
  8890. this._renderCmd.bake();
  8891. },
  8892. unbake: function(){
  8893. this._renderCmd.unbake();
  8894. },
  8895. isBaked: function(){
  8896. return this._renderCmd._isBaked;
  8897. },
  8898. addChild: function(child, localZOrder, tag){
  8899. cc.Node.prototype.addChild.call(this, child, localZOrder, tag);
  8900. this._renderCmd._bakeForAddChild(child);
  8901. },
  8902. _createRenderCmd: function(){
  8903. if (cc._renderType === cc.game.RENDER_TYPE_CANVAS)
  8904. return new cc.Layer.CanvasRenderCmd(this);
  8905. else
  8906. return new cc.Layer.WebGLRenderCmd(this);
  8907. }
  8908. });
  8909. cc.Layer.create = function () {
  8910. return new cc.Layer();
  8911. };
  8912. cc.LayerColor = cc.Layer.extend({
  8913. _blendFunc: null,
  8914. _className: "LayerColor",
  8915. getBlendFunc: function () {
  8916. return this._blendFunc;
  8917. },
  8918. changeWidthAndHeight: function (w, h) {
  8919. this.width = w;
  8920. this.height = h;
  8921. },
  8922. changeWidth: function (w) {
  8923. this.width = w;
  8924. },
  8925. changeHeight: function (h) {
  8926. this.height = h;
  8927. },
  8928. setOpacityModifyRGB: function (value) {
  8929. },
  8930. isOpacityModifyRGB: function () {
  8931. return false;
  8932. },
  8933. ctor: function(color, width, height){
  8934. cc.Layer.prototype.ctor.call(this);
  8935. this._blendFunc = cc.BlendFunc._alphaNonPremultiplied();
  8936. cc.LayerColor.prototype.init.call(this, color, width, height);
  8937. },
  8938. init: function (color, width, height) {
  8939. var winSize = cc.director.getWinSize();
  8940. color = color || cc.color(0, 0, 0, 255);
  8941. width = width === undefined ? winSize.width : width;
  8942. height = height === undefined ? winSize.height : height;
  8943. var locRealColor = this._realColor;
  8944. locRealColor.r = color.r;
  8945. locRealColor.g = color.g;
  8946. locRealColor.b = color.b;
  8947. this._realOpacity = color.a;
  8948. this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.colorDirty|cc.Node._dirtyFlags.opacityDirty);
  8949. cc.LayerColor.prototype.setContentSize.call(this, width, height);
  8950. return true;
  8951. },
  8952. setBlendFunc: function (src, dst) {
  8953. var locBlendFunc = this._blendFunc;
  8954. if (dst === undefined) {
  8955. locBlendFunc.src = src.src;
  8956. locBlendFunc.dst = src.dst;
  8957. } else {
  8958. locBlendFunc.src = src;
  8959. locBlendFunc.dst = dst;
  8960. }
  8961. this._renderCmd.updateBlendFunc(locBlendFunc);
  8962. },
  8963. _createRenderCmd: function(){
  8964. if (cc._renderType === cc.game.RENDER_TYPE_CANVAS)
  8965. return new cc.LayerColor.CanvasRenderCmd(this);
  8966. else
  8967. return new cc.LayerColor.WebGLRenderCmd(this);
  8968. }
  8969. });
  8970. cc.LayerColor.create = function (color, width, height) {
  8971. return new cc.LayerColor(color, width, height);
  8972. };
  8973. (function(){
  8974. var proto = cc.LayerColor.prototype;
  8975. cc.defineGetterSetter(proto, "width", proto._getWidth, proto._setWidth);
  8976. cc.defineGetterSetter(proto, "height", proto._getHeight, proto._setHeight);
  8977. })();
  8978. cc.LayerGradient = cc.LayerColor.extend({
  8979. _endColor: null,
  8980. _startOpacity: 255,
  8981. _endOpacity: 255,
  8982. _alongVector: null,
  8983. _compressedInterpolation: false,
  8984. _className: "LayerGradient",
  8985. _colorStops: [],
  8986. ctor: function (start, end, v, stops) {
  8987. cc.LayerColor.prototype.ctor.call(this);
  8988. this._endColor = cc.color(0, 0, 0, 255);
  8989. this._alongVector = cc.p(0, -1);
  8990. this._startOpacity = 255;
  8991. this._endOpacity = 255;
  8992. if(stops && stops instanceof Array){
  8993. this._colorStops = stops;
  8994. stops.splice(0, 0, {p:0, color: start || cc.color.BLACK});
  8995. stops.push({p:1, color: end || cc.color.BLACK});
  8996. } else
  8997. this._colorStops = [{p:0, color: start || cc.color.BLACK}, {p:1, color: end || cc.color.BLACK}];
  8998. cc.LayerGradient.prototype.init.call(this, start, end, v, stops);
  8999. },
  9000. init: function (start, end, v, stops) {
  9001. start = start || cc.color(0, 0, 0, 255);
  9002. end = end || cc.color(0, 0, 0, 255);
  9003. v = v || cc.p(0, -1);
  9004. var _t = this;
  9005. var locEndColor = _t._endColor;
  9006. _t._startOpacity = start.a;
  9007. locEndColor.r = end.r;
  9008. locEndColor.g = end.g;
  9009. locEndColor.b = end.b;
  9010. _t._endOpacity = end.a;
  9011. _t._alongVector = v;
  9012. _t._compressedInterpolation = true;
  9013. cc.LayerColor.prototype.init.call(_t, cc.color(start.r, start.g, start.b, 255));
  9014. this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.colorDirty|cc.Node._dirtyFlags.opacityDirty|cc.Node._dirtyFlags.gradientDirty);
  9015. return true;
  9016. },
  9017. setContentSize: function (size, height) {
  9018. cc.LayerColor.prototype.setContentSize.call(this, size, height);
  9019. this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.gradientDirty);
  9020. },
  9021. _setWidth: function (width) {
  9022. cc.LayerColor.prototype._setWidth.call(this, width);
  9023. this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.gradientDirty);
  9024. },
  9025. _setHeight: function (height) {
  9026. cc.LayerColor.prototype._setHeight.call(this, height);
  9027. this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.gradientDirty);
  9028. },
  9029. getStartColor: function () {
  9030. return cc.color(this._realColor);
  9031. },
  9032. setStartColor: function (color) {
  9033. this.color = color;
  9034. var stops = this._colorStops;
  9035. if(stops && stops.length > 0){
  9036. var selColor = stops[0].color;
  9037. selColor.r = color.r;
  9038. selColor.g = color.g;
  9039. selColor.b = color.b;
  9040. }
  9041. },
  9042. setEndColor: function (color) {
  9043. var locColor = this._endColor;
  9044. locColor.r = color.r;
  9045. locColor.g = color.g;
  9046. locColor.b = color.b;
  9047. var stops = this._colorStops;
  9048. if(stops && stops.length > 0){
  9049. var selColor = stops[stops.length -1].color;
  9050. selColor.r = color.r;
  9051. selColor.g = color.g;
  9052. selColor.b = color.b;
  9053. }
  9054. this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.colorDirty);
  9055. },
  9056. getEndColor: function () {
  9057. return cc.color(this._endColor);
  9058. },
  9059. setStartOpacity: function (o) {
  9060. this._startOpacity = o;
  9061. var stops = this._colorStops;
  9062. if(stops && stops.length > 0)
  9063. stops[0].color.a = o;
  9064. this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.opacityDirty);
  9065. },
  9066. getStartOpacity: function () {
  9067. return this._startOpacity;
  9068. },
  9069. setEndOpacity: function (o) {
  9070. this._endOpacity = o;
  9071. var stops = this._colorStops;
  9072. if(stops && stops.length > 0)
  9073. stops[stops.length -1].color.a = o;
  9074. this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.opacityDirty);
  9075. },
  9076. getEndOpacity: function () {
  9077. return this._endOpacity;
  9078. },
  9079. setVector: function (Var) {
  9080. this._alongVector.x = Var.x;
  9081. this._alongVector.y = Var.y;
  9082. this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.gradientDirty);
  9083. },
  9084. getVector: function () {
  9085. return cc.p(this._alongVector.x, this._alongVector.y);
  9086. },
  9087. isCompressedInterpolation: function () {
  9088. return this._compressedInterpolation;
  9089. },
  9090. setCompressedInterpolation: function (compress) {
  9091. this._compressedInterpolation = compress;
  9092. this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.gradientDirty);
  9093. },
  9094. getColorStops: function(){
  9095. return this._colorStops;
  9096. },
  9097. setColorStops: function(colorStops){
  9098. this._colorStops = colorStops;
  9099. this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.colorDirty|cc.Node._dirtyFlags.opacityDirty|cc.Node._dirtyFlags.gradientDirty);
  9100. },
  9101. _createRenderCmd: function(){
  9102. if (cc._renderType === cc.game.RENDER_TYPE_CANVAS)
  9103. return new cc.LayerGradient.CanvasRenderCmd(this);
  9104. else
  9105. return new cc.LayerGradient.WebGLRenderCmd(this);
  9106. }
  9107. });
  9108. cc.LayerGradient.create = function (start, end, v, stops) {
  9109. return new cc.LayerGradient(start, end, v, stops);
  9110. };
  9111. (function(){
  9112. var proto = cc.LayerGradient.prototype;
  9113. proto.startColor;
  9114. cc.defineGetterSetter(proto, "startColor", proto.getStartColor, proto.setStartColor);
  9115. proto.endColor;
  9116. cc.defineGetterSetter(proto, "endColor", proto.getEndColor, proto.setEndColor);
  9117. proto.startOpacity;
  9118. cc.defineGetterSetter(proto, "startOpacity", proto.getStartOpacity, proto.setStartOpacity);
  9119. proto.endOpacity;
  9120. cc.defineGetterSetter(proto, "endOpacity", proto.getEndOpacity, proto.setEndOpacity);
  9121. proto.vector;
  9122. cc.defineGetterSetter(proto, "vector", proto.getVector, proto.setVector);
  9123. proto.colorStops;
  9124. cc.defineGetterSetter(proto, "colorStops", proto.getColorStops, proto.setColorStops);
  9125. })();
  9126. cc.LayerMultiplex = cc.Layer.extend({
  9127. _enabledLayer: 0,
  9128. _layers: null,
  9129. _className: "LayerMultiplex",
  9130. ctor: function (layers) {
  9131. cc.Layer.prototype.ctor.call(this);
  9132. if (layers instanceof Array)
  9133. cc.LayerMultiplex.prototype.initWithLayers.call(this, layers);
  9134. else
  9135. cc.LayerMultiplex.prototype.initWithLayers.call(this, Array.prototype.slice.call(arguments));
  9136. },
  9137. initWithLayers: function (layers) {
  9138. if ((layers.length > 0) && (layers[layers.length - 1] == null))
  9139. cc.log(cc._LogInfos.LayerMultiplex_initWithLayers);
  9140. this._layers = layers;
  9141. this._enabledLayer = 0;
  9142. this.addChild(this._layers[this._enabledLayer]);
  9143. return true;
  9144. },
  9145. switchTo: function (n) {
  9146. if (n >= this._layers.length) {
  9147. cc.log(cc._LogInfos.LayerMultiplex_switchTo);
  9148. return;
  9149. }
  9150. this.removeChild(this._layers[this._enabledLayer], true);
  9151. this._enabledLayer = n;
  9152. this.addChild(this._layers[n]);
  9153. },
  9154. switchToAndReleaseMe: function (n) {
  9155. if (n >= this._layers.length) {
  9156. cc.log(cc._LogInfos.LayerMultiplex_switchToAndReleaseMe);
  9157. return;
  9158. }
  9159. this.removeChild(this._layers[this._enabledLayer], true);
  9160. this._layers[this._enabledLayer] = null;
  9161. this._enabledLayer = n;
  9162. this.addChild(this._layers[n]);
  9163. },
  9164. addLayer: function (layer) {
  9165. if (!layer) {
  9166. cc.log(cc._LogInfos.LayerMultiplex_addLayer);
  9167. return;
  9168. }
  9169. this._layers.push(layer);
  9170. }
  9171. });
  9172. cc.LayerMultiplex.create = function () {
  9173. return new cc.LayerMultiplex(Array.prototype.slice.call(arguments));
  9174. };
  9175. (function(){
  9176. cc.Layer.CanvasRenderCmd = function(renderable){
  9177. cc.Node.CanvasRenderCmd.call(this, renderable);
  9178. this._isBaked = false;
  9179. this._bakeSprite = null;
  9180. this._canUseDirtyRegion = true;
  9181. this._updateCache = 2;
  9182. };
  9183. var proto = cc.Layer.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype);
  9184. proto.constructor = cc.Layer.CanvasRenderCmd;
  9185. proto._setCacheDirty = function(child){
  9186. if(child && this._updateCache === 0)
  9187. this._updateCache = 2;
  9188. if (this._cacheDirty === false) {
  9189. this._cacheDirty = true;
  9190. var cachedP = this._cachedParent;
  9191. cachedP && cachedP !== this && cachedP._setNodeDirtyForCache && cachedP._setNodeDirtyForCache();
  9192. }
  9193. };
  9194. proto.updateStatus = function () {
  9195. var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag;
  9196. if (locFlag & flags.orderDirty) {
  9197. this._cacheDirty = true;
  9198. if(this._updateCache === 0)
  9199. this._updateCache = 2;
  9200. this._dirtyFlag = locFlag & flags.orderDirty ^ locFlag;
  9201. }
  9202. cc.Node.RenderCmd.prototype.updateStatus.call(this);
  9203. };
  9204. proto._syncStatus = function (parentCmd) {
  9205. var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag;
  9206. if (locFlag & flags.orderDirty) {
  9207. this._cacheDirty = true;
  9208. if(this._updateCache === 0)
  9209. this._updateCache = 2;
  9210. this._dirtyFlag = locFlag & flags.orderDirty ^ locFlag;
  9211. }
  9212. cc.Node.RenderCmd.prototype._syncStatus.call(this, parentCmd);
  9213. };
  9214. proto.transform = function (parentCmd, recursive) {
  9215. var wt = this._worldTransform;
  9216. var a = wt.a, b = wt.b, c = wt.c, d = wt.d, tx = wt.tx, ty = wt.ty;
  9217. cc.Node.CanvasRenderCmd.prototype.transform.call(this, parentCmd, recursive);
  9218. if(( wt.a !== a || wt.b !== b || wt.c !== c || wt.d !== d ) && this._updateCache === 0)
  9219. this._updateCache = 2;
  9220. };
  9221. proto.bake = function(){
  9222. if (!this._isBaked) {
  9223. this._needDraw = true;
  9224. cc.renderer.childrenOrderDirty = true;
  9225. this._isBaked = this._cacheDirty = true;
  9226. if(this._updateCache === 0)
  9227. this._updateCache = 2;
  9228. var children = this._node._children;
  9229. for(var i = 0, len = children.length; i < len; i++)
  9230. children[i]._renderCmd._setCachedParent(this);
  9231. if (!this._bakeSprite) {
  9232. this._bakeSprite = new cc.BakeSprite();
  9233. this._bakeSprite.setAnchorPoint(0,0);
  9234. }
  9235. }
  9236. };
  9237. proto.unbake = function(){
  9238. if (this._isBaked) {
  9239. cc.renderer.childrenOrderDirty = true;
  9240. this._needDraw = false;
  9241. this._isBaked = false;
  9242. this._cacheDirty = true;
  9243. if(this._updateCache === 0)
  9244. this._updateCache = 2;
  9245. var children = this._node._children;
  9246. for(var i = 0, len = children.length; i < len; i++)
  9247. children[i]._renderCmd._setCachedParent(null);
  9248. }
  9249. };
  9250. proto.isBaked = function(){
  9251. return this._isBaked;
  9252. };
  9253. proto.rendering = function(){
  9254. if(this._cacheDirty){
  9255. var node = this._node;
  9256. var children = node._children, locBakeSprite = this._bakeSprite;
  9257. this.transform(this.getParentRenderCmd(), true);
  9258. var boundingBox = this._getBoundingBoxForBake();
  9259. boundingBox.width = 0|(boundingBox.width+0.5);
  9260. boundingBox.height = 0|(boundingBox.height+0.5);
  9261. var bakeContext = locBakeSprite.getCacheContext();
  9262. var ctx = bakeContext.getContext();
  9263. locBakeSprite.setPosition(boundingBox.x, boundingBox.y);
  9264. if(this._updateCache > 0){
  9265. locBakeSprite.resetCanvasSize(boundingBox.width, boundingBox.height);
  9266. bakeContext.setOffset(0 - boundingBox.x, ctx.canvas.height - boundingBox.height + boundingBox.y );
  9267. node.sortAllChildren();
  9268. cc.renderer._turnToCacheMode(this.__instanceId);
  9269. for (var i = 0, len = children.length; i < len; i++) {
  9270. children[i].visit(this);
  9271. }
  9272. cc.renderer._renderingToCacheCanvas(bakeContext, this.__instanceId);
  9273. locBakeSprite.transform();
  9274. this._updateCache--;
  9275. }
  9276. this._cacheDirty = false;
  9277. }
  9278. };
  9279. proto.visit = function(parentCmd){
  9280. if(!this._isBaked){
  9281. this.originVisit(parentCmd);
  9282. return;
  9283. }
  9284. var node = this._node, children = node._children;
  9285. var len = children.length;
  9286. if (!node._visible || len === 0)
  9287. return;
  9288. this._syncStatus(parentCmd);
  9289. cc.renderer.pushRenderCommand(this);
  9290. this._bakeSprite.visit(this);
  9291. this._dirtyFlag = 0;
  9292. };
  9293. proto._bakeForAddChild = function(child){
  9294. if(child._parent === this._node && this._isBaked)
  9295. child._renderCmd._setCachedParent(this);
  9296. };
  9297. proto._getBoundingBoxForBake = function(){
  9298. var rect = null, node = this._node;
  9299. if (!node._children || node._children.length === 0)
  9300. return cc.rect(0, 0, 10, 10);
  9301. var trans = node.getNodeToWorldTransform();
  9302. var locChildren = node._children;
  9303. for (var i = 0, len = locChildren.length; i < len; i++) {
  9304. var child = locChildren[i];
  9305. if (child && child._visible) {
  9306. if(rect){
  9307. var childRect = child._getBoundingBoxToCurrentNode(trans);
  9308. if (childRect)
  9309. rect = cc.rectUnion(rect, childRect);
  9310. }else{
  9311. rect = child._getBoundingBoxToCurrentNode(trans);
  9312. }
  9313. }
  9314. }
  9315. return rect;
  9316. };
  9317. })();
  9318. (function(){
  9319. cc.LayerColor.CanvasRenderCmd = function(renderable){
  9320. cc.Layer.CanvasRenderCmd.call(this, renderable);
  9321. this._needDraw = true;
  9322. this._blendFuncStr = "source-over";
  9323. this._bakeRenderCmd = new cc.CustomRenderCmd(this, this._bakeRendering);
  9324. };
  9325. var proto = cc.LayerColor.CanvasRenderCmd.prototype = Object.create(cc.Layer.CanvasRenderCmd.prototype);
  9326. proto.constructor = cc.LayerColor.CanvasRenderCmd;
  9327. proto.unbake = function(){
  9328. cc.Layer.CanvasRenderCmd.prototype.unbake.call(this);
  9329. this._needDraw = true;
  9330. };
  9331. proto.rendering = function (ctx, scaleX, scaleY) {
  9332. var wrapper = ctx || cc._renderContext, context = wrapper.getContext(),
  9333. node = this._node,
  9334. curColor = this._displayedColor,
  9335. opacity = this._displayedOpacity / 255,
  9336. locWidth = node._contentSize.width,
  9337. locHeight = node._contentSize.height;
  9338. if (opacity === 0)
  9339. return;
  9340. wrapper.setCompositeOperation(this._blendFuncStr);
  9341. wrapper.setGlobalAlpha(opacity);
  9342. wrapper.setFillStyle("rgba(" + (0 | curColor.r) + "," + (0 | curColor.g) + ","
  9343. + (0 | curColor.b) + ", 1)");
  9344. wrapper.setTransform(this._worldTransform, scaleX, scaleY);
  9345. context.fillRect(0, 0, locWidth , -locHeight );
  9346. cc.g_NumberOfDraws++;
  9347. };
  9348. proto.updateBlendFunc = function(blendFunc){
  9349. this._blendFuncStr = cc.Node.CanvasRenderCmd._getCompositeOperationByBlendFunc(blendFunc);
  9350. };
  9351. proto._updateSquareVertices =
  9352. proto._updateSquareVerticesWidth =
  9353. proto._updateSquareVerticesHeight = function(){};
  9354. proto._bakeRendering = function(){
  9355. if(this._cacheDirty){
  9356. var node = this._node;
  9357. var locBakeSprite = this._bakeSprite, children = node._children;
  9358. var len = children.length, i;
  9359. this.transform(this.getParentRenderCmd(), true);
  9360. var boundingBox = this._getBoundingBoxForBake();
  9361. boundingBox.width = 0|(boundingBox.width+0.5);
  9362. boundingBox.height = 0|(boundingBox.height+0.5);
  9363. var bakeContext = locBakeSprite.getCacheContext();
  9364. var ctx = bakeContext.getContext();
  9365. locBakeSprite.setPosition(boundingBox.x, boundingBox.y);
  9366. if(this._updateCache > 0) {
  9367. ctx.fillStyle = bakeContext._currentFillStyle;
  9368. locBakeSprite.resetCanvasSize(boundingBox.width, boundingBox.height);
  9369. bakeContext.setOffset(0 - boundingBox.x, ctx.canvas.height - boundingBox.height + boundingBox.y );
  9370. var child;
  9371. cc.renderer._turnToCacheMode(this.__instanceId);
  9372. if (len > 0) {
  9373. node.sortAllChildren();
  9374. for (i = 0; i < len; i++) {
  9375. child = children[i];
  9376. if (child._localZOrder < 0)
  9377. child._renderCmd.visit(this);
  9378. else
  9379. break;
  9380. }
  9381. cc.renderer.pushRenderCommand(this);
  9382. for (; i < len; i++) {
  9383. children[i]._renderCmd.visit(this);
  9384. }
  9385. } else
  9386. cc.renderer.pushRenderCommand(this);
  9387. cc.renderer._renderingToCacheCanvas(bakeContext, this.__instanceId);
  9388. locBakeSprite.transform();
  9389. this._updateCache--;
  9390. }
  9391. this._cacheDirty = false;
  9392. }
  9393. };
  9394. proto.visit = function(parentCmd){
  9395. if(!this._isBaked){
  9396. this.originVisit();
  9397. return;
  9398. }
  9399. var node = this._node;
  9400. if (!node._visible)
  9401. return;
  9402. this._syncStatus(parentCmd);
  9403. cc.renderer.pushRenderCommand(this._bakeRenderCmd);
  9404. this._bakeSprite._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
  9405. this._bakeSprite.visit(this);
  9406. this._dirtyFlag = 0;
  9407. };
  9408. proto._getBoundingBoxForBake = function(){
  9409. var node = this._node;
  9410. var rect = cc.rect(0, 0, node._contentSize.width, node._contentSize.height);
  9411. var trans = node.getNodeToWorldTransform();
  9412. rect = cc.rectApplyAffineTransform(rect, node.getNodeToWorldTransform());
  9413. if (!node._children || node._children.length === 0)
  9414. return rect;
  9415. var locChildren = node._children;
  9416. for (var i = 0; i < locChildren.length; i++) {
  9417. var child = locChildren[i];
  9418. if (child && child._visible) {
  9419. var childRect = child._getBoundingBoxToCurrentNode(trans);
  9420. rect = cc.rectUnion(rect, childRect);
  9421. }
  9422. }
  9423. return rect;
  9424. };
  9425. })();
  9426. (function(){
  9427. cc.LayerGradient.CanvasRenderCmd = function(renderable){
  9428. cc.LayerColor.CanvasRenderCmd.call(this, renderable);
  9429. this._needDraw = true;
  9430. this._startPoint = cc.p(0, 0);
  9431. this._endPoint = cc.p(0, 0);
  9432. this._startStopStr = null;
  9433. this._endStopStr = null;
  9434. };
  9435. var proto = cc.LayerGradient.CanvasRenderCmd.prototype = Object.create(cc.LayerColor.CanvasRenderCmd.prototype);
  9436. proto.constructor = cc.LayerGradient.CanvasRenderCmd;
  9437. proto.rendering = function (ctx, scaleX, scaleY) {
  9438. var wrapper = ctx || cc._renderContext, context = wrapper.getContext(),
  9439. node = this._node,
  9440. opacity = this._displayedOpacity / 255;
  9441. if (opacity === 0)
  9442. return;
  9443. var locWidth = node._contentSize.width, locHeight = node._contentSize.height;
  9444. wrapper.setCompositeOperation(this._blendFuncStr);
  9445. wrapper.setGlobalAlpha(opacity);
  9446. var gradient = context.createLinearGradient(this._startPoint.x, this._startPoint.y, this._endPoint.x, this._endPoint.y);
  9447. if(node._colorStops){
  9448. for(var i=0; i < node._colorStops.length; i++) {
  9449. var stop = node._colorStops[i];
  9450. gradient.addColorStop(stop.p, this._colorStopsStr[i]);
  9451. }
  9452. }else{
  9453. gradient.addColorStop(0, this._startStopStr);
  9454. gradient.addColorStop(1, this._endStopStr);
  9455. }
  9456. wrapper.setFillStyle(gradient);
  9457. wrapper.setTransform(this._worldTransform, scaleX, scaleY);
  9458. context.fillRect(0, 0, locWidth , -locHeight );
  9459. cc.g_NumberOfDraws++;
  9460. };
  9461. proto.updateStatus = function () {
  9462. var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag;
  9463. if (locFlag & flags.gradientDirty) {
  9464. this._dirtyFlag |= flags.colorDirty;
  9465. this._dirtyFlag = locFlag & flags.gradientDirty ^ locFlag;
  9466. }
  9467. cc.Node.RenderCmd.prototype.updateStatus.call(this);
  9468. };
  9469. proto._syncStatus = function (parentCmd) {
  9470. var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag;
  9471. if (locFlag & flags.gradientDirty) {
  9472. this._dirtyFlag |= flags.colorDirty;
  9473. this._dirtyFlag = locFlag & flags.gradientDirty ^ locFlag;
  9474. }
  9475. cc.Node.RenderCmd.prototype._syncStatus.call(this, parentCmd);
  9476. };
  9477. proto._updateColor = function() {
  9478. var node = this._node;
  9479. var contentSize = node._contentSize;
  9480. var tWidth = contentSize.width * 0.5, tHeight = contentSize.height * 0.5;
  9481. var angle = cc.pAngleSigned(cc.p(0, -1), node._alongVector);
  9482. var p1 = cc.pRotateByAngle(cc.p(0, -1), cc.p(0,0), angle);
  9483. var factor = Math.min(Math.abs(1 / p1.x), Math.abs(1/ p1.y));
  9484. this._startPoint.x = tWidth * (-p1.x * factor) + tWidth;
  9485. this._startPoint.y = tHeight * (p1.y * factor) - tHeight;
  9486. this._endPoint.x = tWidth * (p1.x * factor) + tWidth;
  9487. this._endPoint.y = tHeight * (-p1.y * factor) - tHeight;
  9488. var locStartColor = this._displayedColor, locEndColor = node._endColor;
  9489. var startOpacity = node._startOpacity/255, endOpacity = node._endOpacity/255;
  9490. this._startStopStr = "rgba(" + Math.round(locStartColor.r) + "," + Math.round(locStartColor.g) + ","
  9491. + Math.round(locStartColor.b) + "," + startOpacity.toFixed(4) + ")";
  9492. this._endStopStr = "rgba(" + Math.round(locEndColor.r) + "," + Math.round(locEndColor.g) + ","
  9493. + Math.round(locEndColor.b) + "," + endOpacity.toFixed(4) + ")";
  9494. if( node._colorStops){
  9495. this._startOpacity = 0;
  9496. this._endOpacity = 0;
  9497. this._colorStopsStr = [];
  9498. for(var i =0; i < node._colorStops.length; i++){
  9499. var stopColor = node._colorStops[i].color;
  9500. var stopOpacity = stopColor.a == null ? 1 : stopColor.a / 255;
  9501. this._colorStopsStr.push("rgba(" + Math.round(stopColor.r) + "," + Math.round(stopColor.g) + ","
  9502. + Math.round(stopColor.b) + "," + stopOpacity.toFixed(4) + ")");
  9503. }
  9504. }
  9505. };
  9506. })();
  9507. cc._tmp.PrototypeSprite = function () {
  9508. var _p = cc.Sprite.prototype;
  9509. cc.defineGetterSetter(_p, "opacityModifyRGB", _p.isOpacityModifyRGB, _p.setOpacityModifyRGB);
  9510. cc.defineGetterSetter(_p, "opacity", _p.getOpacity, _p.setOpacity);
  9511. cc.defineGetterSetter(_p, "color", _p.getColor, _p.setColor);
  9512. _p.dirty;
  9513. _p.flippedX;
  9514. cc.defineGetterSetter(_p, "flippedX", _p.isFlippedX, _p.setFlippedX);
  9515. _p.flippedY;
  9516. cc.defineGetterSetter(_p, "flippedY", _p.isFlippedY, _p.setFlippedY);
  9517. _p.offsetX;
  9518. cc.defineGetterSetter(_p, "offsetX", _p._getOffsetX);
  9519. _p.offsetY;
  9520. cc.defineGetterSetter(_p, "offsetY", _p._getOffsetY);
  9521. _p.atlasIndex;
  9522. _p.texture;
  9523. cc.defineGetterSetter(_p, "texture", _p.getTexture, _p.setTexture);
  9524. _p.textureRectRotated;
  9525. cc.defineGetterSetter(_p, "textureRectRotated", _p.isTextureRectRotated);
  9526. _p.textureAtlas;
  9527. _p.batchNode;
  9528. cc.defineGetterSetter(_p, "batchNode", _p.getBatchNode, _p.setBatchNode);
  9529. _p.quad;
  9530. cc.defineGetterSetter(_p, "quad", _p.getQuad);
  9531. };
  9532. cc.Sprite = cc.Node.extend({
  9533. dirty:false,
  9534. atlasIndex:0,
  9535. textureAtlas:null,
  9536. _batchNode:null,
  9537. _recursiveDirty:null,
  9538. _hasChildren:null,
  9539. _shouldBeHidden:false,
  9540. _transformToBatch:null,
  9541. _blendFunc:null,
  9542. _texture:null,
  9543. _rect:null,
  9544. _rectRotated:false,
  9545. _offsetPosition:null,
  9546. _unflippedOffsetPositionFromCenter:null,
  9547. _opacityModifyRGB:false,
  9548. _flippedX:false,
  9549. _flippedY:false,
  9550. _textureLoaded:false,
  9551. _className:"Sprite",
  9552. ctor: function (fileName, rect, rotated) {
  9553. var self = this;
  9554. cc.Node.prototype.ctor.call(self);
  9555. this.setAnchorPoint(0.5, 0.5);
  9556. self._loader = new cc.Sprite.LoadManager();
  9557. self._shouldBeHidden = false;
  9558. self._offsetPosition = cc.p(0, 0);
  9559. self._unflippedOffsetPositionFromCenter = cc.p(0, 0);
  9560. self._blendFunc = {src: cc.BLEND_SRC, dst: cc.BLEND_DST};
  9561. self._rect = cc.rect(0, 0, 0, 0);
  9562. self._softInit(fileName, rect, rotated);
  9563. },
  9564. textureLoaded:function(){
  9565. return this._textureLoaded;
  9566. },
  9567. addLoadedEventListener:function(callback, target){
  9568. this.addEventListener("load", callback, target);
  9569. },
  9570. isDirty:function () {
  9571. return this.dirty;
  9572. },
  9573. setDirty:function (bDirty) {
  9574. this.dirty = bDirty;
  9575. },
  9576. isTextureRectRotated:function () {
  9577. return this._rectRotated;
  9578. },
  9579. getAtlasIndex:function () {
  9580. return this.atlasIndex;
  9581. },
  9582. setAtlasIndex:function (atlasIndex) {
  9583. this.atlasIndex = atlasIndex;
  9584. },
  9585. getTextureRect:function () {
  9586. return cc.rect(this._rect);
  9587. },
  9588. getTextureAtlas:function () {
  9589. return this.textureAtlas;
  9590. },
  9591. setTextureAtlas:function (textureAtlas) {
  9592. this.textureAtlas = textureAtlas;
  9593. },
  9594. getOffsetPosition:function () {
  9595. return cc.p(this._offsetPosition);
  9596. },
  9597. _getOffsetX: function () {
  9598. return this._offsetPosition.x;
  9599. },
  9600. _getOffsetY: function () {
  9601. return this._offsetPosition.y;
  9602. },
  9603. getBlendFunc:function () {
  9604. return this._blendFunc;
  9605. },
  9606. initWithSpriteFrame:function (spriteFrame) {
  9607. cc.assert(spriteFrame, cc._LogInfos.Sprite_initWithSpriteFrame);
  9608. return this.setSpriteFrame(spriteFrame);
  9609. },
  9610. initWithSpriteFrameName:function (spriteFrameName) {
  9611. cc.assert(spriteFrameName, cc._LogInfos.Sprite_initWithSpriteFrameName);
  9612. var frame = cc.spriteFrameCache.getSpriteFrame(spriteFrameName);
  9613. cc.assert(frame, spriteFrameName + cc._LogInfos.Sprite_initWithSpriteFrameName1);
  9614. return this.initWithSpriteFrame(frame);
  9615. },
  9616. useBatchNode:function (batchNode) {
  9617. this.textureAtlas = batchNode.getTextureAtlas();
  9618. this._batchNode = batchNode;
  9619. },
  9620. setVertexRect:function (rect) {
  9621. var locRect = this._rect;
  9622. locRect.x = rect.x;
  9623. locRect.y = rect.y;
  9624. locRect.width = rect.width;
  9625. locRect.height = rect.height;
  9626. this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
  9627. },
  9628. sortAllChildren:function () {
  9629. if (this._reorderChildDirty) {
  9630. var _children = this._children;
  9631. cc.Node.prototype.sortAllChildren.call(this);
  9632. if (this._batchNode) {
  9633. this._arrayMakeObjectsPerformSelector(_children, cc.Node._stateCallbackType.sortAllChildren);
  9634. }
  9635. this._reorderChildDirty = false;
  9636. }
  9637. },
  9638. reorderChild:function (child, zOrder) {
  9639. cc.assert(child, cc._LogInfos.Sprite_reorderChild_2);
  9640. if(this._children.indexOf(child) === -1){
  9641. cc.log(cc._LogInfos.Sprite_reorderChild);
  9642. return;
  9643. }
  9644. if (zOrder === child.zIndex)
  9645. return;
  9646. if (this._batchNode && !this._reorderChildDirty) {
  9647. this._setReorderChildDirtyRecursively();
  9648. this._batchNode.reorderBatch(true);
  9649. }
  9650. cc.Node.prototype.reorderChild.call(this, child, zOrder);
  9651. },
  9652. removeChild:function (child, cleanup) {
  9653. if (this._batchNode)
  9654. this._batchNode.removeSpriteFromAtlas(child);
  9655. cc.Node.prototype.removeChild.call(this, child, cleanup);
  9656. },
  9657. setVisible:function (visible) {
  9658. cc.Node.prototype.setVisible.call(this, visible);
  9659. this._renderCmd.setDirtyRecursively(true);
  9660. },
  9661. removeAllChildren:function (cleanup) {
  9662. var locChildren = this._children, locBatchNode = this._batchNode;
  9663. if (locBatchNode && locChildren != null) {
  9664. for (var i = 0, len = locChildren.length; i < len; i++)
  9665. locBatchNode.removeSpriteFromAtlas(locChildren[i]);
  9666. }
  9667. cc.Node.prototype.removeAllChildren.call(this, cleanup);
  9668. this._hasChildren = false;
  9669. },
  9670. ignoreAnchorPointForPosition:function (relative) {
  9671. if(this._batchNode){
  9672. cc.log(cc._LogInfos.Sprite_ignoreAnchorPointForPosition);
  9673. return;
  9674. }
  9675. cc.Node.prototype.ignoreAnchorPointForPosition.call(this, relative);
  9676. },
  9677. setFlippedX:function (flippedX) {
  9678. if (this._flippedX !== flippedX) {
  9679. this._flippedX = flippedX;
  9680. this.setTextureRect(this._rect, this._rectRotated, this._contentSize);
  9681. this.setNodeDirty(true);
  9682. }
  9683. },
  9684. setFlippedY:function (flippedY) {
  9685. if (this._flippedY !== flippedY) {
  9686. this._flippedY = flippedY;
  9687. this.setTextureRect(this._rect, this._rectRotated, this._contentSize);
  9688. this.setNodeDirty(true);
  9689. }
  9690. },
  9691. isFlippedX:function () {
  9692. return this._flippedX;
  9693. },
  9694. isFlippedY:function () {
  9695. return this._flippedY;
  9696. },
  9697. setOpacityModifyRGB: function (modify) {
  9698. if (this._opacityModifyRGB !== modify) {
  9699. this._opacityModifyRGB = modify;
  9700. this._renderCmd._setColorDirty();
  9701. }
  9702. },
  9703. isOpacityModifyRGB:function () {
  9704. return this._opacityModifyRGB;
  9705. },
  9706. setDisplayFrameWithAnimationName:function (animationName, frameIndex) {
  9707. cc.assert(animationName, cc._LogInfos.Sprite_setDisplayFrameWithAnimationName_3);
  9708. var cache = cc.animationCache.getAnimation(animationName);
  9709. if(!cache){
  9710. cc.log(cc._LogInfos.Sprite_setDisplayFrameWithAnimationName);
  9711. return;
  9712. }
  9713. var animFrame = cache.getFrames()[frameIndex];
  9714. if(!animFrame){
  9715. cc.log(cc._LogInfos.Sprite_setDisplayFrameWithAnimationName_2);
  9716. return;
  9717. }
  9718. this.setSpriteFrame(animFrame.getSpriteFrame());
  9719. },
  9720. getBatchNode:function () {
  9721. return this._batchNode;
  9722. },
  9723. _setReorderChildDirtyRecursively:function () {
  9724. if (!this._reorderChildDirty) {
  9725. this._reorderChildDirty = true;
  9726. var pNode = this._parent;
  9727. while (pNode && pNode !== this._batchNode) {
  9728. pNode._setReorderChildDirtyRecursively();
  9729. pNode = pNode.parent;
  9730. }
  9731. }
  9732. },
  9733. getTexture:function () {
  9734. return this._texture;
  9735. },
  9736. _softInit: function (fileName, rect, rotated) {
  9737. if (fileName === undefined)
  9738. cc.Sprite.prototype.init.call(this);
  9739. else if (cc.isString(fileName)) {
  9740. if (fileName[0] === "#") {
  9741. var frameName = fileName.substr(1, fileName.length - 1);
  9742. var spriteFrame = cc.spriteFrameCache.getSpriteFrame(frameName);
  9743. if (spriteFrame)
  9744. this.initWithSpriteFrame(spriteFrame);
  9745. else
  9746. cc.log("%s does not exist", fileName);
  9747. } else {
  9748. cc.Sprite.prototype.init.call(this, fileName, rect);
  9749. }
  9750. } else if (typeof fileName === "object") {
  9751. if (fileName instanceof cc.Texture2D) {
  9752. this.initWithTexture(fileName, rect, rotated);
  9753. } else if (fileName instanceof cc.SpriteFrame) {
  9754. this.initWithSpriteFrame(fileName);
  9755. } else if ((fileName instanceof HTMLImageElement) || (fileName instanceof HTMLCanvasElement)) {
  9756. var texture2d = new cc.Texture2D();
  9757. texture2d.initWithElement(fileName);
  9758. texture2d.handleLoadedTexture();
  9759. this.initWithTexture(texture2d);
  9760. }
  9761. }
  9762. },
  9763. getQuad:function () {
  9764. return null;
  9765. },
  9766. setBlendFunc: function (src, dst) {
  9767. var locBlendFunc = this._blendFunc;
  9768. if (dst === undefined) {
  9769. locBlendFunc.src = src.src;
  9770. locBlendFunc.dst = src.dst;
  9771. } else {
  9772. locBlendFunc.src = src;
  9773. locBlendFunc.dst = dst;
  9774. }
  9775. this._renderCmd.updateBlendFunc(locBlendFunc);
  9776. },
  9777. init: function () {
  9778. var _t = this;
  9779. if (arguments.length > 0)
  9780. return _t.initWithFile(arguments[0], arguments[1]);
  9781. cc.Node.prototype.init.call(_t);
  9782. _t.dirty = _t._recursiveDirty = false;
  9783. _t._blendFunc.src = cc.BLEND_SRC;
  9784. _t._blendFunc.dst = cc.BLEND_DST;
  9785. _t.texture = null;
  9786. _t._flippedX = _t._flippedY = false;
  9787. _t.anchorX = 0.5;
  9788. _t.anchorY = 0.5;
  9789. _t._offsetPosition.x = 0;
  9790. _t._offsetPosition.y = 0;
  9791. _t._hasChildren = false;
  9792. _t.setTextureRect(cc.rect(0, 0, 0, 0), false, cc.size(0, 0));
  9793. return true;
  9794. },
  9795. initWithFile:function (filename, rect) {
  9796. cc.assert(filename, cc._LogInfos.Sprite_initWithFile);
  9797. var tex = cc.textureCache.getTextureForKey(filename);
  9798. if (!tex) {
  9799. tex = cc.textureCache.addImage(filename);
  9800. }
  9801. if (!tex.isLoaded()) {
  9802. this._loader.clear();
  9803. this._loader.once(tex, function () {
  9804. this.initWithFile(filename, rect);
  9805. this.dispatchEvent("load");
  9806. }, this);
  9807. return false;
  9808. }
  9809. if (!rect) {
  9810. var size = tex.getContentSize();
  9811. rect = cc.rect(0, 0, size.width, size.height);
  9812. }
  9813. return this.initWithTexture(tex, rect);
  9814. },
  9815. initWithTexture: function (texture, rect, rotated, counterclockwise) {
  9816. var _t = this;
  9817. cc.assert(arguments.length !== 0, cc._LogInfos.CCSpriteBatchNode_initWithTexture);
  9818. this._loader.clear();
  9819. _t._textureLoaded = texture.isLoaded();
  9820. if (!_t._textureLoaded) {
  9821. this._loader.once(texture, function () {
  9822. this.initWithTexture(texture, rect, rotated, counterclockwise);
  9823. this.dispatchEvent("load");
  9824. }, this);
  9825. return false;
  9826. }
  9827. rotated = rotated || false;
  9828. texture = this._renderCmd._handleTextureForRotatedTexture(texture, rect, rotated, counterclockwise);
  9829. if (!cc.Node.prototype.init.call(_t))
  9830. return false;
  9831. _t._batchNode = null;
  9832. _t._recursiveDirty = false;
  9833. _t.dirty = false;
  9834. _t._opacityModifyRGB = true;
  9835. _t._blendFunc.src = cc.BLEND_SRC;
  9836. _t._blendFunc.dst = cc.BLEND_DST;
  9837. _t._flippedX = _t._flippedY = false;
  9838. _t._offsetPosition.x = 0;
  9839. _t._offsetPosition.y = 0;
  9840. _t._hasChildren = false;
  9841. _t._rectRotated = rotated;
  9842. if (rect) {
  9843. _t._rect.x = rect.x;
  9844. _t._rect.y = rect.y;
  9845. _t._rect.width = rect.width;
  9846. _t._rect.height = rect.height;
  9847. }
  9848. if (!rect)
  9849. rect = cc.rect(0, 0, texture.width, texture.height);
  9850. this._renderCmd._checkTextureBoundary(texture, rect, rotated);
  9851. _t.setTexture(texture);
  9852. _t.setTextureRect(rect, rotated);
  9853. _t.setBatchNode(null);
  9854. return true;
  9855. },
  9856. setTextureRect: function (rect, rotated, untrimmedSize, needConvert) {
  9857. var _t = this;
  9858. _t._rectRotated = rotated || false;
  9859. _t.setContentSize(untrimmedSize || rect);
  9860. _t.setVertexRect(rect);
  9861. _t._renderCmd._setTextureCoords(rect, needConvert);
  9862. var relativeOffsetX = _t._unflippedOffsetPositionFromCenter.x, relativeOffsetY = _t._unflippedOffsetPositionFromCenter.y;
  9863. if (_t._flippedX)
  9864. relativeOffsetX = -relativeOffsetX;
  9865. if (_t._flippedY)
  9866. relativeOffsetY = -relativeOffsetY;
  9867. var locRect = _t._rect;
  9868. _t._offsetPosition.x = relativeOffsetX + (_t._contentSize.width - locRect.width) / 2;
  9869. _t._offsetPosition.y = relativeOffsetY + (_t._contentSize.height - locRect.height) / 2;
  9870. },
  9871. addChild: function (child, localZOrder, tag) {
  9872. cc.assert(child, cc._LogInfos.CCSpriteBatchNode_addChild_2);
  9873. if (localZOrder == null)
  9874. localZOrder = child._localZOrder;
  9875. if (tag == null)
  9876. tag = child.tag;
  9877. if(this._renderCmd._setBatchNodeForAddChild(child)){
  9878. cc.Node.prototype.addChild.call(this, child, localZOrder, tag);
  9879. this._hasChildren = true;
  9880. }
  9881. },
  9882. setSpriteFrame: function (newFrame) {
  9883. var _t = this;
  9884. if(cc.isString(newFrame)){
  9885. newFrame = cc.spriteFrameCache.getSpriteFrame(newFrame);
  9886. cc.assert(newFrame, cc._LogInfos.Sprite_setSpriteFrame)
  9887. }
  9888. this._loader.clear();
  9889. this.setNodeDirty(true);
  9890. var pNewTexture = newFrame.getTexture();
  9891. _t._textureLoaded = newFrame.textureLoaded();
  9892. this._loader.clear();
  9893. if (!_t._textureLoaded) {
  9894. this._loader.once(pNewTexture, function () {
  9895. this.setSpriteFrame(newFrame);
  9896. this.dispatchEvent("load");
  9897. }, this);
  9898. return false;
  9899. }
  9900. var frameOffset = newFrame.getOffset();
  9901. _t._unflippedOffsetPositionFromCenter.x = frameOffset.x;
  9902. _t._unflippedOffsetPositionFromCenter.y = frameOffset.y;
  9903. if (pNewTexture !== _t._texture) {
  9904. this._renderCmd._setTexture(pNewTexture);
  9905. _t.setColor(_t._realColor);
  9906. }
  9907. _t.setTextureRect(newFrame.getRect(), newFrame.isRotated(), newFrame.getOriginalSize());
  9908. },
  9909. setDisplayFrame: function(newFrame){
  9910. cc.log(cc._LogInfos.Sprite_setDisplayFrame);
  9911. this.setSpriteFrame(newFrame);
  9912. },
  9913. isFrameDisplayed: function(frame){
  9914. return this._renderCmd.isFrameDisplayed(frame);
  9915. },
  9916. displayFrame: function () {
  9917. return this.getSpriteFrame();
  9918. },
  9919. getSpriteFrame: function () {
  9920. return new cc.SpriteFrame(this._texture,
  9921. cc.rectPointsToPixels(this._rect),
  9922. this._rectRotated,
  9923. cc.pointPointsToPixels(this._unflippedOffsetPositionFromCenter),
  9924. cc.sizePointsToPixels(this._contentSize));
  9925. },
  9926. setBatchNode:function (spriteBatchNode) {
  9927. var _t = this;
  9928. _t._batchNode = spriteBatchNode;
  9929. if (!_t._batchNode) {
  9930. _t.atlasIndex = cc.Sprite.INDEX_NOT_INITIALIZED;
  9931. _t.textureAtlas = null;
  9932. _t._recursiveDirty = false;
  9933. _t.dirty = false;
  9934. } else {
  9935. _t._transformToBatch = cc.affineTransformIdentity();
  9936. _t.textureAtlas = _t._batchNode.getTextureAtlas();
  9937. }
  9938. },
  9939. setTexture: function (texture) {
  9940. if(!texture)
  9941. return this._renderCmd._setTexture(null);
  9942. var isFileName = cc.isString(texture);
  9943. if(isFileName)
  9944. texture = cc.textureCache.addImage(texture);
  9945. this._loader.clear();
  9946. if (!texture._textureLoaded) {
  9947. this._loader.once(texture, function () {
  9948. this.setTexture(texture);
  9949. this.dispatchEvent("load");
  9950. }, this);
  9951. return false;
  9952. }
  9953. this._renderCmd._setTexture(texture);
  9954. if (isFileName)
  9955. this._changeRectWithTexture(texture);
  9956. this.setColor(this._realColor);
  9957. this._textureLoaded = true;
  9958. },
  9959. _changeRectWithTexture: function(texture){
  9960. var contentSize = texture._contentSize;
  9961. var rect = cc.rect(
  9962. 0, 0,
  9963. contentSize.width, contentSize.height
  9964. );
  9965. this.setTextureRect(rect);
  9966. },
  9967. _createRenderCmd: function(){
  9968. if(cc._renderType === cc.game.RENDER_TYPE_CANVAS)
  9969. return new cc.Sprite.CanvasRenderCmd(this);
  9970. else
  9971. return new cc.Sprite.WebGLRenderCmd(this);
  9972. }
  9973. });
  9974. cc.Sprite.create = function (fileName, rect, rotated) {
  9975. return new cc.Sprite(fileName, rect, rotated);
  9976. };
  9977. cc.Sprite.createWithTexture = cc.Sprite.create;
  9978. cc.Sprite.createWithSpriteFrameName = cc.Sprite.create;
  9979. cc.Sprite.createWithSpriteFrame = cc.Sprite.create;
  9980. cc.Sprite.INDEX_NOT_INITIALIZED = -1;
  9981. cc.EventHelper.prototype.apply(cc.Sprite.prototype);
  9982. cc.assert(cc.isFunction(cc._tmp.PrototypeSprite), cc._LogInfos.MissingFile, "SpritesPropertyDefine.js");
  9983. cc._tmp.PrototypeSprite();
  9984. delete cc._tmp.PrototypeSprite;
  9985. (function () {
  9986. var manager = cc.Sprite.LoadManager = function () {
  9987. this.list = [];
  9988. };
  9989. manager.prototype.add = function (source, callback, target) {
  9990. if (!source || !source.addEventListener) return;
  9991. source.addEventListener('load', callback, target);
  9992. this.list.push({
  9993. source: source,
  9994. listener: callback,
  9995. target: target
  9996. });
  9997. };
  9998. manager.prototype.once = function (source, callback, target) {
  9999. if (!source || !source.addEventListener) return;
  10000. var tmpCallback = function (event) {
  10001. source.removeEventListener('load', tmpCallback, target);
  10002. callback.call(target, event);
  10003. };
  10004. source.addEventListener('load', tmpCallback, target);
  10005. this.list.push({
  10006. source: source,
  10007. listener: tmpCallback,
  10008. target: target
  10009. });
  10010. };
  10011. manager.prototype.clear = function () {
  10012. while (this.list.length > 0) {
  10013. var item = this.list.pop();
  10014. item.source.removeEventListener('load', item.listener, item.target);
  10015. }
  10016. };
  10017. })();
  10018. (function() {
  10019. cc.Sprite.CanvasRenderCmd = function (renderable) {
  10020. cc.Node.CanvasRenderCmd.call(this, renderable);
  10021. this._needDraw = true;
  10022. this._textureCoord = {
  10023. renderX: 0,
  10024. renderY: 0,
  10025. x: 0,
  10026. y: 0,
  10027. width: 0,
  10028. height: 0,
  10029. validRect: false
  10030. };
  10031. this._blendFuncStr = "source-over";
  10032. this._colorized = false;
  10033. this._canUseDirtyRegion = true;
  10034. this._textureToRender = null;
  10035. };
  10036. var proto = cc.Sprite.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype);
  10037. proto.constructor = cc.Sprite.CanvasRenderCmd;
  10038. proto.setDirtyRecursively = function (value) {};
  10039. proto._setTexture = function (texture) {
  10040. var node = this._node;
  10041. if (node._texture !== texture) {
  10042. if (texture) {
  10043. node._textureLoaded = texture._textureLoaded;
  10044. }else{
  10045. node._textureLoaded = false;
  10046. }
  10047. node._texture = texture;
  10048. this._updateColor();
  10049. }
  10050. };
  10051. proto._setColorDirty = function () {
  10052. this.setDirtyFlag(cc.Node._dirtyFlags.colorDirty | cc.Node._dirtyFlags.opacityDirty);
  10053. };
  10054. proto.isFrameDisplayed = function (frame) {
  10055. var node = this._node;
  10056. if (frame.getTexture() !== node._texture)
  10057. return false;
  10058. return cc.rectEqualToRect(frame.getRect(), node._rect);
  10059. };
  10060. proto.updateBlendFunc = function (blendFunc) {
  10061. this._blendFuncStr = cc.Node.CanvasRenderCmd._getCompositeOperationByBlendFunc(blendFunc);
  10062. };
  10063. proto._setBatchNodeForAddChild = function (child) {
  10064. return true;
  10065. };
  10066. proto._handleTextureForRotatedTexture = function (texture, rect, rotated, counterclockwise) {
  10067. if (rotated && texture.isLoaded()) {
  10068. var tempElement = texture.getHtmlElementObj();
  10069. tempElement = cc.Sprite.CanvasRenderCmd._cutRotateImageToCanvas(tempElement, rect, counterclockwise);
  10070. var tempTexture = new cc.Texture2D();
  10071. tempTexture.initWithElement(tempElement);
  10072. tempTexture.handleLoadedTexture();
  10073. texture = tempTexture;
  10074. rect.x = rect.y = 0;
  10075. this._node._rect = cc.rect(0, 0, rect.width, rect.height);
  10076. }
  10077. return texture;
  10078. };
  10079. proto._checkTextureBoundary = function (texture, rect, rotated) {
  10080. if (texture && texture.url) {
  10081. var _x = rect.x + rect.width, _y = rect.y + rect.height;
  10082. if (_x > texture.width)
  10083. cc.error(cc._LogInfos.RectWidth, texture.url);
  10084. if (_y > texture.height)
  10085. cc.error(cc._LogInfos.RectHeight, texture.url);
  10086. }
  10087. };
  10088. proto.rendering = function (ctx, scaleX, scaleY) {
  10089. var node = this._node;
  10090. var locTextureCoord = this._textureCoord, alpha = (this._displayedOpacity / 255);
  10091. var texture = this._textureToRender || node._texture;
  10092. if ((texture && (locTextureCoord.width === 0 || locTextureCoord.height === 0|| !texture._textureLoaded)) || alpha === 0)
  10093. return;
  10094. var wrapper = ctx || cc._renderContext, context = wrapper.getContext();
  10095. var locX = node._offsetPosition.x, locHeight = node._rect.height, locWidth = node._rect.width,
  10096. locY = -node._offsetPosition.y - locHeight, image;
  10097. wrapper.setTransform(this._worldTransform, scaleX, scaleY);
  10098. wrapper.setCompositeOperation(this._blendFuncStr);
  10099. wrapper.setGlobalAlpha(alpha);
  10100. if(node._flippedX || node._flippedY)
  10101. wrapper.save();
  10102. if (node._flippedX) {
  10103. locX = -locX - locWidth;
  10104. context.scale(-1, 1);
  10105. }
  10106. if (node._flippedY) {
  10107. locY = node._offsetPosition.y;
  10108. context.scale(1, -1);
  10109. }
  10110. var sx, sy, sw, sh, x, y, w, h;
  10111. if (this._colorized) {
  10112. sx = 0;
  10113. sy = 0;
  10114. }else{
  10115. sx = locTextureCoord.renderX;
  10116. sy = locTextureCoord.renderY;
  10117. }
  10118. sw = locTextureCoord.width;
  10119. sh = locTextureCoord.height;
  10120. x = locX;
  10121. y = locY;
  10122. w = locWidth;
  10123. h = locHeight;
  10124. if (texture && texture._htmlElementObj) {
  10125. image = texture._htmlElementObj;
  10126. if (texture._pattern !== "") {
  10127. wrapper.setFillStyle(context.createPattern(image, texture._pattern));
  10128. context.fillRect(x, y, w, h);
  10129. } else {
  10130. context.drawImage(image,
  10131. sx, sy, sw, sh,
  10132. x, y, w, h);
  10133. }
  10134. } else {
  10135. var contentSize = node._contentSize;
  10136. if (locTextureCoord.validRect) {
  10137. var curColor = this._displayedColor;
  10138. wrapper.setFillStyle("rgba(" + curColor.r + "," + curColor.g + "," + curColor.b + ",1)");
  10139. context.fillRect(x, y, contentSize.width * scaleX, contentSize.height * scaleY);
  10140. }
  10141. }
  10142. if(node._flippedX || node._flippedY)
  10143. wrapper.restore();
  10144. cc.g_NumberOfDraws++;
  10145. };
  10146. proto._updateColor = function(){
  10147. var node = this._node;
  10148. var texture = node._texture, rect = this._textureCoord;
  10149. var dColor = this._displayedColor;
  10150. if(texture){
  10151. if(dColor.r !== 255 || dColor.g !== 255 || dColor.b !== 255){
  10152. this._textureToRender = texture._generateColorTexture(dColor.r, dColor.g, dColor.b, rect);
  10153. this._colorized = true;
  10154. }else if(texture){
  10155. this._textureToRender = texture;
  10156. this._colorized = false;
  10157. }
  10158. }
  10159. };
  10160. proto._textureLoadedCallback = function (sender) {
  10161. var node = this;
  10162. if (node._textureLoaded)
  10163. return;
  10164. node._textureLoaded = true;
  10165. var locRect = node._rect, locRenderCmd = this._renderCmd;
  10166. if (!locRect) {
  10167. locRect = cc.rect(0, 0, sender.width, sender.height);
  10168. } else if (cc._rectEqualToZero(locRect)) {
  10169. locRect.width = sender.width;
  10170. locRect.height = sender.height;
  10171. }
  10172. node.texture = sender;
  10173. node.setTextureRect(locRect, node._rectRotated);
  10174. var locColor = locRenderCmd._displayedColor;
  10175. if (locColor.r !== 255 || locColor.g !== 255 || locColor.b !== 255)
  10176. locRenderCmd._updateColor();
  10177. node.setBatchNode(node._batchNode);
  10178. node.dispatchEvent("load");
  10179. };
  10180. proto._setTextureCoords = function (rect, needConvert) {
  10181. if (needConvert === undefined)
  10182. needConvert = true;
  10183. var locTextureRect = this._textureCoord,
  10184. scaleFactor = needConvert ? cc.contentScaleFactor() : 1;
  10185. locTextureRect.renderX = locTextureRect.x = 0 | (rect.x * scaleFactor);
  10186. locTextureRect.renderY = locTextureRect.y = 0 | (rect.y * scaleFactor);
  10187. locTextureRect.width = 0 | (rect.width * scaleFactor);
  10188. locTextureRect.height = 0 | (rect.height * scaleFactor);
  10189. locTextureRect.validRect = !(locTextureRect.width === 0 || locTextureRect.height === 0 || locTextureRect.x < 0 || locTextureRect.y < 0);
  10190. };
  10191. cc.Sprite.CanvasRenderCmd._cutRotateImageToCanvas = function (texture, rect, counterclockwise) {
  10192. if (!texture)
  10193. return null;
  10194. if (!rect)
  10195. return texture;
  10196. counterclockwise = counterclockwise == null? true: counterclockwise;
  10197. var nCanvas = document.createElement("canvas");
  10198. nCanvas.width = rect.width;
  10199. nCanvas.height = rect.height;
  10200. var ctx = nCanvas.getContext("2d");
  10201. ctx.translate(nCanvas.width / 2, nCanvas.height / 2);
  10202. if(counterclockwise)
  10203. ctx.rotate(-1.5707963267948966);
  10204. else
  10205. ctx.rotate(1.5707963267948966);
  10206. ctx.drawImage(texture, rect.x, rect.y, rect.height, rect.width, -rect.height / 2, -rect.width / 2, rect.height, rect.width);
  10207. return nCanvas;
  10208. };
  10209. })();
  10210. cc.BakeSprite = cc.Sprite.extend({
  10211. _cacheCanvas: null,
  10212. _cacheContext: null,
  10213. ctor: function(){
  10214. cc.Sprite.prototype.ctor.call(this);
  10215. var canvasElement = document.createElement("canvas");
  10216. canvasElement.width = canvasElement.height = 10;
  10217. this._cacheCanvas = canvasElement;
  10218. this._cacheContext = new cc.CanvasContextWrapper(canvasElement.getContext("2d"));
  10219. var texture = new cc.Texture2D();
  10220. texture.initWithElement(canvasElement);
  10221. texture.handleLoadedTexture();
  10222. this.setTexture(texture);
  10223. },
  10224. getCacheContext: function(){
  10225. return this._cacheContext;
  10226. },
  10227. getCacheCanvas: function(){
  10228. return this._cacheCanvas;
  10229. },
  10230. resetCanvasSize: function(sizeOrWidth, height){
  10231. var locCanvas = this._cacheCanvas,
  10232. locContext = this._cacheContext,
  10233. strokeStyle = locContext._context.strokeStyle,
  10234. fillStyle = locContext._context.fillStyle;
  10235. if(height === undefined){
  10236. height = sizeOrWidth.height;
  10237. sizeOrWidth = sizeOrWidth.width;
  10238. }
  10239. locCanvas.width = sizeOrWidth;
  10240. locCanvas.height = height;
  10241. if(strokeStyle !== locContext._context.strokeStyle)
  10242. locContext._context.strokeStyle = strokeStyle;
  10243. if(fillStyle !== locContext._context.fillStyle)
  10244. locContext._context.fillStyle = fillStyle;
  10245. this.getTexture().handleLoadedTexture();
  10246. this.setTextureRect(cc.rect(0,0, sizeOrWidth, height), false, null, false);
  10247. }
  10248. });
  10249. cc.AnimationFrame = cc.Class.extend({
  10250. _spriteFrame:null,
  10251. _delayPerUnit:0,
  10252. _userInfo:null,
  10253. ctor:function (spriteFrame, delayUnits, userInfo) {
  10254. this._spriteFrame = spriteFrame || null;
  10255. this._delayPerUnit = delayUnits || 0;
  10256. this._userInfo = userInfo || null;
  10257. },
  10258. clone: function(){
  10259. var frame = new cc.AnimationFrame();
  10260. frame.initWithSpriteFrame(this._spriteFrame.clone(), this._delayPerUnit, this._userInfo);
  10261. return frame;
  10262. },
  10263. copyWithZone:function (pZone) {
  10264. return cc.clone(this);
  10265. },
  10266. copy:function (pZone) {
  10267. var newFrame = new cc.AnimationFrame();
  10268. newFrame.initWithSpriteFrame(this._spriteFrame.clone(), this._delayPerUnit, this._userInfo);
  10269. return newFrame;
  10270. },
  10271. initWithSpriteFrame:function (spriteFrame, delayUnits, userInfo) {
  10272. this._spriteFrame = spriteFrame;
  10273. this._delayPerUnit = delayUnits;
  10274. this._userInfo = userInfo;
  10275. return true;
  10276. },
  10277. getSpriteFrame:function () {
  10278. return this._spriteFrame;
  10279. },
  10280. setSpriteFrame:function (spriteFrame) {
  10281. this._spriteFrame = spriteFrame;
  10282. },
  10283. getDelayUnits:function () {
  10284. return this._delayPerUnit;
  10285. },
  10286. setDelayUnits:function (delayUnits) {
  10287. this._delayPerUnit = delayUnits;
  10288. },
  10289. getUserInfo:function () {
  10290. return this._userInfo;
  10291. },
  10292. setUserInfo:function (userInfo) {
  10293. this._userInfo = userInfo;
  10294. }
  10295. });
  10296. cc.AnimationFrame.create = function(spriteFrame,delayUnits,userInfo){
  10297. return new cc.AnimationFrame(spriteFrame,delayUnits,userInfo);
  10298. };
  10299. cc.Animation = cc.Class.extend({
  10300. _frames:null,
  10301. _loops:0,
  10302. _restoreOriginalFrame:false,
  10303. _duration:0,
  10304. _delayPerUnit:0,
  10305. _totalDelayUnits:0,
  10306. ctor:function (frames, delay, loops) {
  10307. this._frames = [];
  10308. if (frames === undefined) {
  10309. this.initWithSpriteFrames(null, 0);
  10310. } else {
  10311. var frame0 = frames[0];
  10312. if(frame0){
  10313. if (frame0 instanceof cc.SpriteFrame) {
  10314. this.initWithSpriteFrames(frames, delay, loops);
  10315. }else if(frame0 instanceof cc.AnimationFrame) {
  10316. this.initWithAnimationFrames(frames, delay, loops);
  10317. }
  10318. }
  10319. }
  10320. },
  10321. getFrames:function () {
  10322. return this._frames;
  10323. },
  10324. setFrames:function (frames) {
  10325. this._frames = frames;
  10326. },
  10327. addSpriteFrame:function (frame) {
  10328. var animFrame = new cc.AnimationFrame();
  10329. animFrame.initWithSpriteFrame(frame, 1, null);
  10330. this._frames.push(animFrame);
  10331. this._totalDelayUnits++;
  10332. },
  10333. addSpriteFrameWithFile:function (fileName) {
  10334. var texture = cc.textureCache.addImage(fileName);
  10335. var rect = cc.rect(0, 0, 0, 0);
  10336. rect.width = texture.width;
  10337. rect.height = texture.height;
  10338. var frame = new cc.SpriteFrame(texture, rect);
  10339. this.addSpriteFrame(frame);
  10340. },
  10341. addSpriteFrameWithTexture:function (texture, rect) {
  10342. var pFrame = new cc.SpriteFrame(texture, rect);
  10343. this.addSpriteFrame(pFrame);
  10344. },
  10345. initWithAnimationFrames:function (arrayOfAnimationFrames, delayPerUnit, loops) {
  10346. cc.arrayVerifyType(arrayOfAnimationFrames, cc.AnimationFrame);
  10347. this._delayPerUnit = delayPerUnit;
  10348. this._loops = loops === undefined ? 1 : loops;
  10349. this._totalDelayUnits = 0;
  10350. var locFrames = this._frames;
  10351. locFrames.length = 0;
  10352. for (var i = 0; i < arrayOfAnimationFrames.length; i++) {
  10353. var animFrame = arrayOfAnimationFrames[i];
  10354. locFrames.push(animFrame);
  10355. this._totalDelayUnits += animFrame.getDelayUnits();
  10356. }
  10357. return true;
  10358. },
  10359. clone: function(){
  10360. var animation = new cc.Animation();
  10361. animation.initWithAnimationFrames(this._copyFrames(), this._delayPerUnit, this._loops);
  10362. animation.setRestoreOriginalFrame(this._restoreOriginalFrame);
  10363. return animation;
  10364. },
  10365. copyWithZone:function (pZone) {
  10366. var pCopy = new cc.Animation();
  10367. pCopy.initWithAnimationFrames(this._copyFrames(), this._delayPerUnit, this._loops);
  10368. pCopy.setRestoreOriginalFrame(this._restoreOriginalFrame);
  10369. return pCopy;
  10370. },
  10371. _copyFrames:function(){
  10372. var copyFrames = [];
  10373. for(var i = 0; i< this._frames.length;i++)
  10374. copyFrames.push(this._frames[i].clone());
  10375. return copyFrames;
  10376. },
  10377. copy:function (pZone) {
  10378. return this.copyWithZone(null);
  10379. },
  10380. getLoops:function () {
  10381. return this._loops;
  10382. },
  10383. setLoops:function (value) {
  10384. this._loops = value;
  10385. },
  10386. setRestoreOriginalFrame:function (restOrigFrame) {
  10387. this._restoreOriginalFrame = restOrigFrame;
  10388. },
  10389. getRestoreOriginalFrame:function () {
  10390. return this._restoreOriginalFrame;
  10391. },
  10392. getDuration:function () {
  10393. return this._totalDelayUnits * this._delayPerUnit;
  10394. },
  10395. getDelayPerUnit:function () {
  10396. return this._delayPerUnit;
  10397. },
  10398. setDelayPerUnit:function (delayPerUnit) {
  10399. this._delayPerUnit = delayPerUnit;
  10400. },
  10401. getTotalDelayUnits:function () {
  10402. return this._totalDelayUnits;
  10403. },
  10404. initWithSpriteFrames:function (frames, delay, loops) {
  10405. cc.arrayVerifyType(frames, cc.SpriteFrame);
  10406. this._loops = loops === undefined ? 1 : loops;
  10407. this._delayPerUnit = delay || 0;
  10408. this._totalDelayUnits = 0;
  10409. var locFrames = this._frames;
  10410. locFrames.length = 0;
  10411. if (frames) {
  10412. for (var i = 0; i < frames.length; i++) {
  10413. var frame = frames[i];
  10414. var animFrame = new cc.AnimationFrame();
  10415. animFrame.initWithSpriteFrame(frame, 1, null);
  10416. locFrames.push(animFrame);
  10417. }
  10418. this._totalDelayUnits += frames.length;
  10419. }
  10420. return true;
  10421. },
  10422. retain:function () {
  10423. },
  10424. release:function () {
  10425. }
  10426. });
  10427. cc.Animation.create = function (frames, delay, loops) {
  10428. return new cc.Animation(frames, delay, loops);
  10429. };
  10430. cc.Animation.createWithAnimationFrames = cc.Animation.create;
  10431. cc.animationCache = {
  10432. _animations: {},
  10433. addAnimation:function (animation, name) {
  10434. this._animations[name] = animation;
  10435. },
  10436. removeAnimation:function (name) {
  10437. if (!name) {
  10438. return;
  10439. }
  10440. if (this._animations[name]) {
  10441. delete this._animations[name];
  10442. }
  10443. },
  10444. getAnimation:function (name) {
  10445. if (this._animations[name])
  10446. return this._animations[name];
  10447. return null;
  10448. },
  10449. _addAnimationsWithDictionary:function (dictionary,plist) {
  10450. var animations = dictionary["animations"];
  10451. if (!animations) {
  10452. cc.log(cc._LogInfos.animationCache__addAnimationsWithDictionary);
  10453. return;
  10454. }
  10455. var version = 1;
  10456. var properties = dictionary["properties"];
  10457. if (properties) {
  10458. version = (properties["format"] != null) ? parseInt(properties["format"]) : version;
  10459. var spritesheets = properties["spritesheets"];
  10460. var spriteFrameCache = cc.spriteFrameCache;
  10461. var path = cc.path;
  10462. for (var i = 0; i < spritesheets.length; i++) {
  10463. spriteFrameCache.addSpriteFrames(path.changeBasename(plist, spritesheets[i]));
  10464. }
  10465. }
  10466. switch (version) {
  10467. case 1:
  10468. this._parseVersion1(animations);
  10469. break;
  10470. case 2:
  10471. this._parseVersion2(animations);
  10472. break;
  10473. default :
  10474. cc.log(cc._LogInfos.animationCache__addAnimationsWithDictionary_2);
  10475. break;
  10476. }
  10477. },
  10478. addAnimations:function (plist) {
  10479. cc.assert(plist, cc._LogInfos.animationCache_addAnimations_2);
  10480. var dict = cc.loader.getRes(plist);
  10481. if(!dict){
  10482. cc.log(cc._LogInfos.animationCache_addAnimations);
  10483. return;
  10484. }
  10485. this._addAnimationsWithDictionary(dict,plist);
  10486. },
  10487. _parseVersion1:function (animations) {
  10488. var frameCache = cc.spriteFrameCache;
  10489. for (var key in animations) {
  10490. var animationDict = animations[key];
  10491. var frameNames = animationDict["frames"];
  10492. var delay = parseFloat(animationDict["delay"]) || 0;
  10493. var animation = null;
  10494. if (!frameNames) {
  10495. cc.log(cc._LogInfos.animationCache__parseVersion1, key);
  10496. continue;
  10497. }
  10498. var frames = [];
  10499. for (var i = 0; i < frameNames.length; i++) {
  10500. var spriteFrame = frameCache.getSpriteFrame(frameNames[i]);
  10501. if (!spriteFrame) {
  10502. cc.log(cc._LogInfos.animationCache__parseVersion1_2, key, frameNames[i]);
  10503. continue;
  10504. }
  10505. var animFrame = new cc.AnimationFrame();
  10506. animFrame.initWithSpriteFrame(spriteFrame, 1, null);
  10507. frames.push(animFrame);
  10508. }
  10509. if (frames.length === 0) {
  10510. cc.log(cc._LogInfos.animationCache__parseVersion1_3, key);
  10511. continue;
  10512. } else if (frames.length !== frameNames.length) {
  10513. cc.log(cc._LogInfos.animationCache__parseVersion1_4, key);
  10514. }
  10515. animation = new cc.Animation(frames, delay, 1);
  10516. cc.animationCache.addAnimation(animation, key);
  10517. }
  10518. },
  10519. _parseVersion2:function (animations) {
  10520. var frameCache = cc.spriteFrameCache;
  10521. for (var key in animations) {
  10522. var animationDict = animations[key];
  10523. var isLoop = animationDict["loop"];
  10524. var loopsTemp = parseInt(animationDict["loops"]);
  10525. var loops = isLoop ? cc.REPEAT_FOREVER : ((isNaN(loopsTemp)) ? 1 : loopsTemp);
  10526. var restoreOriginalFrame = (animationDict["restoreOriginalFrame"] && animationDict["restoreOriginalFrame"] == true) ? true : false;
  10527. var frameArray = animationDict["frames"];
  10528. if (!frameArray) {
  10529. cc.log(cc._LogInfos.animationCache__parseVersion2, key);
  10530. continue;
  10531. }
  10532. var arr = [];
  10533. for (var i = 0; i < frameArray.length; i++) {
  10534. var entry = frameArray[i];
  10535. var spriteFrameName = entry["spriteframe"];
  10536. var spriteFrame = frameCache.getSpriteFrame(spriteFrameName);
  10537. if (!spriteFrame) {
  10538. cc.log(cc._LogInfos.animationCache__parseVersion2_2, key, spriteFrameName);
  10539. continue;
  10540. }
  10541. var delayUnits = parseFloat(entry["delayUnits"]) || 0;
  10542. var userInfo = entry["notification"];
  10543. var animFrame = new cc.AnimationFrame();
  10544. animFrame.initWithSpriteFrame(spriteFrame, delayUnits, userInfo);
  10545. arr.push(animFrame);
  10546. }
  10547. var delayPerUnit = parseFloat(animationDict["delayPerUnit"]) || 0;
  10548. var animation = new cc.Animation();
  10549. animation.initWithAnimationFrames(arr, delayPerUnit, loops);
  10550. animation.setRestoreOriginalFrame(restoreOriginalFrame);
  10551. cc.animationCache.addAnimation(animation, key);
  10552. }
  10553. },
  10554. _clear: function () {
  10555. this._animations = {};
  10556. }
  10557. };
  10558. cc.SpriteFrame = cc.Class.extend({
  10559. _offset:null,
  10560. _originalSize:null,
  10561. _rectInPixels:null,
  10562. _rotated:false,
  10563. _rect:null,
  10564. _offsetInPixels:null,
  10565. _originalSizeInPixels:null,
  10566. _texture:null,
  10567. _textureFilename:"",
  10568. _textureLoaded:false,
  10569. ctor:function (filename, rect, rotated, offset, originalSize) {
  10570. this._offset = cc.p(0, 0);
  10571. this._offsetInPixels = cc.p(0, 0);
  10572. this._originalSize = cc.size(0, 0);
  10573. this._rotated = false;
  10574. this._originalSizeInPixels = cc.size(0, 0);
  10575. this._textureFilename = "";
  10576. this._texture = null;
  10577. this._textureLoaded = false;
  10578. if(filename !== undefined && rect !== undefined ){
  10579. if(rotated === undefined || offset === undefined || originalSize === undefined)
  10580. this.initWithTexture(filename, rect);
  10581. else
  10582. this.initWithTexture(filename, rect, rotated, offset, originalSize)
  10583. }
  10584. },
  10585. textureLoaded:function(){
  10586. return this._textureLoaded;
  10587. },
  10588. addLoadedEventListener:function(callback, target){
  10589. this.addEventListener("load", callback, target);
  10590. },
  10591. getRectInPixels:function () {
  10592. var locRectInPixels = this._rectInPixels;
  10593. return cc.rect(locRectInPixels.x, locRectInPixels.y, locRectInPixels.width, locRectInPixels.height);
  10594. },
  10595. setRectInPixels:function (rectInPixels) {
  10596. if (!this._rectInPixels){
  10597. this._rectInPixels = cc.rect(0,0,0,0);
  10598. }
  10599. this._rectInPixels.x = rectInPixels.x;
  10600. this._rectInPixels.y = rectInPixels.y;
  10601. this._rectInPixels.width = rectInPixels.width;
  10602. this._rectInPixels.height = rectInPixels.height;
  10603. this._rect = cc.rectPixelsToPoints(rectInPixels);
  10604. },
  10605. isRotated:function () {
  10606. return this._rotated;
  10607. },
  10608. setRotated:function (bRotated) {
  10609. this._rotated = bRotated;
  10610. },
  10611. getRect:function () {
  10612. var locRect = this._rect;
  10613. return cc.rect(locRect.x, locRect.y, locRect.width, locRect.height);
  10614. },
  10615. setRect:function (rect) {
  10616. if (!this._rect){
  10617. this._rect = cc.rect(0,0,0,0);
  10618. }
  10619. this._rect.x = rect.x;
  10620. this._rect.y = rect.y;
  10621. this._rect.width = rect.width;
  10622. this._rect.height = rect.height;
  10623. this._rectInPixels = cc.rectPointsToPixels(this._rect);
  10624. },
  10625. getOffsetInPixels:function () {
  10626. return cc.p(this._offsetInPixels);
  10627. },
  10628. setOffsetInPixels:function (offsetInPixels) {
  10629. this._offsetInPixels.x = offsetInPixels.x;
  10630. this._offsetInPixels.y = offsetInPixels.y;
  10631. cc._pointPixelsToPointsOut(this._offsetInPixels, this._offset);
  10632. },
  10633. getOriginalSizeInPixels:function () {
  10634. return cc.size(this._originalSizeInPixels);
  10635. },
  10636. setOriginalSizeInPixels:function (sizeInPixels) {
  10637. this._originalSizeInPixels.width = sizeInPixels.width;
  10638. this._originalSizeInPixels.height = sizeInPixels.height;
  10639. },
  10640. getOriginalSize:function () {
  10641. return cc.size(this._originalSize);
  10642. },
  10643. setOriginalSize:function (sizeInPixels) {
  10644. this._originalSize.width = sizeInPixels.width;
  10645. this._originalSize.height = sizeInPixels.height;
  10646. },
  10647. getTexture:function () {
  10648. if (this._texture)
  10649. return this._texture;
  10650. if (this._textureFilename !== "") {
  10651. var locTexture = cc.textureCache.addImage(this._textureFilename);
  10652. if (locTexture)
  10653. this._textureLoaded = locTexture.isLoaded();
  10654. return locTexture;
  10655. }
  10656. return null;
  10657. },
  10658. setTexture:function (texture) {
  10659. if (this._texture !== texture) {
  10660. var locLoaded = texture.isLoaded();
  10661. this._textureLoaded = locLoaded;
  10662. this._texture = texture;
  10663. if(!locLoaded){
  10664. texture.addEventListener("load", function(sender){
  10665. this._textureLoaded = true;
  10666. if(this._rotated && cc._renderType === cc.game.RENDER_TYPE_CANVAS){
  10667. var tempElement = sender.getHtmlElementObj();
  10668. tempElement = cc.Sprite.CanvasRenderCmd._cutRotateImageToCanvas(tempElement, this.getRect());
  10669. var tempTexture = new cc.Texture2D();
  10670. tempTexture.initWithElement(tempElement);
  10671. tempTexture.handleLoadedTexture();
  10672. this.setTexture(tempTexture);
  10673. var rect = this.getRect();
  10674. this.setRect(cc.rect(0, 0, rect.width, rect.height));
  10675. }
  10676. var locRect = this._rect;
  10677. if(locRect.width === 0 && locRect.height === 0){
  10678. var w = sender.width, h = sender.height;
  10679. this._rect.width = w;
  10680. this._rect.height = h;
  10681. this._rectInPixels = cc.rectPointsToPixels(this._rect);
  10682. this._originalSizeInPixels.width = this._rectInPixels.width;
  10683. this._originalSizeInPixels.height = this._rectInPixels.height;
  10684. this._originalSize.width = w;
  10685. this._originalSize.height = h;
  10686. }
  10687. this.dispatchEvent("load");
  10688. }, this);
  10689. }
  10690. }
  10691. },
  10692. getOffset:function () {
  10693. return cc.p(this._offset);
  10694. },
  10695. setOffset:function (offsets) {
  10696. this._offset.x = offsets.x;
  10697. this._offset.y = offsets.y;
  10698. },
  10699. clone: function(){
  10700. var frame = new cc.SpriteFrame();
  10701. frame.initWithTexture(this._textureFilename, this._rectInPixels, this._rotated, this._offsetInPixels, this._originalSizeInPixels);
  10702. frame.setTexture(this._texture);
  10703. return frame;
  10704. },
  10705. copyWithZone:function () {
  10706. var copy = new cc.SpriteFrame();
  10707. copy.initWithTexture(this._textureFilename, this._rectInPixels, this._rotated, this._offsetInPixels, this._originalSizeInPixels);
  10708. copy.setTexture(this._texture);
  10709. return copy;
  10710. },
  10711. copy:function () {
  10712. return this.copyWithZone();
  10713. },
  10714. initWithTexture:function (texture, rect, rotated, offset, originalSize) {
  10715. if(arguments.length === 2)
  10716. rect = cc.rectPointsToPixels(rect);
  10717. offset = offset || cc.p(0, 0);
  10718. originalSize = originalSize || rect;
  10719. rotated = rotated || false;
  10720. if (cc.isString(texture)){
  10721. this._texture = null;
  10722. this._textureFilename = texture;
  10723. } else if (texture instanceof cc.Texture2D){
  10724. this.setTexture(texture);
  10725. }
  10726. texture = this.getTexture();
  10727. this._rectInPixels = rect;
  10728. this._rect = cc.rectPixelsToPoints(rect);
  10729. if(texture && texture.url && texture.isLoaded()) {
  10730. var _x, _y;
  10731. if(rotated){
  10732. _x = rect.x + rect.height;
  10733. _y = rect.y + rect.width;
  10734. }else{
  10735. _x = rect.x + rect.width;
  10736. _y = rect.y + rect.height;
  10737. }
  10738. if(_x > texture.getPixelsWide()){
  10739. cc.error(cc._LogInfos.RectWidth, texture.url);
  10740. }
  10741. if(_y > texture.getPixelsHigh()){
  10742. cc.error(cc._LogInfos.RectHeight, texture.url);
  10743. }
  10744. }
  10745. this._offsetInPixels.x = offset.x;
  10746. this._offsetInPixels.y = offset.y;
  10747. cc._pointPixelsToPointsOut(offset, this._offset);
  10748. this._originalSizeInPixels.width = originalSize.width;
  10749. this._originalSizeInPixels.height = originalSize.height;
  10750. cc._sizePixelsToPointsOut(originalSize, this._originalSize);
  10751. this._rotated = rotated;
  10752. return true;
  10753. }
  10754. });
  10755. cc.EventHelper.prototype.apply(cc.SpriteFrame.prototype);
  10756. cc.SpriteFrame.create = function (filename, rect, rotated, offset, originalSize) {
  10757. return new cc.SpriteFrame(filename,rect,rotated,offset,originalSize);
  10758. };
  10759. cc.SpriteFrame.createWithTexture = cc.SpriteFrame.create;
  10760. cc.SpriteFrame._frameWithTextureForCanvas = function (texture, rect, rotated, offset, originalSize) {
  10761. var spriteFrame = new cc.SpriteFrame();
  10762. spriteFrame._texture = texture;
  10763. spriteFrame._rectInPixels = rect;
  10764. spriteFrame._rect = cc.rectPixelsToPoints(rect);
  10765. spriteFrame._offsetInPixels.x = offset.x;
  10766. spriteFrame._offsetInPixels.y = offset.y;
  10767. cc._pointPixelsToPointsOut(spriteFrame._offsetInPixels, spriteFrame._offset);
  10768. spriteFrame._originalSizeInPixels.width = originalSize.width;
  10769. spriteFrame._originalSizeInPixels.height = originalSize.height;
  10770. cc._sizePixelsToPointsOut(spriteFrame._originalSizeInPixels, spriteFrame._originalSize);
  10771. spriteFrame._rotated = rotated;
  10772. return spriteFrame;
  10773. };
  10774. cc.spriteFrameCache = {
  10775. _CCNS_REG1 : /^\s*\{\s*([\-]?\d+[.]?\d*)\s*,\s*([\-]?\d+[.]?\d*)\s*\}\s*$/,
  10776. _CCNS_REG2 : /^\s*\{\s*\{\s*([\-]?\d+[.]?\d*)\s*,\s*([\-]?\d+[.]?\d*)\s*\}\s*,\s*\{\s*([\-]?\d+[.]?\d*)\s*,\s*([\-]?\d+[.]?\d*)\s*\}\s*\}\s*$/,
  10777. _spriteFrames: {},
  10778. _spriteFramesAliases: {},
  10779. _frameConfigCache : {},
  10780. _rectFromString : function (content) {
  10781. var result = this._CCNS_REG2.exec(content);
  10782. if(!result) return cc.rect(0, 0, 0, 0);
  10783. return cc.rect(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3]), parseFloat(result[4]));
  10784. },
  10785. _pointFromString : function (content) {
  10786. var result = this._CCNS_REG1.exec(content);
  10787. if(!result) return cc.p(0,0);
  10788. return cc.p(parseFloat(result[1]), parseFloat(result[2]));
  10789. },
  10790. _sizeFromString : function (content) {
  10791. var result = this._CCNS_REG1.exec(content);
  10792. if(!result) return cc.size(0, 0);
  10793. return cc.size(parseFloat(result[1]), parseFloat(result[2]));
  10794. },
  10795. _getFrameConfig : function(url){
  10796. var dict = cc.loader.getRes(url);
  10797. cc.assert(dict, cc._LogInfos.spriteFrameCache__getFrameConfig_2, url);
  10798. cc.loader.release(url);//release it in loader
  10799. if(dict._inited){
  10800. this._frameConfigCache[url] = dict;
  10801. return dict;
  10802. }
  10803. this._frameConfigCache[url] = this._parseFrameConfig(dict);
  10804. return this._frameConfigCache[url];
  10805. },
  10806. _getFrameConfigByJsonObject: function(url, jsonObject) {
  10807. cc.assert(jsonObject, cc._LogInfos.spriteFrameCache__getFrameConfig_2, url);
  10808. this._frameConfigCache[url] = this._parseFrameConfig(jsonObject);
  10809. return this._frameConfigCache[url];
  10810. },
  10811. _parseFrameConfig: function(dict) {
  10812. var tempFrames = dict["frames"], tempMeta = dict["metadata"] || dict["meta"];
  10813. var frames = {}, meta = {};
  10814. var format = 0;
  10815. if(tempMeta){//init meta
  10816. var tmpFormat = tempMeta["format"];
  10817. format = (tmpFormat.length <= 1) ? parseInt(tmpFormat) : tmpFormat;
  10818. meta.image = tempMeta["textureFileName"] || tempMeta["textureFileName"] || tempMeta["image"];
  10819. }
  10820. for (var key in tempFrames) {
  10821. var frameDict = tempFrames[key];
  10822. if(!frameDict) continue;
  10823. var tempFrame = {};
  10824. if (format == 0) {
  10825. tempFrame.rect = cc.rect(frameDict["x"], frameDict["y"], frameDict["width"], frameDict["height"]);
  10826. tempFrame.rotated = false;
  10827. tempFrame.offset = cc.p(frameDict["offsetX"], frameDict["offsetY"]);
  10828. var ow = frameDict["originalWidth"];
  10829. var oh = frameDict["originalHeight"];
  10830. if (!ow || !oh) {
  10831. cc.log(cc._LogInfos.spriteFrameCache__getFrameConfig);
  10832. }
  10833. ow = Math.abs(ow);
  10834. oh = Math.abs(oh);
  10835. tempFrame.size = cc.size(ow, oh);
  10836. } else if (format == 1 || format == 2) {
  10837. tempFrame.rect = this._rectFromString(frameDict["frame"]);
  10838. tempFrame.rotated = frameDict["rotated"] || false;
  10839. tempFrame.offset = this._pointFromString(frameDict["offset"]);
  10840. tempFrame.size = this._sizeFromString(frameDict["sourceSize"]);
  10841. } else if (format == 3) {
  10842. var spriteSize = this._sizeFromString(frameDict["spriteSize"]);
  10843. var textureRect = this._rectFromString(frameDict["textureRect"]);
  10844. if (spriteSize) {
  10845. textureRect = cc.rect(textureRect.x, textureRect.y, spriteSize.width, spriteSize.height);
  10846. }
  10847. tempFrame.rect = textureRect;
  10848. tempFrame.rotated = frameDict["textureRotated"] || false;
  10849. tempFrame.offset = this._pointFromString(frameDict["spriteOffset"]);
  10850. tempFrame.size = this._sizeFromString(frameDict["spriteSourceSize"]);
  10851. tempFrame.aliases = frameDict["aliases"];
  10852. } else {
  10853. var tmpFrame = frameDict["frame"], tmpSourceSize = frameDict["sourceSize"];
  10854. key = frameDict["filename"] || key;
  10855. tempFrame.rect = cc.rect(tmpFrame["x"], tmpFrame["y"], tmpFrame["w"], tmpFrame["h"]);
  10856. tempFrame.rotated = frameDict["rotated"] || false;
  10857. tempFrame.offset = cc.p(0, 0);
  10858. tempFrame.size = cc.size(tmpSourceSize["w"], tmpSourceSize["h"]);
  10859. }
  10860. frames[key] = tempFrame;
  10861. }
  10862. return {_inited: true, frames: frames, meta: meta};
  10863. },
  10864. _addSpriteFramesByObject: function(url, jsonObject, texture) {
  10865. cc.assert(url, cc._LogInfos.spriteFrameCache_addSpriteFrames_2);
  10866. if(!jsonObject || !jsonObject["frames"])
  10867. return;
  10868. var frameConfig = this._frameConfigCache[url] || this._getFrameConfigByJsonObject(url, jsonObject);
  10869. this._createSpriteFrames(url, frameConfig, texture);
  10870. },
  10871. _createSpriteFrames: function(url, frameConfig, texture) {
  10872. var frames = frameConfig.frames, meta = frameConfig.meta;
  10873. if(!texture){
  10874. var texturePath = cc.path.changeBasename(url, meta.image || ".png");
  10875. texture = cc.textureCache.addImage(texturePath);
  10876. }else if(texture instanceof cc.Texture2D){
  10877. }else if(cc.isString(texture)){//string
  10878. texture = cc.textureCache.addImage(texture);
  10879. }else{
  10880. cc.assert(0, cc._LogInfos.spriteFrameCache_addSpriteFrames_3);
  10881. }
  10882. var spAliases = this._spriteFramesAliases, spriteFrames = this._spriteFrames;
  10883. for (var key in frames) {
  10884. var frame = frames[key];
  10885. var spriteFrame = spriteFrames[key];
  10886. if (!spriteFrame) {
  10887. spriteFrame = new cc.SpriteFrame(texture, frame.rect, frame.rotated, frame.offset, frame.size);
  10888. var aliases = frame.aliases;
  10889. if(aliases){//set aliases
  10890. for(var i = 0, li = aliases.length; i < li; i++){
  10891. var alias = aliases[i];
  10892. if (spAliases[alias])
  10893. cc.log(cc._LogInfos.spriteFrameCache_addSpriteFrames, alias);
  10894. spAliases[alias] = key;
  10895. }
  10896. }
  10897. if (cc._renderType === cc.game.RENDER_TYPE_CANVAS && spriteFrame.isRotated()) {
  10898. var locTexture = spriteFrame.getTexture();
  10899. if (locTexture.isLoaded()) {
  10900. var tempElement = spriteFrame.getTexture().getHtmlElementObj();
  10901. tempElement = cc.Sprite.CanvasRenderCmd._cutRotateImageToCanvas(tempElement, spriteFrame.getRectInPixels());
  10902. var tempTexture = new cc.Texture2D();
  10903. tempTexture.initWithElement(tempElement);
  10904. tempTexture.handleLoadedTexture();
  10905. spriteFrame.setTexture(tempTexture);
  10906. var rect = spriteFrame._rect;
  10907. spriteFrame.setRect(cc.rect(0, 0, rect.width, rect.height));
  10908. }
  10909. }
  10910. spriteFrames[key] = spriteFrame;
  10911. }
  10912. }
  10913. },
  10914. addSpriteFrames: function (url, texture) {
  10915. cc.assert(url, cc._LogInfos.spriteFrameCache_addSpriteFrames_2);
  10916. var dict = this._frameConfigCache[url] || cc.loader.getRes(url);
  10917. if(!dict || !dict["frames"])
  10918. return;
  10919. var frameConfig = this._frameConfigCache[url] || this._getFrameConfig(url);
  10920. this._createSpriteFrames(url, frameConfig, texture);
  10921. },
  10922. _checkConflict: function (dictionary) {
  10923. var framesDict = dictionary["frames"];
  10924. for (var key in framesDict) {
  10925. if (this._spriteFrames[key]) {
  10926. cc.log(cc._LogInfos.spriteFrameCache__checkConflict, key);
  10927. }
  10928. }
  10929. },
  10930. addSpriteFrame: function (frame, frameName) {
  10931. this._spriteFrames[frameName] = frame;
  10932. },
  10933. removeSpriteFrames: function () {
  10934. this._spriteFrames = {};
  10935. this._spriteFramesAliases = {};
  10936. },
  10937. removeSpriteFrameByName: function (name) {
  10938. if (!name) {
  10939. return;
  10940. }
  10941. if (this._spriteFramesAliases[name]) {
  10942. delete(this._spriteFramesAliases[name]);
  10943. }
  10944. if (this._spriteFrames[name]) {
  10945. delete(this._spriteFrames[name]);
  10946. }
  10947. },
  10948. removeSpriteFramesFromFile: function (url) {
  10949. var self = this, spriteFrames = self._spriteFrames,
  10950. aliases = self._spriteFramesAliases, cfg = self._frameConfigCache[url];
  10951. if(!cfg) return;
  10952. var frames = cfg.frames;
  10953. for (var key in frames) {
  10954. if (spriteFrames[key]) {
  10955. delete(spriteFrames[key]);
  10956. for (var alias in aliases) {//remove alias
  10957. if(aliases[alias] === key) delete aliases[alias];
  10958. }
  10959. }
  10960. }
  10961. },
  10962. removeSpriteFramesFromTexture: function (texture) {
  10963. var self = this, spriteFrames = self._spriteFrames, aliases = self._spriteFramesAliases;
  10964. for (var key in spriteFrames) {
  10965. var frame = spriteFrames[key];
  10966. if (frame && (frame.getTexture() === texture)) {
  10967. delete(spriteFrames[key]);
  10968. for (var alias in aliases) {//remove alias
  10969. if(aliases[alias] === key) delete aliases[alias];
  10970. }
  10971. }
  10972. }
  10973. },
  10974. getSpriteFrame: function (name) {
  10975. var self = this, frame = self._spriteFrames[name];
  10976. if (!frame) {
  10977. var key = self._spriteFramesAliases[name];
  10978. if (key) {
  10979. frame = self._spriteFrames[key.toString()];
  10980. if(!frame) delete self._spriteFramesAliases[name];
  10981. }
  10982. }
  10983. return frame;
  10984. },
  10985. _clear: function () {
  10986. this._spriteFrames = {};
  10987. this._spriteFramesAliases = {};
  10988. this._frameConfigCache = {};
  10989. }
  10990. };
  10991. cc.g_NumberOfDraws = 0;
  10992. cc.Director = cc.Class.extend({
  10993. _landscape: false,
  10994. _nextDeltaTimeZero: false,
  10995. _paused: false,
  10996. _purgeDirectorInNextLoop: false,
  10997. _sendCleanupToScene: false,
  10998. _animationInterval: 0.0,
  10999. _oldAnimationInterval: 0.0,
  11000. _projection: 0,
  11001. _contentScaleFactor: 1.0,
  11002. _deltaTime: 0.0,
  11003. _winSizeInPoints: null,
  11004. _lastUpdate: null,
  11005. _nextScene: null,
  11006. _notificationNode: null,
  11007. _openGLView: null,
  11008. _scenesStack: null,
  11009. _projectionDelegate: null,
  11010. _runningScene: null,
  11011. _totalFrames: 0,
  11012. _secondsPerFrame: 0,
  11013. _dirtyRegion: null,
  11014. _scheduler: null,
  11015. _actionManager: null,
  11016. _eventProjectionChanged: null,
  11017. _eventAfterUpdate: null,
  11018. _eventAfterVisit: null,
  11019. _eventAfterDraw: null,
  11020. ctor: function () {
  11021. var self = this;
  11022. self._lastUpdate = Date.now();
  11023. cc.eventManager.addCustomListener(cc.game.EVENT_SHOW, function () {
  11024. self._lastUpdate = Date.now();
  11025. });
  11026. },
  11027. init: function () {
  11028. this._oldAnimationInterval = this._animationInterval = 1.0 / cc.defaultFPS;
  11029. this._scenesStack = [];
  11030. this._projection = cc.Director.PROJECTION_DEFAULT;
  11031. this._projectionDelegate = null;
  11032. this._totalFrames = 0;
  11033. this._lastUpdate = Date.now();
  11034. this._paused = false;
  11035. this._purgeDirectorInNextLoop = false;
  11036. this._winSizeInPoints = cc.size(0, 0);
  11037. this._openGLView = null;
  11038. this._contentScaleFactor = 1.0;
  11039. this._scheduler = new cc.Scheduler();
  11040. if(cc.ActionManager){
  11041. this._actionManager = new cc.ActionManager();
  11042. this._scheduler.scheduleUpdate(this._actionManager, cc.Scheduler.PRIORITY_SYSTEM, false);
  11043. }else{
  11044. this._actionManager = null;
  11045. }
  11046. this._eventAfterUpdate = new cc.EventCustom(cc.Director.EVENT_AFTER_UPDATE);
  11047. this._eventAfterUpdate.setUserData(this);
  11048. this._eventAfterVisit = new cc.EventCustom(cc.Director.EVENT_AFTER_VISIT);
  11049. this._eventAfterVisit.setUserData(this);
  11050. this._eventAfterDraw = new cc.EventCustom(cc.Director.EVENT_AFTER_DRAW);
  11051. this._eventAfterDraw.setUserData(this);
  11052. this._eventProjectionChanged = new cc.EventCustom(cc.Director.EVENT_PROJECTION_CHANGED);
  11053. this._eventProjectionChanged.setUserData(this);
  11054. return true;
  11055. },
  11056. calculateDeltaTime: function () {
  11057. var now = Date.now();
  11058. if (this._nextDeltaTimeZero) {
  11059. this._deltaTime = 0;
  11060. this._nextDeltaTimeZero = false;
  11061. } else {
  11062. this._deltaTime = (now - this._lastUpdate) / 1000;
  11063. }
  11064. if ((cc.game.config[cc.game.CONFIG_KEY.debugMode] > 0) && (this._deltaTime > 0.2))
  11065. this._deltaTime = 1 / 60.0;
  11066. this._lastUpdate = now;
  11067. },
  11068. convertToGL: function (uiPoint) {
  11069. var docElem = document.documentElement;
  11070. var view = cc.view;
  11071. var box = element.getBoundingClientRect();
  11072. box.left += window.pageXOffset - docElem.clientLeft;
  11073. box.top += window.pageYOffset - docElem.clientTop;
  11074. var x = view._devicePixelRatio * (uiPoint.x - box.left);
  11075. var y = view._devicePixelRatio * (box.top + box.height - uiPoint.y);
  11076. return view._isRotated ? {x: view._viewPortRect.width - y, y: x} : {x: x, y: y};
  11077. },
  11078. convertToUI: function (glPoint) {
  11079. var docElem = document.documentElement;
  11080. var view = cc.view;
  11081. var box = element.getBoundingClientRect();
  11082. box.left += window.pageXOffset - docElem.clientLeft;
  11083. box.top += window.pageYOffset - docElem.clientTop;
  11084. var uiPoint = {x: 0, y: 0};
  11085. if (view._isRotated) {
  11086. uiPoint.x = box.left + glPoint.y / view._devicePixelRatio;
  11087. uiPoint.y = box.top + box.height - (view._viewPortRect.width - glPoint.x) / view._devicePixelRatio;
  11088. }
  11089. else {
  11090. uiPoint.x = box.left + glPoint.x / view._devicePixelRatio;
  11091. uiPoint.y = box.top + box.height - glPoint.y / view._devicePixelRatio;
  11092. }
  11093. return uiPoint;
  11094. },
  11095. drawScene: function () {
  11096. var renderer = cc.renderer;
  11097. this.calculateDeltaTime();
  11098. if (!this._paused) {
  11099. this._scheduler.update(this._deltaTime);
  11100. cc.eventManager.dispatchEvent(this._eventAfterUpdate);
  11101. }
  11102. if (this._nextScene) {
  11103. this.setNextScene();
  11104. }
  11105. if (this._beforeVisitScene)
  11106. this._beforeVisitScene();
  11107. if (this._runningScene) {
  11108. if (renderer.childrenOrderDirty) {
  11109. cc.renderer.clearRenderCommands();
  11110. cc.renderer.assignedZ = 0;
  11111. this._runningScene._renderCmd._curLevel = 0;
  11112. this._runningScene.visit();
  11113. renderer.resetFlag();
  11114. }
  11115. else if (renderer.transformDirty()) {
  11116. renderer.transform();
  11117. }
  11118. }
  11119. renderer.clear();
  11120. if (this._notificationNode)
  11121. this._notificationNode.visit();
  11122. cc.eventManager.dispatchEvent(this._eventAfterVisit);
  11123. cc.g_NumberOfDraws = 0;
  11124. if (this._afterVisitScene)
  11125. this._afterVisitScene();
  11126. renderer.rendering(cc._renderContext);
  11127. this._totalFrames++;
  11128. cc.eventManager.dispatchEvent(this._eventAfterDraw);
  11129. this._calculateMPF();
  11130. },
  11131. _beforeVisitScene: null,
  11132. _afterVisitScene: null,
  11133. end: function () {
  11134. this._purgeDirectorInNextLoop = true;
  11135. },
  11136. getContentScaleFactor: function () {
  11137. return this._contentScaleFactor;
  11138. },
  11139. getNotificationNode: function () {
  11140. return this._notificationNode;
  11141. },
  11142. getWinSize: function () {
  11143. return cc.size(this._winSizeInPoints);
  11144. },
  11145. getWinSizeInPixels: function () {
  11146. return cc.size(this._winSizeInPoints.width * this._contentScaleFactor, this._winSizeInPoints.height * this._contentScaleFactor);
  11147. },
  11148. getVisibleSize: null,
  11149. getVisibleOrigin: null,
  11150. getZEye: null,
  11151. pause: function () {
  11152. if (this._paused)
  11153. return;
  11154. this._oldAnimationInterval = this._animationInterval;
  11155. this.setAnimationInterval(1 / 4.0);
  11156. this._paused = true;
  11157. },
  11158. popScene: function () {
  11159. cc.assert(this._runningScene, cc._LogInfos.Director_popScene);
  11160. this._scenesStack.pop();
  11161. var c = this._scenesStack.length;
  11162. if (c === 0)
  11163. this.end();
  11164. else {
  11165. this._sendCleanupToScene = true;
  11166. this._nextScene = this._scenesStack[c - 1];
  11167. }
  11168. },
  11169. purgeCachedData: function () {
  11170. cc.animationCache._clear();
  11171. cc.spriteFrameCache._clear();
  11172. cc.textureCache._clear();
  11173. },
  11174. purgeDirector: function () {
  11175. this.getScheduler().unscheduleAll();
  11176. if (cc.eventManager)
  11177. cc.eventManager.setEnabled(false);
  11178. if (this._runningScene) {
  11179. this._runningScene.onExitTransitionDidStart();
  11180. this._runningScene.onExit();
  11181. this._runningScene.cleanup();
  11182. }
  11183. this._runningScene = null;
  11184. this._nextScene = null;
  11185. this._scenesStack.length = 0;
  11186. this.stopAnimation();
  11187. this.purgeCachedData();
  11188. cc.checkGLErrorDebug();
  11189. },
  11190. pushScene: function (scene) {
  11191. cc.assert(scene, cc._LogInfos.Director_pushScene);
  11192. this._sendCleanupToScene = false;
  11193. this._scenesStack.push(scene);
  11194. this._nextScene = scene;
  11195. },
  11196. runScene: function (scene) {
  11197. cc.assert(scene, cc._LogInfos.Director_pushScene);
  11198. if (!this._runningScene) {
  11199. this.pushScene(scene);
  11200. this.startAnimation();
  11201. } else {
  11202. var i = this._scenesStack.length;
  11203. if (i === 0) {
  11204. this._sendCleanupToScene = true;
  11205. this._scenesStack[i] = scene;
  11206. this._nextScene = scene;
  11207. } else {
  11208. this._sendCleanupToScene = true;
  11209. this._scenesStack[i - 1] = scene;
  11210. this._nextScene = scene;
  11211. }
  11212. }
  11213. },
  11214. resume: function () {
  11215. if (!this._paused) {
  11216. return;
  11217. }
  11218. this.setAnimationInterval(this._oldAnimationInterval);
  11219. this._lastUpdate = Date.now();
  11220. if (!this._lastUpdate) {
  11221. cc.log(cc._LogInfos.Director_resume);
  11222. }
  11223. this._paused = false;
  11224. this._deltaTime = 0;
  11225. },
  11226. setContentScaleFactor: function (scaleFactor) {
  11227. if (scaleFactor !== this._contentScaleFactor) {
  11228. this._contentScaleFactor = scaleFactor;
  11229. }
  11230. },
  11231. setDepthTest: null,
  11232. setClearColor: null,
  11233. setDefaultValues: function () {
  11234. },
  11235. setNextDeltaTimeZero: function (nextDeltaTimeZero) {
  11236. this._nextDeltaTimeZero = nextDeltaTimeZero;
  11237. },
  11238. setNextScene: function () {
  11239. var runningIsTransition = false, newIsTransition = false;
  11240. if (cc.TransitionScene) {
  11241. runningIsTransition = this._runningScene ? this._runningScene instanceof cc.TransitionScene : false;
  11242. newIsTransition = this._nextScene ? this._nextScene instanceof cc.TransitionScene : false;
  11243. }
  11244. if (!newIsTransition) {
  11245. var locRunningScene = this._runningScene;
  11246. if (locRunningScene) {
  11247. locRunningScene.onExitTransitionDidStart();
  11248. locRunningScene.onExit();
  11249. }
  11250. if (this._sendCleanupToScene && locRunningScene)
  11251. locRunningScene.cleanup();
  11252. }
  11253. this._runningScene = this._nextScene;
  11254. cc.renderer.childrenOrderDirty = true;
  11255. this._nextScene = null;
  11256. if ((!runningIsTransition) && (this._runningScene !== null)) {
  11257. this._runningScene.onEnter();
  11258. this._runningScene.onEnterTransitionDidFinish();
  11259. }
  11260. },
  11261. setNotificationNode: function (node) {
  11262. cc.renderer.childrenOrderDirty = true;
  11263. if(this._notificationNode){
  11264. this._notificationNode.onExitTransitionDidStart();
  11265. this._notificationNode.onExit();
  11266. this._notificationNode.cleanup();
  11267. }
  11268. this._notificationNode = node;
  11269. if(!node)
  11270. return;
  11271. this._notificationNode.onEnter();
  11272. this._notificationNode.onEnterTransitionDidFinish();
  11273. },
  11274. getDelegate: function () {
  11275. return this._projectionDelegate;
  11276. },
  11277. setDelegate: function (delegate) {
  11278. this._projectionDelegate = delegate;
  11279. },
  11280. setOpenGLView: null,
  11281. setProjection: null,
  11282. setViewport: null,
  11283. getOpenGLView: null,
  11284. getProjection: null,
  11285. setAlphaBlending: null,
  11286. isSendCleanupToScene: function () {
  11287. return this._sendCleanupToScene;
  11288. },
  11289. getRunningScene: function () {
  11290. return this._runningScene;
  11291. },
  11292. getAnimationInterval: function () {
  11293. return this._animationInterval;
  11294. },
  11295. isDisplayStats: function () {
  11296. return cc.profiler ? cc.profiler.isShowingStats() : false;
  11297. },
  11298. setDisplayStats: function (displayStats) {
  11299. if (cc.profiler) {
  11300. displayStats ? cc.profiler.showStats() : cc.profiler.hideStats();
  11301. }
  11302. },
  11303. getSecondsPerFrame: function () {
  11304. return this._secondsPerFrame;
  11305. },
  11306. isNextDeltaTimeZero: function () {
  11307. return this._nextDeltaTimeZero;
  11308. },
  11309. isPaused: function () {
  11310. return this._paused;
  11311. },
  11312. getTotalFrames: function () {
  11313. return this._totalFrames;
  11314. },
  11315. popToRootScene: function () {
  11316. this.popToSceneStackLevel(1);
  11317. },
  11318. popToSceneStackLevel: function (level) {
  11319. cc.assert(this._runningScene, cc._LogInfos.Director_popToSceneStackLevel_2);
  11320. var locScenesStack = this._scenesStack;
  11321. var c = locScenesStack.length;
  11322. if (level === 0) {
  11323. this.end();
  11324. return;
  11325. }
  11326. if (level >= c)
  11327. return;
  11328. while (c > level) {
  11329. var current = locScenesStack.pop();
  11330. if (current.running) {
  11331. current.onExitTransitionDidStart();
  11332. current.onExit();
  11333. }
  11334. current.cleanup();
  11335. c--;
  11336. }
  11337. this._nextScene = locScenesStack[locScenesStack.length - 1];
  11338. this._sendCleanupToScene = true;
  11339. },
  11340. getScheduler: function () {
  11341. return this._scheduler;
  11342. },
  11343. setScheduler: function (scheduler) {
  11344. if (this._scheduler !== scheduler) {
  11345. this._scheduler = scheduler;
  11346. }
  11347. },
  11348. getActionManager: function () {
  11349. return this._actionManager;
  11350. },
  11351. setActionManager: function (actionManager) {
  11352. if (this._actionManager !== actionManager) {
  11353. this._actionManager = actionManager;
  11354. }
  11355. },
  11356. getDeltaTime: function () {
  11357. return this._deltaTime;
  11358. },
  11359. _calculateMPF: function () {
  11360. var now = Date.now();
  11361. this._secondsPerFrame = (now - this._lastUpdate) / 1000;
  11362. }
  11363. });
  11364. cc.Director.EVENT_PROJECTION_CHANGED = "director_projection_changed";
  11365. cc.Director.EVENT_AFTER_UPDATE = "director_after_update";
  11366. cc.Director.EVENT_AFTER_VISIT = "director_after_visit";
  11367. cc.Director.EVENT_AFTER_DRAW = "director_after_draw";
  11368. cc.DisplayLinkDirector = cc.Director.extend({
  11369. invalid: false,
  11370. startAnimation: function () {
  11371. this._nextDeltaTimeZero = true;
  11372. this.invalid = false;
  11373. },
  11374. mainLoop: function () {
  11375. if (this._purgeDirectorInNextLoop) {
  11376. this._purgeDirectorInNextLoop = false;
  11377. this.purgeDirector();
  11378. }
  11379. else if (!this.invalid) {
  11380. this.drawScene();
  11381. }
  11382. },
  11383. stopAnimation: function () {
  11384. this.invalid = true;
  11385. },
  11386. setAnimationInterval: function (value) {
  11387. this._animationInterval = value;
  11388. if (!this.invalid) {
  11389. this.stopAnimation();
  11390. this.startAnimation();
  11391. }
  11392. }
  11393. });
  11394. cc.Director.sharedDirector = null;
  11395. cc.Director.firstUseDirector = true;
  11396. cc.Director._getInstance = function () {
  11397. if (cc.Director.firstUseDirector) {
  11398. cc.Director.firstUseDirector = false;
  11399. cc.Director.sharedDirector = new cc.DisplayLinkDirector();
  11400. cc.Director.sharedDirector.init();
  11401. }
  11402. return cc.Director.sharedDirector;
  11403. };
  11404. cc.defaultFPS = 60;
  11405. cc.Director.PROJECTION_2D = 0;
  11406. cc.Director.PROJECTION_3D = 1;
  11407. cc.Director.PROJECTION_CUSTOM = 3;
  11408. cc.Director.PROJECTION_DEFAULT = cc.Director.PROJECTION_2D;
  11409. cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
  11410. if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) {
  11411. var _p = cc.Director.prototype;
  11412. _p.getProjection = function (projection) {
  11413. return this._projection;
  11414. };
  11415. _p.setProjection = function (projection) {
  11416. this._projection = projection;
  11417. cc.eventManager.dispatchEvent(this._eventProjectionChanged);
  11418. };
  11419. _p.setDepthTest = function () {
  11420. };
  11421. _p.setClearColor = function (clearColor) {
  11422. cc.renderer._clearColor = clearColor;
  11423. cc.renderer._clearFillStyle = 'rgb(' + clearColor.r + ',' + clearColor.g + ',' + clearColor.b +')' ;
  11424. };
  11425. _p.setOpenGLView = function (openGLView) {
  11426. this._winSizeInPoints.width = cc._canvas.width;
  11427. this._winSizeInPoints.height = cc._canvas.height;
  11428. this._openGLView = openGLView || cc.view;
  11429. if (cc.eventManager)
  11430. cc.eventManager.setEnabled(true);
  11431. };
  11432. _p.getVisibleSize = function () {
  11433. return this.getWinSize();
  11434. };
  11435. _p.getVisibleOrigin = function () {
  11436. return cc.p(0, 0);
  11437. };
  11438. } else {
  11439. cc.Director._fpsImage = new Image();
  11440. cc.Director._fpsImage.addEventListener("load", function () {
  11441. cc.Director._fpsImageLoaded = true;
  11442. });
  11443. if (cc._fpsImage) {
  11444. cc.Director._fpsImage.src = cc._fpsImage;
  11445. }
  11446. }
  11447. });
  11448. cc.PRIORITY_NON_SYSTEM = cc.PRIORITY_SYSTEM + 1;
  11449. cc.ListEntry = function (prev, next, callback, target, priority, paused, markedForDeletion) {
  11450. this.prev = prev;
  11451. this.next = next;
  11452. this.callback = callback;
  11453. this.target = target;
  11454. this.priority = priority;
  11455. this.paused = paused;
  11456. this.markedForDeletion = markedForDeletion;
  11457. };
  11458. cc.HashUpdateEntry = function (list, entry, target, callback, hh) {
  11459. this.list = list;
  11460. this.entry = entry;
  11461. this.target = target;
  11462. this.callback = callback;
  11463. this.hh = hh;
  11464. };
  11465. cc.HashTimerEntry = cc.hashSelectorEntry = function (timers, target, timerIndex, currentTimer, currentTimerSalvaged, paused, hh) {
  11466. var _t = this;
  11467. _t.timers = timers;
  11468. _t.target = target;
  11469. _t.timerIndex = timerIndex;
  11470. _t.currentTimer = currentTimer;
  11471. _t.currentTimerSalvaged = currentTimerSalvaged;
  11472. _t.paused = paused;
  11473. _t.hh = hh;
  11474. };
  11475. cc.Timer = cc.Class.extend({
  11476. _scheduler: null,
  11477. _elapsed:0.0,
  11478. _runForever:false,
  11479. _useDelay:false,
  11480. _timesExecuted:0,
  11481. _repeat:0,
  11482. _delay:0,
  11483. _interval:0.0,
  11484. getInterval : function(){return this._interval;},
  11485. setInterval : function(interval){this._interval = interval;},
  11486. setupTimerWithInterval: function(seconds, repeat, delay){
  11487. this._elapsed = -1;
  11488. this._interval = seconds;
  11489. this._delay = delay;
  11490. this._useDelay = (this._delay > 0);
  11491. this._repeat = repeat;
  11492. this._runForever = (this._repeat === cc.REPEAT_FOREVER);
  11493. },
  11494. trigger: function(){
  11495. return 0;
  11496. },
  11497. cancel: function(){
  11498. return 0;
  11499. },
  11500. ctor:function () {
  11501. this._scheduler = null;
  11502. this._elapsed = -1;
  11503. this._runForever = false;
  11504. this._useDelay = false;
  11505. this._timesExecuted = 0;
  11506. this._repeat = 0;
  11507. this._delay = 0;
  11508. this._interval = 0;
  11509. },
  11510. update:function (dt) {
  11511. if (this._elapsed === -1) {
  11512. this._elapsed = 0;
  11513. this._timesExecuted = 0;
  11514. } else {
  11515. this._elapsed += dt;
  11516. if (this._runForever && !this._useDelay) {//standard timer usage
  11517. if (this._elapsed >= this._interval) {
  11518. this.trigger();
  11519. this._elapsed = 0;
  11520. }
  11521. } else {//advanced usage
  11522. if (this._useDelay) {
  11523. if (this._elapsed >= this._delay) {
  11524. this.trigger();
  11525. this._elapsed -= this._delay;
  11526. this._timesExecuted += 1;
  11527. this._useDelay = false;
  11528. }
  11529. } else {
  11530. if (this._elapsed >= this._interval) {
  11531. this.trigger();
  11532. this._elapsed = 0;
  11533. this._timesExecuted += 1;
  11534. }
  11535. }
  11536. if (!this._runForever && this._timesExecuted > this._repeat)
  11537. this.cancel();
  11538. }
  11539. }
  11540. }
  11541. });
  11542. cc.TimerTargetSelector = cc.Timer.extend({
  11543. _target: null,
  11544. _selector: null,
  11545. ctor: function(){
  11546. this._target = null;
  11547. this._selector = null;
  11548. },
  11549. initWithSelector: function(scheduler, selector, target, seconds, repeat, delay){
  11550. this._scheduler = scheduler;
  11551. this._target = target;
  11552. this._selector = selector;
  11553. this.setupTimerWithInterval(seconds, repeat, delay);
  11554. return true;
  11555. },
  11556. getSelector: function(){
  11557. return this._selector;
  11558. },
  11559. trigger: function(){
  11560. if (this._target && this._selector){
  11561. this._target.call(this._selector, this._elapsed);
  11562. }
  11563. },
  11564. cancel: function(){
  11565. this._scheduler.unschedule(this._selector, this._target);
  11566. }
  11567. });
  11568. cc.TimerTargetCallback = cc.Timer.extend({
  11569. _target: null,
  11570. _callback: null,
  11571. _key: null,
  11572. ctor: function(){
  11573. this._target = null;
  11574. this._callback = null;
  11575. },
  11576. initWithCallback: function(scheduler, callback, target, key, seconds, repeat, delay){
  11577. this._scheduler = scheduler;
  11578. this._target = target;
  11579. this._callback = callback;
  11580. this._key = key;
  11581. this.setupTimerWithInterval(seconds, repeat, delay);
  11582. return true;
  11583. },
  11584. getCallback: function(){
  11585. return this._callback;
  11586. },
  11587. getKey: function(){
  11588. return this._key;
  11589. },
  11590. trigger: function(){
  11591. if(this._callback)
  11592. this._callback.call(this._target, this._elapsed);
  11593. },
  11594. cancel: function(){
  11595. this._scheduler.unschedule(this._callback, this._target);
  11596. }
  11597. });
  11598. cc.Scheduler = cc.Class.extend({
  11599. _timeScale:1.0,
  11600. _updatesNegList: null,
  11601. _updates0List: null,
  11602. _updatesPosList: null,
  11603. _hashForTimers:null,
  11604. _arrayForTimers:null,
  11605. _hashForUpdates:null,
  11606. _currentTarget:null,
  11607. _currentTargetSalvaged:false,
  11608. _updateHashLocked:false,
  11609. ctor:function () {
  11610. this._timeScale = 1.0;
  11611. this._updatesNegList = [];
  11612. this._updates0List = [];
  11613. this._updatesPosList = [];
  11614. this._hashForUpdates = {};
  11615. this._hashForTimers = {};
  11616. this._currentTarget = null;
  11617. this._currentTargetSalvaged = false;
  11618. this._updateHashLocked = false;
  11619. this._arrayForTimers = [];
  11620. },
  11621. _schedulePerFrame: function(callback, target, priority, paused){
  11622. var hashElement = this._hashForUpdates[target.__instanceId];
  11623. if (hashElement && hashElement.entry){
  11624. if (hashElement.entry.priority !== priority){
  11625. if (this._updateHashLocked){
  11626. cc.log("warning: you CANNOT change update priority in scheduled function");
  11627. hashElement.entry.markedForDeletion = false;
  11628. hashElement.entry.paused = paused;
  11629. return;
  11630. }else{
  11631. this.unscheduleUpdate(target);
  11632. }
  11633. }else{
  11634. hashElement.entry.markedForDeletion = false;
  11635. hashElement.entry.paused = paused;
  11636. return;
  11637. }
  11638. }
  11639. if (priority === 0){
  11640. this._appendIn(this._updates0List, callback, target, paused);
  11641. }else if (priority < 0){
  11642. this._priorityIn(this._updatesNegList, callback, target, priority, paused);
  11643. }else{
  11644. this._priorityIn(this._updatesPosList, callback, target, priority, paused);
  11645. }
  11646. },
  11647. _removeHashElement:function (element) {
  11648. delete this._hashForTimers[element.target.__instanceId];
  11649. cc.arrayRemoveObject(this._arrayForTimers, element);
  11650. element.Timer = null;
  11651. element.target = null;
  11652. element = null;
  11653. },
  11654. _removeUpdateFromHash:function (entry) {
  11655. var self = this, element = self._hashForUpdates[entry.target.__instanceId];
  11656. if (element) {
  11657. cc.arrayRemoveObject(element.list, element.entry);
  11658. delete self._hashForUpdates[element.target.__instanceId];
  11659. element.entry = null;
  11660. element.target = null;
  11661. }
  11662. },
  11663. _priorityIn:function (ppList, callback, target, priority, paused) {
  11664. var self = this,
  11665. listElement = new cc.ListEntry(null, null, callback, target, priority, paused, false);
  11666. if (!ppList) {
  11667. ppList = [];
  11668. ppList.push(listElement);
  11669. } else {
  11670. var index2Insert = ppList.length - 1;
  11671. for(var i = 0; i <= index2Insert; i++){
  11672. if (priority < ppList[i].priority) {
  11673. index2Insert = i;
  11674. break;
  11675. }
  11676. }
  11677. ppList.splice(i, 0, listElement);
  11678. }
  11679. self._hashForUpdates[target.__instanceId] = new cc.HashUpdateEntry(ppList, listElement, target, null);
  11680. return ppList;
  11681. },
  11682. _appendIn:function (ppList, callback, target, paused) {
  11683. var self = this, listElement = new cc.ListEntry(null, null, callback, target, 0, paused, false);
  11684. ppList.push(listElement);
  11685. self._hashForUpdates[target.__instanceId] = new cc.HashUpdateEntry(ppList, listElement, target, null, null);
  11686. },
  11687. setTimeScale:function (timeScale) {
  11688. this._timeScale = timeScale;
  11689. },
  11690. getTimeScale:function () {
  11691. return this._timeScale;
  11692. },
  11693. update:function (dt) {
  11694. this._updateHashLocked = true;
  11695. if(this._timeScale !== 1)
  11696. dt *= this._timeScale;
  11697. var i, list, len, entry;
  11698. for(i=0,list=this._updatesNegList, len = list.length; i<len; i++){
  11699. entry = list[i];
  11700. if(!entry.paused && !entry.markedForDeletion)
  11701. entry.callback(dt);
  11702. }
  11703. for(i=0, list=this._updates0List, len=list.length; i<len; i++){
  11704. entry = list[i];
  11705. if (!entry.paused && !entry.markedForDeletion)
  11706. entry.callback(dt);
  11707. }
  11708. for(i=0, list=this._updatesPosList, len=list.length; i<len; i++){
  11709. entry = list[i];
  11710. if (!entry.paused && !entry.markedForDeletion)
  11711. entry.callback(dt);
  11712. }
  11713. var elt, arr = this._arrayForTimers;
  11714. for(i=0; i<arr.length; i++){
  11715. elt = arr[i];
  11716. this._currentTarget = elt;
  11717. this._currentTargetSalvaged = false;
  11718. if (!elt.paused){
  11719. for (elt.timerIndex = 0; elt.timerIndex < elt.timers.length; ++(elt.timerIndex)){
  11720. elt.currentTimer = elt.timers[elt.timerIndex];
  11721. elt.currentTimerSalvaged = false;
  11722. elt.currentTimer.update(dt);
  11723. elt.currentTimer = null;
  11724. }
  11725. }
  11726. if (this._currentTargetSalvaged && this._currentTarget.timers.length === 0)
  11727. this._removeHashElement(this._currentTarget);
  11728. }
  11729. for(i=0,list=this._updatesNegList; i<list.length; ){
  11730. entry = list[i];
  11731. if(entry.markedForDeletion)
  11732. this._removeUpdateFromHash(entry);
  11733. else
  11734. i++;
  11735. }
  11736. for(i=0, list=this._updates0List; i<list.length; ){
  11737. entry = list[i];
  11738. if (entry.markedForDeletion)
  11739. this._removeUpdateFromHash(entry);
  11740. else
  11741. i++;
  11742. }
  11743. for(i=0, list=this._updatesPosList; i<list.length; ){
  11744. entry = list[i];
  11745. if (entry.markedForDeletion)
  11746. this._removeUpdateFromHash(entry);
  11747. else
  11748. i++;
  11749. }
  11750. this._updateHashLocked = false;
  11751. this._currentTarget = null;
  11752. },
  11753. scheduleCallbackForTarget: function(target, callback_fn, interval, repeat, delay, paused){
  11754. this.schedule(callback_fn, target, interval, repeat, delay, paused, target.__instanceId + "");
  11755. },
  11756. schedule: function(callback, target, interval, repeat, delay, paused, key){
  11757. var isSelector = false;
  11758. if(typeof callback !== "function"){
  11759. var selector = callback;
  11760. isSelector = true;
  11761. }
  11762. if(isSelector === false){
  11763. if(arguments.length === 4 || arguments.length === 5){
  11764. key = delay;
  11765. paused = repeat;
  11766. delay = 0;
  11767. repeat = cc.REPEAT_FOREVER;
  11768. }
  11769. }else{
  11770. if(arguments.length === 4){
  11771. paused = repeat;
  11772. repeat = cc.REPEAT_FOREVER;
  11773. delay = 0;
  11774. }
  11775. }
  11776. if (key === undefined) {
  11777. key = target.__instanceId + "";
  11778. }
  11779. cc.assert(target, cc._LogInfos.Scheduler_scheduleCallbackForTarget_3);
  11780. var element = this._hashForTimers[target.__instanceId];
  11781. if(!element){
  11782. element = new cc.HashTimerEntry(null, target, 0, null, null, paused, null);
  11783. this._arrayForTimers.push(element);
  11784. this._hashForTimers[target.__instanceId] = element;
  11785. }else{
  11786. cc.assert(element.paused === paused, "");
  11787. }
  11788. var timer, i;
  11789. if (element.timers == null) {
  11790. element.timers = [];
  11791. } else if(isSelector === false) {
  11792. for (i = 0; i < element.timers.length; i++) {
  11793. timer = element.timers[i];
  11794. if (callback === timer._callback) {
  11795. cc.log(cc._LogInfos.Scheduler_scheduleCallbackForTarget, timer.getInterval().toFixed(4), interval.toFixed(4));
  11796. timer._interval = interval;
  11797. return;
  11798. }
  11799. }
  11800. }else{
  11801. for (i = 0; i < element.timers.length; ++i){
  11802. timer =element.timers[i];
  11803. if (timer && selector === timer.getSelector()){
  11804. cc.log("CCScheduler#scheduleSelector. Selector already scheduled. Updating interval from: %.4f to %.4f", timer.getInterval(), interval);
  11805. timer.setInterval(interval);
  11806. return;
  11807. }
  11808. }
  11809. }
  11810. if(isSelector === false){
  11811. timer = new cc.TimerTargetCallback();
  11812. timer.initWithCallback(this, callback, target, key, interval, repeat, delay);
  11813. element.timers.push(timer);
  11814. }else{
  11815. timer = new cc.TimerTargetSelector();
  11816. timer.initWithSelector(this, selector, target, interval, repeat, delay);
  11817. element.timers.push(timer);
  11818. }
  11819. },
  11820. scheduleUpdate: function(target, priority, paused){
  11821. this._schedulePerFrame(function(dt){
  11822. target.update(dt);
  11823. }, target, priority, paused);
  11824. },
  11825. _getUnscheduleMark: function(key, timer){
  11826. switch (typeof key){
  11827. case "number":
  11828. case "string":
  11829. return key === timer.getKey();
  11830. case "function":
  11831. return key === timer._callback;
  11832. default:
  11833. return key === timer.getSelector();
  11834. }
  11835. },
  11836. unschedule: function(key, target){
  11837. if (!target || !key)
  11838. return;
  11839. var self = this, element = self._hashForTimers[target.__instanceId];
  11840. if (element) {
  11841. var timers = element.timers;
  11842. for(var i = 0, li = timers.length; i < li; i++){
  11843. var timer = timers[i];
  11844. if (this._getUnscheduleMark(key, timer)) {
  11845. if ((timer === element.currentTimer) && (!element.currentTimerSalvaged)) {
  11846. element.currentTimerSalvaged = true;
  11847. }
  11848. timers.splice(i, 1);
  11849. if (element.timerIndex >= i) {
  11850. element.timerIndex--;
  11851. }
  11852. if (timers.length === 0) {
  11853. if (self._currentTarget === element) {
  11854. self._currentTargetSalvaged = true;
  11855. } else {
  11856. self._removeHashElement(element);
  11857. }
  11858. }
  11859. return;
  11860. }
  11861. }
  11862. }
  11863. },
  11864. unscheduleUpdate: function(target){
  11865. if (target == null)
  11866. return;
  11867. var element = this._hashForUpdates[target.__instanceId];
  11868. if (element){
  11869. if (this._updateHashLocked){
  11870. element.entry.markedForDeletion = true;
  11871. }else{
  11872. this._removeUpdateFromHash(element.entry);
  11873. }
  11874. }
  11875. },
  11876. unscheduleAllForTarget: function(target){
  11877. if (target == null){
  11878. return;
  11879. }
  11880. var element = this._hashForTimers[target.__instanceId];
  11881. if (element){
  11882. if (element.timers.indexOf(element.currentTimer) > -1
  11883. && (! element.currentTimerSalvaged)){
  11884. element.currentTimerSalvaged = true;
  11885. }
  11886. element.timers.length = 0;
  11887. if (this._currentTarget === element){
  11888. this._currentTargetSalvaged = true;
  11889. }else{
  11890. this._removeHashElement(element);
  11891. }
  11892. }
  11893. this.unscheduleUpdate(target);
  11894. },
  11895. unscheduleAll: function(){
  11896. this.unscheduleAllWithMinPriority(cc.Scheduler.PRIORITY_SYSTEM);
  11897. },
  11898. unscheduleAllWithMinPriority: function(minPriority){
  11899. var i, element, arr = this._arrayForTimers;
  11900. for(i=arr.length-1; i>=0; i--){
  11901. element = arr[i];
  11902. this.unscheduleAllForTarget(element.target);
  11903. }
  11904. var entry;
  11905. var temp_length = 0;
  11906. if(minPriority < 0){
  11907. for(i=0; i<this._updatesNegList.length; ){
  11908. temp_length = this._updatesNegList.length;
  11909. entry = this._updatesNegList[i];
  11910. if(entry && entry.priority >= minPriority)
  11911. this.unscheduleUpdate(entry.target);
  11912. if (temp_length == this._updatesNegList.length)
  11913. i++;
  11914. }
  11915. }
  11916. if(minPriority <= 0){
  11917. for(i=0; i<this._updates0List.length; ){
  11918. temp_length = this._updates0List.length;
  11919. entry = this._updates0List[i];
  11920. if (entry)
  11921. this.unscheduleUpdate(entry.target);
  11922. if (temp_length == this._updates0List.length)
  11923. i++;
  11924. }
  11925. }
  11926. for(i=0; i<this._updatesPosList.length; ){
  11927. temp_length = this._updatesPosList.length;
  11928. entry = this._updatesPosList[i];
  11929. if(entry && entry.priority >= minPriority)
  11930. this.unscheduleUpdate(entry.target);
  11931. if (temp_length == this._updatesPosList.length)
  11932. i++;
  11933. }
  11934. },
  11935. isScheduled: function(key, target){
  11936. cc.assert(key, "Argument key must not be empty");
  11937. cc.assert(target, "Argument target must be non-nullptr");
  11938. var element = this._hashForUpdates[target.__instanceId];
  11939. if (!element){
  11940. return false;
  11941. }
  11942. if (element.timers == null){
  11943. return false;
  11944. }else{
  11945. var timers = element.timers;
  11946. for (var i = 0; i < timers.length; ++i){
  11947. var timer = timers[i];
  11948. if (key === timer.getKey()){
  11949. return true;
  11950. }
  11951. }
  11952. return false;
  11953. }
  11954. },
  11955. pauseAllTargets:function () {
  11956. return this.pauseAllTargetsWithMinPriority(cc.Scheduler.PRIORITY_SYSTEM);
  11957. },
  11958. pauseAllTargetsWithMinPriority:function (minPriority) {
  11959. var idsWithSelectors = [];
  11960. var self = this, element, locArrayForTimers = self._arrayForTimers;
  11961. var i, li;
  11962. for(i = 0, li = locArrayForTimers.length; i < li; i++){
  11963. element = locArrayForTimers[i];
  11964. if (element) {
  11965. element.paused = true;
  11966. idsWithSelectors.push(element.target);
  11967. }
  11968. }
  11969. var entry;
  11970. if(minPriority < 0){
  11971. for(i=0; i<this._updatesNegList.length; i++){
  11972. entry = this._updatesNegList[i];
  11973. if (entry) {
  11974. if(entry.priority >= minPriority){
  11975. entry.paused = true;
  11976. idsWithSelectors.push(entry.target);
  11977. }
  11978. }
  11979. }
  11980. }
  11981. if(minPriority <= 0){
  11982. for(i=0; i<this._updates0List.length; i++){
  11983. entry = this._updates0List[i];
  11984. if (entry) {
  11985. entry.paused = true;
  11986. idsWithSelectors.push(entry.target);
  11987. }
  11988. }
  11989. }
  11990. for(i=0; i<this._updatesPosList.length; i++){
  11991. entry = this._updatesPosList[i];
  11992. if (entry) {
  11993. if(entry.priority >= minPriority){
  11994. entry.paused = true;
  11995. idsWithSelectors.push(entry.target);
  11996. }
  11997. }
  11998. }
  11999. return idsWithSelectors;
  12000. },
  12001. resumeTargets:function (targetsToResume) {
  12002. if (!targetsToResume)
  12003. return;
  12004. for (var i = 0; i < targetsToResume.length; i++) {
  12005. this.resumeTarget(targetsToResume[i]);
  12006. }
  12007. },
  12008. pauseTarget:function (target) {
  12009. cc.assert(target, cc._LogInfos.Scheduler_pauseTarget);
  12010. var self = this, element = self._hashForTimers[target.__instanceId];
  12011. if (element) {
  12012. element.paused = true;
  12013. }
  12014. var elementUpdate = self._hashForUpdates[target.__instanceId];
  12015. if (elementUpdate) {
  12016. elementUpdate.entry.paused = true;
  12017. }
  12018. },
  12019. resumeTarget:function (target) {
  12020. cc.assert(target, cc._LogInfos.Scheduler_resumeTarget);
  12021. var self = this, element = self._hashForTimers[target.__instanceId];
  12022. if (element) {
  12023. element.paused = false;
  12024. }
  12025. var elementUpdate = self._hashForUpdates[target.__instanceId];
  12026. if (elementUpdate) {
  12027. elementUpdate.entry.paused = false;
  12028. }
  12029. },
  12030. isTargetPaused:function (target) {
  12031. cc.assert(target, cc._LogInfos.Scheduler_isTargetPaused);
  12032. var element = this._hashForTimers[target.__instanceId];
  12033. if (element) {
  12034. return element.paused;
  12035. }
  12036. var elementUpdate = this._hashForUpdates[target.__instanceId];
  12037. if (elementUpdate) {
  12038. return elementUpdate.entry.paused;
  12039. }
  12040. return false;
  12041. },
  12042. scheduleUpdateForTarget: function(target, priority, paused){
  12043. this.scheduleUpdate(target, priority, paused);
  12044. },
  12045. unscheduleCallbackForTarget:function (target, callback) {
  12046. this.unschedule(callback, target);
  12047. },
  12048. unscheduleUpdateForTarget:function (target) {
  12049. this.unscheduleUpdate(target);
  12050. },
  12051. unscheduleAllCallbacksForTarget: function(target){
  12052. this.unschedule(target.__instanceId + "", target);
  12053. },
  12054. unscheduleAllCallbacks: function(){
  12055. this.unscheduleAllWithMinPriority(cc.Scheduler.PRIORITY_SYSTEM);
  12056. },
  12057. unscheduleAllCallbacksWithMinPriority:function (minPriority) {
  12058. this.unscheduleAllWithMinPriority(minPriority);
  12059. }
  12060. });
  12061. cc.Scheduler.PRIORITY_SYSTEM = (-2147483647 - 1);
  12062. cc._tmp.PrototypeLabelTTF = function () {
  12063. var _p = cc.LabelTTF.prototype;
  12064. cc.defineGetterSetter(_p, "color", _p.getColor, _p.setColor);
  12065. cc.defineGetterSetter(_p, "opacity", _p.getOpacity, _p.setOpacity);
  12066. _p.string;
  12067. cc.defineGetterSetter(_p, "string", _p.getString, _p.setString);
  12068. _p.textAlign;
  12069. cc.defineGetterSetter(_p, "textAlign", _p.getHorizontalAlignment, _p.setHorizontalAlignment);
  12070. _p.verticalAlign;
  12071. cc.defineGetterSetter(_p, "verticalAlign", _p.getVerticalAlignment, _p.setVerticalAlignment);
  12072. _p.fontSize;
  12073. cc.defineGetterSetter(_p, "fontSize", _p.getFontSize, _p.setFontSize);
  12074. _p.fontName;
  12075. cc.defineGetterSetter(_p, "fontName", _p.getFontName, _p.setFontName);
  12076. _p.font;
  12077. cc.defineGetterSetter(_p, "font", _p._getFont, _p._setFont);
  12078. _p.boundingSize;
  12079. _p.boundingWidth;
  12080. cc.defineGetterSetter(_p, "boundingWidth", _p._getBoundingWidth, _p._setBoundingWidth);
  12081. _p.boundingHeight;
  12082. cc.defineGetterSetter(_p, "boundingHeight", _p._getBoundingHeight, _p._setBoundingHeight);
  12083. _p.fillStyle;
  12084. cc.defineGetterSetter(_p, "fillStyle", _p._getFillStyle, _p.setFontFillColor);
  12085. _p.strokeStyle;
  12086. cc.defineGetterSetter(_p, "strokeStyle", _p._getStrokeStyle, _p._setStrokeStyle);
  12087. _p.lineWidth;
  12088. cc.defineGetterSetter(_p, "lineWidth", _p._getLineWidth, _p._setLineWidth);
  12089. _p.shadowOffset;
  12090. _p.shadowOffsetX;
  12091. cc.defineGetterSetter(_p, "shadowOffsetX", _p._getShadowOffsetX, _p._setShadowOffsetX);
  12092. _p.shadowOffsetY;
  12093. cc.defineGetterSetter(_p, "shadowOffsetY", _p._getShadowOffsetY, _p._setShadowOffsetY);
  12094. _p.shadowOpacity;
  12095. cc.defineGetterSetter(_p, "shadowOpacity", _p._getShadowOpacity, _p._setShadowOpacity);
  12096. _p.shadowBlur;
  12097. cc.defineGetterSetter(_p, "shadowBlur", _p._getShadowBlur, _p._setShadowBlur);
  12098. };
  12099. cc.LabelTTF = cc.Sprite.extend({
  12100. _dimensions: null,
  12101. _hAlignment: cc.TEXT_ALIGNMENT_CENTER,
  12102. _vAlignment: cc.VERTICAL_TEXT_ALIGNMENT_TOP,
  12103. _fontName: null,
  12104. _fontSize: 0.0,
  12105. _string: "",
  12106. _originalText: null,
  12107. _onCacheCanvasMode: true,
  12108. _shadowEnabled: false,
  12109. _shadowOffset: null,
  12110. _shadowOpacity: 0,
  12111. _shadowBlur: 0,
  12112. _shadowColor: null,
  12113. _strokeEnabled: false,
  12114. _strokeColor: null,
  12115. _strokeSize: 0,
  12116. _textFillColor: null,
  12117. _strokeShadowOffsetX: 0,
  12118. _strokeShadowOffsetY: 0,
  12119. _needUpdateTexture: false,
  12120. _lineWidths: null,
  12121. _className: "LabelTTF",
  12122. _fontStyle: "normal",
  12123. _fontWeight: "normal",
  12124. _lineHeight: "normal",
  12125. initWithString: function (label, fontName, fontSize, dimensions, hAlignment, vAlignment) {
  12126. var strInfo;
  12127. if (label)
  12128. strInfo = label + "";
  12129. else
  12130. strInfo = "";
  12131. fontSize = fontSize || 16;
  12132. dimensions = dimensions || cc.size(0, 0);
  12133. hAlignment = hAlignment || cc.TEXT_ALIGNMENT_LEFT;
  12134. vAlignment = vAlignment || cc.VERTICAL_TEXT_ALIGNMENT_TOP;
  12135. this._opacityModifyRGB = false;
  12136. this._dimensions = cc.size(dimensions.width, dimensions.height);
  12137. this._fontName = fontName || "Arial";
  12138. this._hAlignment = hAlignment;
  12139. this._vAlignment = vAlignment;
  12140. this._fontSize = fontSize;
  12141. this._renderCmd._setFontStyle(this._fontName, fontSize, this._fontStyle, this._fontWeight);
  12142. this.string = strInfo;
  12143. this._renderCmd._setColorsString();
  12144. this._renderCmd._updateTexture();
  12145. this._setUpdateTextureDirty();
  12146. this._scaleX = this._scaleY = 1 / cc.view.getDevicePixelRatio();
  12147. return true;
  12148. },
  12149. _setUpdateTextureDirty: function () {
  12150. this._needUpdateTexture = true;
  12151. this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.textDirty);
  12152. },
  12153. ctor: function (text, fontName, fontSize, dimensions, hAlignment, vAlignment) {
  12154. cc.Sprite.prototype.ctor.call(this);
  12155. this._dimensions = cc.size(0, 0);
  12156. this._hAlignment = cc.TEXT_ALIGNMENT_LEFT;
  12157. this._vAlignment = cc.VERTICAL_TEXT_ALIGNMENT_TOP;
  12158. this._opacityModifyRGB = false;
  12159. this._fontName = "Arial";
  12160. this._shadowEnabled = false;
  12161. this._shadowOffset = cc.p(0, 0);
  12162. this._shadowOpacity = 0;
  12163. this._shadowBlur = 0;
  12164. this._strokeEnabled = false;
  12165. this._strokeColor = cc.color(255, 255, 255, 255);
  12166. this._strokeSize = 0;
  12167. this._textFillColor = cc.color(255, 255, 255, 255);
  12168. this._strokeShadowOffsetX = 0;
  12169. this._strokeShadowOffsetY = 0;
  12170. this._needUpdateTexture = false;
  12171. this._lineWidths = [];
  12172. this._renderCmd._setColorsString();
  12173. this._textureLoaded = true;
  12174. if (fontName && fontName instanceof cc.FontDefinition) {
  12175. this.initWithStringAndTextDefinition(text, fontName);
  12176. } else {
  12177. cc.LabelTTF.prototype.initWithString.call(this, text, fontName, fontSize, dimensions, hAlignment, vAlignment);
  12178. }
  12179. },
  12180. init: function () {
  12181. return this.initWithString(" ", this._fontName, this._fontSize);
  12182. },
  12183. description: function () {
  12184. return "<cc.LabelTTF | FontName =" + this._fontName + " FontSize = " + this._fontSize.toFixed(1) + ">";
  12185. },
  12186. getLineHeight: function () {
  12187. return !this._lineHeight || this._lineHeight.charAt ?
  12188. this._renderCmd._getFontClientHeight() :
  12189. this._lineHeight || this._renderCmd._getFontClientHeight();
  12190. },
  12191. setLineHeight: function (lineHeight) {
  12192. this._lineHeight = lineHeight;
  12193. },
  12194. getString: function () {
  12195. return this._string;
  12196. },
  12197. getHorizontalAlignment: function () {
  12198. return this._hAlignment;
  12199. },
  12200. getVerticalAlignment: function () {
  12201. return this._vAlignment;
  12202. },
  12203. getDimensions: function () {
  12204. return cc.size(this._dimensions);
  12205. },
  12206. getFontSize: function () {
  12207. return this._fontSize;
  12208. },
  12209. getFontName: function () {
  12210. return this._fontName;
  12211. },
  12212. initWithStringAndTextDefinition: function (text, textDefinition) {
  12213. this._updateWithTextDefinition(textDefinition, false);
  12214. this.string = text;
  12215. return true;
  12216. },
  12217. setTextDefinition: function (theDefinition) {
  12218. if (theDefinition)
  12219. this._updateWithTextDefinition(theDefinition, true);
  12220. },
  12221. getTextDefinition: function () {
  12222. return this._prepareTextDefinition(false);
  12223. },
  12224. enableShadow: function (a, b, c, d) {
  12225. if (a.r != null && a.g != null && a.b != null && a.a != null) {
  12226. this._enableShadow(a, b, c);
  12227. } else {
  12228. this._enableShadowNoneColor(a, b, c, d);
  12229. }
  12230. },
  12231. _enableShadowNoneColor: function (shadowOffsetX, shadowOffsetY, shadowOpacity, shadowBlur) {
  12232. shadowOpacity = shadowOpacity || 0.5;
  12233. if (false === this._shadowEnabled)
  12234. this._shadowEnabled = true;
  12235. var locShadowOffset = this._shadowOffset;
  12236. if (locShadowOffset && (locShadowOffset.x !== shadowOffsetX) || (locShadowOffset._y !== shadowOffsetY)) {
  12237. locShadowOffset.x = shadowOffsetX;
  12238. locShadowOffset.y = shadowOffsetY;
  12239. }
  12240. if (this._shadowOpacity !== shadowOpacity) {
  12241. this._shadowOpacity = shadowOpacity;
  12242. }
  12243. this._renderCmd._setColorsString();
  12244. if (this._shadowBlur !== shadowBlur)
  12245. this._shadowBlur = shadowBlur;
  12246. this._setUpdateTextureDirty();
  12247. },
  12248. _enableShadow: function (shadowColor, offset, blurRadius) {
  12249. if (!this._shadowColor) {
  12250. this._shadowColor = cc.color(255, 255, 255, 128);
  12251. }
  12252. this._shadowColor.r = shadowColor.r;
  12253. this._shadowColor.g = shadowColor.g;
  12254. this._shadowColor.b = shadowColor.b;
  12255. var x, y, a, b;
  12256. x = offset.width || offset.x || 0;
  12257. y = offset.height || offset.y || 0;
  12258. a = (shadowColor.a != null) ? (shadowColor.a / 255) : 0.5;
  12259. b = blurRadius;
  12260. this._enableShadowNoneColor(x, y, a, b);
  12261. },
  12262. _getShadowOffsetX: function () {
  12263. return this._shadowOffset.x;
  12264. },
  12265. _setShadowOffsetX: function (x) {
  12266. if (false === this._shadowEnabled)
  12267. this._shadowEnabled = true;
  12268. if (this._shadowOffset.x !== x) {
  12269. this._shadowOffset.x = x;
  12270. this._setUpdateTextureDirty();
  12271. }
  12272. },
  12273. _getShadowOffsetY: function () {
  12274. return this._shadowOffset._y;
  12275. },
  12276. _setShadowOffsetY: function (y) {
  12277. if (false === this._shadowEnabled)
  12278. this._shadowEnabled = true;
  12279. if (this._shadowOffset._y !== y) {
  12280. this._shadowOffset._y = y;
  12281. this._setUpdateTextureDirty();
  12282. }
  12283. },
  12284. _getShadowOffset: function () {
  12285. return cc.p(this._shadowOffset.x, this._shadowOffset.y);
  12286. },
  12287. _setShadowOffset: function (offset) {
  12288. if (false === this._shadowEnabled)
  12289. this._shadowEnabled = true;
  12290. if (this._shadowOffset.x !== offset.x || this._shadowOffset.y !== offset.y) {
  12291. this._shadowOffset.x = offset.x;
  12292. this._shadowOffset.y = offset.y;
  12293. this._setUpdateTextureDirty();
  12294. }
  12295. },
  12296. _getShadowOpacity: function () {
  12297. return this._shadowOpacity;
  12298. },
  12299. _setShadowOpacity: function (shadowOpacity) {
  12300. if (false === this._shadowEnabled)
  12301. this._shadowEnabled = true;
  12302. if (this._shadowOpacity !== shadowOpacity) {
  12303. this._shadowOpacity = shadowOpacity;
  12304. this._renderCmd._setColorsString();
  12305. this._setUpdateTextureDirty();
  12306. }
  12307. },
  12308. _getShadowBlur: function () {
  12309. return this._shadowBlur;
  12310. },
  12311. _setShadowBlur: function (shadowBlur) {
  12312. if (false === this._shadowEnabled)
  12313. this._shadowEnabled = true;
  12314. if (this._shadowBlur !== shadowBlur) {
  12315. this._shadowBlur = shadowBlur;
  12316. this._setUpdateTextureDirty();
  12317. }
  12318. },
  12319. disableShadow: function () {
  12320. if (this._shadowEnabled) {
  12321. this._shadowEnabled = false;
  12322. this._setUpdateTextureDirty();
  12323. }
  12324. },
  12325. enableStroke: function (strokeColor, strokeSize) {
  12326. if (this._strokeEnabled === false)
  12327. this._strokeEnabled = true;
  12328. var locStrokeColor = this._strokeColor;
  12329. if ((locStrokeColor.r !== strokeColor.r) || (locStrokeColor.g !== strokeColor.g) || (locStrokeColor.b !== strokeColor.b)) {
  12330. locStrokeColor.r = strokeColor.r;
  12331. locStrokeColor.g = strokeColor.g;
  12332. locStrokeColor.b = strokeColor.b;
  12333. this._renderCmd._setColorsString();
  12334. }
  12335. if (this._strokeSize !== strokeSize)
  12336. this._strokeSize = strokeSize || 0;
  12337. this._setUpdateTextureDirty();
  12338. },
  12339. _getStrokeStyle: function () {
  12340. return this._strokeColor;
  12341. },
  12342. _setStrokeStyle: function (strokeStyle) {
  12343. if (this._strokeEnabled === false)
  12344. this._strokeEnabled = true;
  12345. var locStrokeColor = this._strokeColor;
  12346. if ((locStrokeColor.r !== strokeStyle.r) || (locStrokeColor.g !== strokeStyle.g) || (locStrokeColor.b !== strokeStyle.b)) {
  12347. locStrokeColor.r = strokeStyle.r;
  12348. locStrokeColor.g = strokeStyle.g;
  12349. locStrokeColor.b = strokeStyle.b;
  12350. this._renderCmd._setColorsString();
  12351. this._setUpdateTextureDirty();
  12352. }
  12353. },
  12354. _getLineWidth: function () {
  12355. return this._strokeSize;
  12356. },
  12357. _setLineWidth: function (lineWidth) {
  12358. if (this._strokeEnabled === false)
  12359. this._strokeEnabled = true;
  12360. if (this._strokeSize !== lineWidth) {
  12361. this._strokeSize = lineWidth || 0;
  12362. this._setUpdateTextureDirty();
  12363. }
  12364. },
  12365. disableStroke: function () {
  12366. if (this._strokeEnabled) {
  12367. this._strokeEnabled = false;
  12368. this._setUpdateTextureDirty();
  12369. }
  12370. },
  12371. setFontFillColor: function (fillColor) {
  12372. var locTextFillColor = this._textFillColor;
  12373. if (locTextFillColor.r !== fillColor.r || locTextFillColor.g !== fillColor.g || locTextFillColor.b !== fillColor.b) {
  12374. locTextFillColor.r = fillColor.r;
  12375. locTextFillColor.g = fillColor.g;
  12376. locTextFillColor.b = fillColor.b;
  12377. this._renderCmd._setColorsString();
  12378. this._needUpdateTexture = true;
  12379. }
  12380. },
  12381. _getFillStyle: function () {
  12382. return this._textFillColor;
  12383. },
  12384. _updateWithTextDefinition: function (textDefinition, mustUpdateTexture) {
  12385. if (textDefinition.fontDimensions) {
  12386. this._dimensions.width = textDefinition.boundingWidth;
  12387. this._dimensions.height = textDefinition.boundingHeight;
  12388. } else {
  12389. this._dimensions.width = 0;
  12390. this._dimensions.height = 0;
  12391. }
  12392. this._hAlignment = textDefinition.textAlign;
  12393. this._vAlignment = textDefinition.verticalAlign;
  12394. this._fontName = textDefinition.fontName;
  12395. this._fontSize = textDefinition.fontSize || 12;
  12396. if(textDefinition.lineHeight)
  12397. this._lineHeight = textDefinition.lineHeight
  12398. else
  12399. this._lineHeight = this._fontSize;
  12400. this._renderCmd._setFontStyle(textDefinition);
  12401. if (textDefinition.shadowEnabled)
  12402. this.enableShadow(textDefinition.shadowOffsetX,
  12403. textDefinition.shadowOffsetY,
  12404. textDefinition.shadowOpacity,
  12405. textDefinition.shadowBlur);
  12406. if (textDefinition.strokeEnabled)
  12407. this.enableStroke(textDefinition.strokeStyle, textDefinition.lineWidth);
  12408. this.setFontFillColor(textDefinition.fillStyle);
  12409. if (mustUpdateTexture)
  12410. this._renderCmd._updateTexture();
  12411. var flags = cc.Node._dirtyFlags;
  12412. this._renderCmd.setDirtyFlag(flags.colorDirty|flags.opacityDirty|flags.textDirty);
  12413. },
  12414. _prepareTextDefinition: function (adjustForResolution) {
  12415. var texDef = new cc.FontDefinition();
  12416. if (adjustForResolution) {
  12417. texDef.fontSize = this._fontSize;
  12418. texDef.boundingWidth = cc.contentScaleFactor() * this._dimensions.width;
  12419. texDef.boundingHeight = cc.contentScaleFactor() * this._dimensions.height;
  12420. } else {
  12421. texDef.fontSize = this._fontSize;
  12422. texDef.boundingWidth = this._dimensions.width;
  12423. texDef.boundingHeight = this._dimensions.height;
  12424. }
  12425. texDef.fontName = this._fontName;
  12426. texDef.textAlign = this._hAlignment;
  12427. texDef.verticalAlign = this._vAlignment;
  12428. if (this._strokeEnabled) {
  12429. texDef.strokeEnabled = true;
  12430. var locStrokeColor = this._strokeColor;
  12431. texDef.strokeStyle = cc.color(locStrokeColor.r, locStrokeColor.g, locStrokeColor.b);
  12432. texDef.lineWidth = this._strokeSize;
  12433. } else
  12434. texDef.strokeEnabled = false;
  12435. if (this._shadowEnabled) {
  12436. texDef.shadowEnabled = true;
  12437. texDef.shadowBlur = this._shadowBlur;
  12438. texDef.shadowOpacity = this._shadowOpacity;
  12439. texDef.shadowOffsetX = (adjustForResolution ? cc.contentScaleFactor() : 1) * this._shadowOffset.x;
  12440. texDef.shadowOffsetY = (adjustForResolution ? cc.contentScaleFactor() : 1) * this._shadowOffset.y;
  12441. } else
  12442. texDef._shadowEnabled = false;
  12443. var locTextFillColor = this._textFillColor;
  12444. texDef.fillStyle = cc.color(locTextFillColor.r, locTextFillColor.g, locTextFillColor.b);
  12445. return texDef;
  12446. },
  12447. getScale: function () {
  12448. if (this._scaleX !== this._scaleY)
  12449. cc.log(cc._LogInfos.Node_getScale);
  12450. return this._scaleX * cc.view.getDevicePixelRatio();
  12451. },
  12452. setScale: function (scale, scaleY) {
  12453. this._scaleX = scale / cc.view.getDevicePixelRatio();
  12454. this._scaleY = ((scaleY || scaleY === 0) ? scaleY : scale) /
  12455. cc.view.getDevicePixelRatio();
  12456. this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
  12457. },
  12458. getScaleX: function () {
  12459. return this._scaleX * cc.view.getDevicePixelRatio();
  12460. },
  12461. setScaleX: function (newScaleX) {
  12462. this._scaleX = newScaleX / cc.view.getDevicePixelRatio();
  12463. this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
  12464. },
  12465. getScaleY: function () {
  12466. return this._scaleY * cc.view.getDevicePixelRatio();
  12467. },
  12468. setScaleY: function (newScaleY) {
  12469. this._scaleY = newScaleY / cc.view.getDevicePixelRatio();
  12470. this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
  12471. },
  12472. setString: function (text) {
  12473. text = String(text);
  12474. if (this._originalText !== text) {
  12475. this._originalText = text + "";
  12476. this._updateString();
  12477. this._setUpdateTextureDirty();
  12478. this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
  12479. }
  12480. },
  12481. _updateString: function () {
  12482. if ((!this._string || this._string === "") && this._string !== this._originalText)
  12483. cc.renderer.childrenOrderDirty = true;
  12484. this._string = this._originalText;
  12485. },
  12486. setHorizontalAlignment: function (alignment) {
  12487. if (alignment !== this._hAlignment) {
  12488. this._hAlignment = alignment;
  12489. this._setUpdateTextureDirty();
  12490. }
  12491. },
  12492. setVerticalAlignment: function (verticalAlignment) {
  12493. if (verticalAlignment !== this._vAlignment) {
  12494. this._vAlignment = verticalAlignment;
  12495. this._setUpdateTextureDirty();
  12496. }
  12497. },
  12498. setDimensions: function (dim, height) {
  12499. var width;
  12500. if (height === undefined) {
  12501. width = dim.width;
  12502. height = dim.height;
  12503. } else
  12504. width = dim;
  12505. if (width !== this._dimensions.width || height !== this._dimensions.height) {
  12506. this._dimensions.width = width;
  12507. this._dimensions.height = height;
  12508. this._updateString();
  12509. this._setUpdateTextureDirty();
  12510. }
  12511. },
  12512. _getBoundingWidth: function () {
  12513. return this._dimensions.width;
  12514. },
  12515. _setBoundingWidth: function (width) {
  12516. if (width !== this._dimensions.width) {
  12517. this._dimensions.width = width;
  12518. this._updateString();
  12519. this._setUpdateTextureDirty();
  12520. }
  12521. },
  12522. _getBoundingHeight: function () {
  12523. return this._dimensions.height;
  12524. },
  12525. _setBoundingHeight: function (height) {
  12526. if (height !== this._dimensions.height) {
  12527. this._dimensions.height = height;
  12528. this._updateString();
  12529. this._setUpdateTextureDirty();
  12530. }
  12531. },
  12532. setFontSize: function (fontSize) {
  12533. if (this._fontSize !== fontSize) {
  12534. this._fontSize = fontSize;
  12535. this._renderCmd._setFontStyle(this._fontName, this._fontSize, this._fontStyle, this._fontWeight);
  12536. this._setUpdateTextureDirty();
  12537. }
  12538. },
  12539. setFontName: function (fontName) {
  12540. if (this._fontName && this._fontName !== fontName) {
  12541. this._fontName = fontName;
  12542. this._renderCmd._setFontStyle(this._fontName, this._fontSize, this._fontStyle, this._fontWeight);
  12543. this._setUpdateTextureDirty();
  12544. }
  12545. },
  12546. _getFont: function () {
  12547. return this._renderCmd._getFontStyle();
  12548. },
  12549. _setFont: function (fontStyle) {
  12550. var res = cc.LabelTTF._fontStyleRE.exec(fontStyle);
  12551. if (res) {
  12552. this._fontSize = parseInt(res[1]);
  12553. this._fontName = res[2];
  12554. this._renderCmd._setFontStyle(this._fontName, this._fontSize, this._fontStyle, this._fontWeight);
  12555. this._setUpdateTextureDirty();
  12556. }
  12557. },
  12558. getContentSize: function () {
  12559. if (this._needUpdateTexture)
  12560. this._renderCmd._updateTTF();
  12561. return cc.size(this._contentSize);
  12562. },
  12563. _getWidth: function () {
  12564. if (this._needUpdateTexture)
  12565. this._renderCmd._updateTTF();
  12566. return this._contentSize.width;
  12567. },
  12568. _getHeight: function () {
  12569. if (this._needUpdateTexture)
  12570. this._renderCmd._updateTTF();
  12571. return this._contentSize.height;
  12572. },
  12573. setTextureRect: function (rect, rotated, untrimmedSize) {
  12574. cc.Sprite.prototype.setTextureRect.call(this, rect, rotated, untrimmedSize, false);
  12575. },
  12576. setDrawMode: function (onCacheMode) {
  12577. this._onCacheCanvasMode = onCacheMode;
  12578. },
  12579. _createRenderCmd: function () {
  12580. if (cc._renderType === cc.game.RENDER_TYPE_WEBGL)
  12581. return new cc.LabelTTF.WebGLRenderCmd(this);
  12582. else if (this._onCacheCanvasMode)
  12583. return new cc.LabelTTF.CacheCanvasRenderCmd(this);
  12584. else
  12585. return new cc.LabelTTF.CanvasRenderCmd(this);
  12586. },
  12587. _setFontStyle: function(fontStyle){
  12588. if (this._fontStyle !== fontStyle) {
  12589. this._fontStyle = fontStyle;
  12590. this._renderCmd._setFontStyle(this._fontName, this._fontSize, this._fontStyle, this._fontWeight);
  12591. this._setUpdateTextureDirty();
  12592. }
  12593. },
  12594. _getFontStyle: function(){
  12595. return this._fontStyle;
  12596. },
  12597. _setFontWeight: function(fontWeight){
  12598. if (this._fontWeight !== fontWeight) {
  12599. this._fontWeight = fontWeight;
  12600. this._renderCmd._setFontStyle(this._fontName, this._fontSize, this._fontStyle, this._fontWeight);
  12601. this._setUpdateTextureDirty();
  12602. }
  12603. },
  12604. _getFontWeight: function(){
  12605. return this._fontWeight;
  12606. }
  12607. });
  12608. cc.assert(cc.isFunction(cc._tmp.PrototypeLabelTTF), cc._LogInfos.MissingFile, "LabelTTFPropertyDefine.js");
  12609. cc._tmp.PrototypeLabelTTF();
  12610. delete cc._tmp.PrototypeLabelTTF;
  12611. cc.LabelTTF._fontStyleRE = /^(\d+)px\s+['"]?([\w\s\d]+)['"]?$/;
  12612. cc.LabelTTF.create = function (text, fontName, fontSize, dimensions, hAlignment, vAlignment) {
  12613. return new cc.LabelTTF(text, fontName, fontSize, dimensions, hAlignment, vAlignment);
  12614. };
  12615. cc.LabelTTF.createWithFontDefinition = cc.LabelTTF.create;
  12616. cc.LabelTTF.__labelHeightDiv = document.createElement("div");
  12617. cc.LabelTTF.__labelHeightDiv.style.fontFamily = "Arial";
  12618. cc.LabelTTF.__labelHeightDiv.style.position = "absolute";
  12619. cc.LabelTTF.__labelHeightDiv.style.left = "-100px";
  12620. cc.LabelTTF.__labelHeightDiv.style.top = "-100px";
  12621. cc.LabelTTF.__labelHeightDiv.style.lineHeight = "normal";
  12622. document.body ?
  12623. document.body.appendChild(cc.LabelTTF.__labelHeightDiv) :
  12624. window.addEventListener('load', function () {
  12625. this.removeEventListener('load', arguments.callee, false);
  12626. document.body.appendChild(cc.LabelTTF.__labelHeightDiv);
  12627. }, false);
  12628. cc.LabelTTF.__getFontHeightByDiv = function (fontName, fontSize) {
  12629. var clientHeight, labelDiv = cc.LabelTTF.__labelHeightDiv;
  12630. if(fontName instanceof cc.FontDefinition){
  12631. var fontDef = fontName;
  12632. clientHeight = cc.LabelTTF.__fontHeightCache[fontDef._getCanvasFontStr()];
  12633. if (clientHeight > 0) return clientHeight;
  12634. labelDiv.innerHTML = "ajghl~!";
  12635. labelDiv.style.fontFamily = fontDef.fontName;
  12636. labelDiv.style.fontSize = fontDef.fontSize + "px";
  12637. labelDiv.style.fontStyle = fontDef.fontStyle;
  12638. labelDiv.style.fontWeight = fontDef.fontWeight;
  12639. clientHeight = labelDiv.clientHeight;
  12640. cc.LabelTTF.__fontHeightCache[fontDef._getCanvasFontStr()] = clientHeight;
  12641. labelDiv.innerHTML = "";
  12642. }
  12643. else {
  12644. clientHeight = cc.LabelTTF.__fontHeightCache[fontName + "." + fontSize];
  12645. if (clientHeight > 0) return clientHeight;
  12646. labelDiv.innerHTML = "ajghl~!";
  12647. labelDiv.style.fontFamily = fontName;
  12648. labelDiv.style.fontSize = fontSize + "px";
  12649. clientHeight = labelDiv.clientHeight;
  12650. cc.LabelTTF.__fontHeightCache[fontName + "." + fontSize] = clientHeight;
  12651. labelDiv.innerHTML = "";
  12652. }
  12653. return clientHeight;
  12654. };
  12655. cc.LabelTTF.__fontHeightCache = {};
  12656. cc.LabelTTF._textAlign = ["left", "center", "right"];
  12657. cc.LabelTTF._textBaseline = ["top", "middle", "bottom"];
  12658. cc.LabelTTF.wrapInspection = true;
  12659. cc.LabelTTF._wordRex = /([a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]+|\S)/;
  12660. cc.LabelTTF._symbolRex = /^[!,.:;}\]%\?>、‘“》?。,!]/;
  12661. cc.LabelTTF._lastWordRex = /([a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]+|\S)$/;
  12662. cc.LabelTTF._lastEnglish = /[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]+$/;
  12663. cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/;
  12664. (function() {
  12665. cc.LabelTTF.RenderCmd = function () {
  12666. this._fontClientHeight = 18;
  12667. this._fontStyleStr = "";
  12668. this._shadowColorStr = "rgba(128, 128, 128, 0.5)";
  12669. this._strokeColorStr = "";
  12670. this._fillColorStr = "rgba(255,255,255,1)";
  12671. this._labelCanvas = null;
  12672. this._labelContext = null;
  12673. this._lineWidths = [];
  12674. this._strings = [];
  12675. this._isMultiLine = false;
  12676. this._status = [];
  12677. this._renderingIndex = 0;
  12678. this._texRect = cc.rect();
  12679. this._canUseDirtyRegion = true;
  12680. };
  12681. var proto = cc.LabelTTF.RenderCmd.prototype;
  12682. proto.constructor = cc.LabelTTF.RenderCmd;
  12683. proto._setFontStyle = function (fontNameOrFontDef, fontSize, fontStyle, fontWeight) {
  12684. if(fontNameOrFontDef instanceof cc.FontDefinition){
  12685. this._fontStyleStr = fontNameOrFontDef._getCanvasFontStr();
  12686. this._fontClientHeight = cc.LabelTTF.__getFontHeightByDiv(fontNameOrFontDef);
  12687. }else {
  12688. var deviceFontSize = fontSize * cc.view.getDevicePixelRatio();
  12689. this._fontStyleStr = fontStyle + " " + fontWeight + " " + deviceFontSize + "px '" + fontNameOrFontDef + "'";
  12690. this._fontClientHeight = cc.LabelTTF.__getFontHeightByDiv(fontNameOrFontDef, fontSize);
  12691. }
  12692. };
  12693. proto._getFontStyle = function () {
  12694. return this._fontStyleStr;
  12695. };
  12696. proto._getFontClientHeight = function () {
  12697. return this._fontClientHeight;
  12698. };
  12699. proto._updateColor = function(){
  12700. this._setColorsString();
  12701. this._updateTexture();
  12702. };
  12703. proto._setColorsString = function () {
  12704. var locDisplayColor = this._displayedColor, node = this._node,
  12705. locShadowColor = node._shadowColor || this._displayedColor;
  12706. var locStrokeColor = node._strokeColor, locFontFillColor = node._textFillColor;
  12707. var dr = locDisplayColor.r / 255, dg = locDisplayColor.g / 255, db = locDisplayColor.b / 255;
  12708. this._shadowColorStr = "rgba(" + (0 | (dr * locShadowColor.r)) + "," + (0 | ( dg * locShadowColor.g)) + ","
  12709. + (0 | (db * locShadowColor.b)) + "," + node._shadowOpacity + ")";
  12710. this._fillColorStr = "rgba(" + (0 | (dr * locFontFillColor.r)) + "," + (0 | (dg * locFontFillColor.g)) + ","
  12711. + (0 | (db * locFontFillColor.b)) + ", 1)";
  12712. this._strokeColorStr = "rgba(" + (0 | (dr * locStrokeColor.r)) + "," + (0 | (dg * locStrokeColor.g)) + ","
  12713. + (0 | (db * locStrokeColor.b)) + ", 1)";
  12714. };
  12715. var localBB = new cc.Rect();
  12716. proto.getLocalBB = function () {
  12717. var node = this._node;
  12718. localBB.x = localBB.y = 0;
  12719. var pixelRatio = cc.view.getDevicePixelRatio();
  12720. localBB.width = node._getWidth() * pixelRatio;
  12721. localBB.height = node._getHeight() * pixelRatio;
  12722. return localBB;
  12723. };
  12724. proto._updateTTF = function () {
  12725. var node = this._node;
  12726. var pixelRatio = cc.view.getDevicePixelRatio();
  12727. var locDimensionsWidth = node._dimensions.width * pixelRatio, i, strLength;
  12728. var locLineWidth = this._lineWidths;
  12729. locLineWidth.length = 0;
  12730. this._isMultiLine = false;
  12731. this._measureConfig();
  12732. if (locDimensionsWidth !== 0) {
  12733. this._strings = node._string.split('\n');
  12734. for (i = 0; i < this._strings.length; i++) {
  12735. this._checkWarp(this._strings, i, locDimensionsWidth);
  12736. }
  12737. } else {
  12738. this._strings = node._string.split('\n');
  12739. for (i = 0, strLength = this._strings.length; i < strLength; i++) {
  12740. locLineWidth.push(this._measure(this._strings[i]));
  12741. }
  12742. }
  12743. if (this._strings.length > 1)
  12744. this._isMultiLine = true;
  12745. var locSize, locStrokeShadowOffsetX = 0, locStrokeShadowOffsetY = 0;
  12746. if (node._strokeEnabled)
  12747. locStrokeShadowOffsetX = locStrokeShadowOffsetY = node._strokeSize * 2;
  12748. if (node._shadowEnabled) {
  12749. var locOffsetSize = node._shadowOffset;
  12750. locStrokeShadowOffsetX += Math.abs(locOffsetSize.x) * 2;
  12751. locStrokeShadowOffsetY += Math.abs(locOffsetSize.y) * 2;
  12752. }
  12753. if (locDimensionsWidth === 0) {
  12754. if (this._isMultiLine)
  12755. locSize = cc.size(
  12756. Math.ceil(Math.max.apply(Math, locLineWidth) + locStrokeShadowOffsetX),
  12757. Math.ceil((this._fontClientHeight * pixelRatio * this._strings.length) + locStrokeShadowOffsetY));
  12758. else
  12759. locSize = cc.size(
  12760. Math.ceil(this._measure(node._string) + locStrokeShadowOffsetX),
  12761. Math.ceil(this._fontClientHeight * pixelRatio + locStrokeShadowOffsetY));
  12762. } else {
  12763. if (node._dimensions.height === 0) {
  12764. if (this._isMultiLine)
  12765. locSize = cc.size(
  12766. Math.ceil(locDimensionsWidth + locStrokeShadowOffsetX),
  12767. Math.ceil((node.getLineHeight() * pixelRatio * this._strings.length) + locStrokeShadowOffsetY));
  12768. else
  12769. locSize = cc.size(
  12770. Math.ceil(locDimensionsWidth + locStrokeShadowOffsetX),
  12771. Math.ceil(node.getLineHeight() * pixelRatio + locStrokeShadowOffsetY));
  12772. } else {
  12773. locSize = cc.size(
  12774. Math.ceil(locDimensionsWidth + locStrokeShadowOffsetX),
  12775. Math.ceil(node._dimensions.height * pixelRatio + locStrokeShadowOffsetY));
  12776. }
  12777. }
  12778. if (node._getFontStyle() !== "normal") {
  12779. locSize.width = Math.ceil(locSize.width + node._fontSize * 0.3);
  12780. }
  12781. if (this._strings.length === 0) {
  12782. this._texRect.width = 1;
  12783. this._texRect.height = locSize.height || 1;
  12784. }
  12785. else {
  12786. this._texRect.width = locSize.width;
  12787. this._texRect.height = locSize.height;
  12788. }
  12789. var nodeW = locSize.width / pixelRatio, nodeH = locSize.height / pixelRatio;
  12790. node.setContentSize(nodeW, nodeH);
  12791. node._strokeShadowOffsetX = locStrokeShadowOffsetX;
  12792. node._strokeShadowOffsetY = locStrokeShadowOffsetY;
  12793. var locAP = node._anchorPoint;
  12794. this._anchorPointInPoints.x = (locStrokeShadowOffsetX * 0.5) + ((locSize.width - locStrokeShadowOffsetX) * locAP.x);
  12795. this._anchorPointInPoints.y = (locStrokeShadowOffsetY * 0.5) + ((locSize.height - locStrokeShadowOffsetY) * locAP.y);
  12796. };
  12797. proto._saveStatus = function () {
  12798. var node = this._node;
  12799. var scale = cc.view.getDevicePixelRatio();
  12800. var locStrokeShadowOffsetX = node._strokeShadowOffsetX, locStrokeShadowOffsetY = node._strokeShadowOffsetY;
  12801. var locContentSizeHeight = node._contentSize.height * scale - locStrokeShadowOffsetY, locVAlignment = node._vAlignment,
  12802. locHAlignment = node._hAlignment;
  12803. var dx = locStrokeShadowOffsetX * 0.5,
  12804. dy = locContentSizeHeight + locStrokeShadowOffsetY * 0.5;
  12805. var xOffset = 0, yOffset = 0, OffsetYArray = [];
  12806. var locContentWidth = node._contentSize.width * scale - locStrokeShadowOffsetX;
  12807. var lineHeight = node.getLineHeight() * scale;
  12808. var transformTop = (lineHeight - this._fontClientHeight * scale) / 2;
  12809. if (locHAlignment === cc.TEXT_ALIGNMENT_RIGHT)
  12810. xOffset += locContentWidth;
  12811. else if (locHAlignment === cc.TEXT_ALIGNMENT_CENTER)
  12812. xOffset += locContentWidth / 2;
  12813. else
  12814. xOffset += 0;
  12815. if (this._isMultiLine) {
  12816. var locStrLen = this._strings.length;
  12817. if (locVAlignment === cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM)
  12818. yOffset = lineHeight - transformTop * 2 + locContentSizeHeight - lineHeight * locStrLen;
  12819. else if (locVAlignment === cc.VERTICAL_TEXT_ALIGNMENT_CENTER)
  12820. yOffset = (lineHeight - transformTop * 2) / 2 + (locContentSizeHeight - lineHeight * locStrLen) / 2;
  12821. for (var i = 0; i < locStrLen; i++) {
  12822. var tmpOffsetY = -locContentSizeHeight + (lineHeight * i + transformTop) + yOffset;
  12823. OffsetYArray.push(tmpOffsetY);
  12824. }
  12825. } else {
  12826. if (locVAlignment === cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM) {
  12827. } else if (locVAlignment === cc.VERTICAL_TEXT_ALIGNMENT_TOP) {
  12828. yOffset -= locContentSizeHeight;
  12829. } else {
  12830. yOffset -= locContentSizeHeight * 0.5;
  12831. }
  12832. OffsetYArray.push(yOffset);
  12833. }
  12834. var tmpStatus = {
  12835. contextTransform:cc.p(dx,dy),
  12836. xOffset:xOffset,
  12837. OffsetYArray:OffsetYArray
  12838. };
  12839. this._status.push(tmpStatus);
  12840. };
  12841. proto._drawTTFInCanvas = function (context) {
  12842. if (!context)
  12843. return;
  12844. var locStatus = this._status.pop();
  12845. context.setTransform(1, 0, 0, 1, locStatus.contextTransform.x, locStatus.contextTransform.y);
  12846. var xOffset = locStatus.xOffset;
  12847. var yOffsetArray = locStatus.OffsetYArray;
  12848. this.drawLabels(context, xOffset, yOffsetArray);
  12849. };
  12850. proto._checkWarp = function (strArr, i, maxWidth) {
  12851. var text = strArr[i];
  12852. var allWidth = this._measure(text);
  12853. if (allWidth > maxWidth && text.length > 1) {
  12854. var fuzzyLen = text.length * ( maxWidth / allWidth ) | 0;
  12855. var tmpText = text.substr(fuzzyLen);
  12856. var width = allWidth - this._measure(tmpText);
  12857. var sLine;
  12858. var pushNum = 0;
  12859. var checkWhile = 0;
  12860. while (width > maxWidth && checkWhile++ < 100) {
  12861. fuzzyLen *= maxWidth / width;
  12862. fuzzyLen = fuzzyLen | 0;
  12863. tmpText = text.substr(fuzzyLen);
  12864. width = allWidth - this._measure(tmpText);
  12865. }
  12866. checkWhile = 0;
  12867. while (width < maxWidth && checkWhile++ < 100) {
  12868. if (tmpText) {
  12869. var exec = cc.LabelTTF._wordRex.exec(tmpText);
  12870. pushNum = exec ? exec[0].length : 1;
  12871. sLine = tmpText;
  12872. }
  12873. fuzzyLen = fuzzyLen + pushNum;
  12874. tmpText = text.substr(fuzzyLen);
  12875. width = allWidth - this._measure(tmpText);
  12876. }
  12877. fuzzyLen -= pushNum;
  12878. if (fuzzyLen === 0) {
  12879. fuzzyLen = 1;
  12880. sLine = sLine.substr(1);
  12881. }
  12882. var sText = text.substr(0, fuzzyLen), result;
  12883. if (cc.LabelTTF.wrapInspection) {
  12884. if (cc.LabelTTF._symbolRex.test(sLine || tmpText)) {
  12885. result = cc.LabelTTF._lastWordRex.exec(sText);
  12886. fuzzyLen -= result ? result[0].length : 0;
  12887. if (fuzzyLen === 0) fuzzyLen = 1;
  12888. sLine = text.substr(fuzzyLen);
  12889. sText = text.substr(0, fuzzyLen);
  12890. }
  12891. }
  12892. if (cc.LabelTTF._firsrEnglish.test(sLine)) {
  12893. result = cc.LabelTTF._lastEnglish.exec(sText);
  12894. if (result && sText !== result[0]) {
  12895. fuzzyLen -= result[0].length;
  12896. sLine = text.substr(fuzzyLen);
  12897. sText = text.substr(0, fuzzyLen);
  12898. }
  12899. }
  12900. strArr[i] = sLine || tmpText;
  12901. strArr.splice(i, 0, sText);
  12902. }
  12903. };
  12904. proto.updateStatus = function () {
  12905. var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag;
  12906. if (locFlag & flags.textDirty)
  12907. this._updateTexture();
  12908. cc.Node.RenderCmd.prototype.updateStatus.call(this);
  12909. if (this._dirtyFlag & flags.transformDirty){
  12910. this.transform(this.getParentRenderCmd(), true);
  12911. this._dirtyFlag = this._dirtyFlag & cc.Node._dirtyFlags.transformDirty ^ this._dirtyFlag;
  12912. }
  12913. };
  12914. proto._syncStatus = function (parentCmd) {
  12915. var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag;
  12916. if (locFlag & flags.textDirty)
  12917. this._updateTexture();
  12918. cc.Node.RenderCmd.prototype._syncStatus.call(this, parentCmd);
  12919. if (cc._renderType === cc.game.RENDER_TYPE_WEBGL || locFlag & flags.transformDirty)
  12920. this.transform(parentCmd);
  12921. };
  12922. proto.drawLabels = function (context, xOffset, yOffsetArray) {
  12923. var node = this._node;
  12924. if (node._shadowEnabled) {
  12925. var locShadowOffset = node._shadowOffset;
  12926. context.shadowColor = this._shadowColorStr;
  12927. context.shadowOffsetX = locShadowOffset.x;
  12928. context.shadowOffsetY = -locShadowOffset.y;
  12929. context.shadowBlur = node._shadowBlur;
  12930. }
  12931. var locHAlignment = node._hAlignment,
  12932. locVAlignment = node._vAlignment,
  12933. locStrokeSize = node._strokeSize;
  12934. if (context.font !== this._fontStyleStr)
  12935. context.font = this._fontStyleStr;
  12936. context.fillStyle = this._fillColorStr;
  12937. var locStrokeEnabled = node._strokeEnabled;
  12938. if (locStrokeEnabled) {
  12939. context.lineWidth = locStrokeSize * 2;
  12940. context.strokeStyle = this._strokeColorStr;
  12941. }
  12942. context.textBaseline = cc.LabelTTF._textBaseline[locVAlignment];
  12943. context.textAlign = cc.LabelTTF._textAlign[locHAlignment];
  12944. var locStrLen = this._strings.length;
  12945. for (var i = 0; i < locStrLen; i++) {
  12946. var line = this._strings[i];
  12947. if (locStrokeEnabled)
  12948. context.strokeText(line, xOffset, yOffsetArray[i]);
  12949. context.fillText(line, xOffset, yOffsetArray[i]);
  12950. }
  12951. cc.g_NumberOfDraws++;
  12952. };
  12953. })();
  12954. (function(){
  12955. cc.LabelTTF.CacheRenderCmd = function (renderable) {
  12956. cc.LabelTTF.RenderCmd.call(this,renderable);
  12957. var locCanvas = this._labelCanvas = document.createElement("canvas");
  12958. locCanvas.width = 1;
  12959. locCanvas.height = 1;
  12960. this._labelContext = locCanvas.getContext("2d");
  12961. this._texRect = cc.rect();
  12962. };
  12963. cc.LabelTTF.CacheRenderCmd.prototype = Object.create( cc.LabelTTF.RenderCmd.prototype);
  12964. cc.inject(cc.LabelTTF.RenderCmd.prototype, cc.LabelTTF.CacheRenderCmd.prototype);
  12965. var proto = cc.LabelTTF.CacheRenderCmd.prototype;
  12966. proto.constructor = cc.LabelTTF.CacheRenderCmd;
  12967. proto._updateTexture = function () {
  12968. this._dirtyFlag = this._dirtyFlag & cc.Node._dirtyFlags.textDirty ^ this._dirtyFlag;
  12969. var node = this._node;
  12970. this._updateTTF();
  12971. var width = this._texRect.width, height = this._texRect.height;
  12972. var locContext = this._labelContext, locLabelCanvas = this._labelCanvas;
  12973. if(!node._texture){
  12974. var labelTexture = new cc.Texture2D();
  12975. labelTexture.initWithElement(this._labelCanvas);
  12976. node.setTexture(labelTexture);
  12977. }
  12978. if (node._string.length === 0) {
  12979. locLabelCanvas.width = width;
  12980. locLabelCanvas.height = height;
  12981. node._texture && node._texture.handleLoadedTexture();
  12982. node.setTextureRect(this._texRect);
  12983. return true;
  12984. }
  12985. locContext.font = this._fontStyleStr;
  12986. var flag = locLabelCanvas.width === width && locLabelCanvas.height === height;
  12987. locLabelCanvas.width = this._texRect.width;
  12988. locLabelCanvas.height = this._texRect.height;
  12989. if (flag) locContext.clearRect(0, 0, width, height);
  12990. this._saveStatus();
  12991. this._drawTTFInCanvas(locContext);
  12992. node._texture && node._texture.handleLoadedTexture();
  12993. node.setTextureRect(this._texRect);
  12994. return true;
  12995. };
  12996. proto._measureConfig = function () {
  12997. this._labelContext.font = this._fontStyleStr;
  12998. };
  12999. proto._measure = function (text) {
  13000. return this._labelContext.measureText(text).width;
  13001. };
  13002. })();
  13003. (function(){
  13004. cc.LabelTTF.CacheCanvasRenderCmd = function (renderable) {
  13005. cc.Sprite.CanvasRenderCmd.call(this, renderable);
  13006. cc.LabelTTF.CacheRenderCmd.call(this);
  13007. };
  13008. var proto = cc.LabelTTF.CacheCanvasRenderCmd.prototype = Object.create(cc.Sprite.CanvasRenderCmd.prototype);
  13009. cc.inject(cc.LabelTTF.CacheRenderCmd.prototype, proto);
  13010. proto.constructor = cc.LabelTTF.CacheCanvasRenderCmd;
  13011. })();
  13012. (function(){
  13013. cc.LabelTTF.CanvasRenderCmd = function (renderable) {
  13014. cc.Sprite.CanvasRenderCmd.call(this, renderable);
  13015. cc.LabelTTF.RenderCmd.call(this);
  13016. };
  13017. cc.LabelTTF.CanvasRenderCmd.prototype = Object.create(cc.Sprite.CanvasRenderCmd.prototype);
  13018. cc.inject(cc.LabelTTF.RenderCmd.prototype, cc.LabelTTF.CanvasRenderCmd.prototype);
  13019. var proto = cc.LabelTTF.CanvasRenderCmd.prototype;
  13020. proto.constructor = cc.LabelTTF.CanvasRenderCmd;
  13021. proto._measureConfig = function () {};
  13022. proto._measure = function (text) {
  13023. var context = cc._renderContext.getContext();
  13024. context.font = this._fontStyleStr;
  13025. return context.measureText(text).width;
  13026. };
  13027. proto._updateTexture = function () {
  13028. this._dirtyFlag = this._dirtyFlag & cc.Node._dirtyFlags.textDirty ^ this._dirtyFlag;
  13029. var node = this._node;
  13030. var scale = cc.view.getDevicePixelRatio();
  13031. this._updateTTF();
  13032. if (node._string.length === 0) {
  13033. node.setTextureRect(this._texRect);
  13034. return true;
  13035. }
  13036. this._saveStatus();
  13037. node.setTextureRect(this._texRect);
  13038. return true;
  13039. };
  13040. proto.rendering = function(ctx) {
  13041. var scaleX = cc.view.getScaleX(),
  13042. scaleY = cc.view.getScaleY();
  13043. var wrapper = ctx || cc._renderContext, context = wrapper.getContext();
  13044. if (!context)
  13045. return;
  13046. var node = this._node;
  13047. wrapper.computeRealOffsetY();
  13048. if(this._status.length <= 0)
  13049. return;
  13050. var locIndex = (this._renderingIndex >= this._status.length)? this._renderingIndex-this._status.length:this._renderingIndex;
  13051. var status = this._status[locIndex];
  13052. this._renderingIndex = locIndex+1;
  13053. var locHeight = node._rect.height,
  13054. locX = node._offsetPosition.x,
  13055. locY = -node._offsetPosition.y - locHeight;
  13056. var alpha = (this._displayedOpacity / 255);
  13057. wrapper.setTransform(this._worldTransform, scaleX, scaleY);
  13058. wrapper.setCompositeOperation(this._blendFuncStr);
  13059. wrapper.setGlobalAlpha(alpha);
  13060. wrapper.save();
  13061. if (node._flippedX) {
  13062. locX = -locX - node._rect.width;
  13063. context.scale(-1, 1);
  13064. }
  13065. if (node._flippedY) {
  13066. locY = node._offsetPosition.y;
  13067. context.scale(1, -1);
  13068. }
  13069. var xOffset = status.xOffset + status.contextTransform.x + locX * scaleX;
  13070. var yOffsetArray = [];
  13071. var locStrLen = this._strings.length;
  13072. for (var i = 0; i < locStrLen; i++)
  13073. yOffsetArray.push(status.OffsetYArray[i] + status.contextTransform.y + locY * scaleY);
  13074. this.drawLabels(context, xOffset, yOffsetArray);
  13075. wrapper.restore();
  13076. };
  13077. })();
  13078. var cc = cc || {};
  13079. cc._tmp = cc._tmp || {};
  13080. cc.associateWithNative = function (jsObj, superclass) {
  13081. };
  13082. cc.KEY = {
  13083. none:0,
  13084. back:6,
  13085. menu:18,
  13086. backspace:8,
  13087. tab:9,
  13088. enter:13,
  13089. shift:16,
  13090. ctrl:17,
  13091. alt:18,
  13092. pause:19,
  13093. capslock:20,
  13094. escape:27,
  13095. space:32,
  13096. pageup:33,
  13097. pagedown:34,
  13098. end:35,
  13099. home:36,
  13100. left:37,
  13101. up:38,
  13102. right:39,
  13103. down:40,
  13104. select:41,
  13105. insert:45,
  13106. Delete:46,
  13107. 0:48,
  13108. 1:49,
  13109. 2:50,
  13110. 3:51,
  13111. 4:52,
  13112. 5:53,
  13113. 6:54,
  13114. 7:55,
  13115. 8:56,
  13116. 9:57,
  13117. a:65,
  13118. b:66,
  13119. c:67,
  13120. d:68,
  13121. e:69,
  13122. f:70,
  13123. g:71,
  13124. h:72,
  13125. i:73,
  13126. j:74,
  13127. k:75,
  13128. l:76,
  13129. m:77,
  13130. n:78,
  13131. o:79,
  13132. p:80,
  13133. q:81,
  13134. r:82,
  13135. s:83,
  13136. t:84,
  13137. u:85,
  13138. v:86,
  13139. w:87,
  13140. x:88,
  13141. y:89,
  13142. z:90,
  13143. num0:96,
  13144. num1:97,
  13145. num2:98,
  13146. num3:99,
  13147. num4:100,
  13148. num5:101,
  13149. num6:102,
  13150. num7:103,
  13151. num8:104,
  13152. num9:105,
  13153. '*':106,
  13154. '+':107,
  13155. '-':109,
  13156. 'numdel':110,
  13157. '/':111,
  13158. f1:112,
  13159. f2:113,
  13160. f3:114,
  13161. f4:115,
  13162. f5:116,
  13163. f6:117,
  13164. f7:118,
  13165. f8:119,
  13166. f9:120,
  13167. f10:121,
  13168. f11:122,
  13169. f12:123,
  13170. numlock:144,
  13171. scrolllock:145,
  13172. ';':186,
  13173. semicolon:186,
  13174. equal:187,
  13175. '=':187,
  13176. ',':188,
  13177. comma:188,
  13178. dash:189,
  13179. '.':190,
  13180. period:190,
  13181. forwardslash:191,
  13182. grave:192,
  13183. '[':219,
  13184. openbracket:219,
  13185. backslash:220,
  13186. ']':221,
  13187. closebracket:221,
  13188. quote:222,
  13189. dpadLeft:1000,
  13190. dpadRight:1001,
  13191. dpadUp:1003,
  13192. dpadDown:1004,
  13193. dpadCenter:1005
  13194. };
  13195. cc.FMT_JPG = 0;
  13196. cc.FMT_PNG = 1;
  13197. cc.FMT_TIFF = 2;
  13198. cc.FMT_RAWDATA = 3;
  13199. cc.FMT_WEBP = 4;
  13200. cc.FMT_UNKNOWN = 5;
  13201. cc.getImageFormatByData = function (imgData) {
  13202. if (imgData.length > 8 && imgData[0] === 0x89
  13203. && imgData[1] === 0x50
  13204. && imgData[2] === 0x4E
  13205. && imgData[3] === 0x47
  13206. && imgData[4] === 0x0D
  13207. && imgData[5] === 0x0A
  13208. && imgData[6] === 0x1A
  13209. && imgData[7] === 0x0A) {
  13210. return cc.FMT_PNG;
  13211. }
  13212. if (imgData.length > 2 && ((imgData[0] === 0x49 && imgData[1] === 0x49)
  13213. || (imgData[0] === 0x4d && imgData[1] === 0x4d)
  13214. || (imgData[0] === 0xff && imgData[1] === 0xd8))) {
  13215. return cc.FMT_TIFF;
  13216. }
  13217. return cc.FMT_UNKNOWN;
  13218. };
  13219. cc.inherits = function (childCtor, parentCtor) {
  13220. function tempCtor() {}
  13221. tempCtor.prototype = parentCtor.prototype;
  13222. childCtor.superClass_ = parentCtor.prototype;
  13223. childCtor.prototype = new tempCtor();
  13224. childCtor.prototype.constructor = childCtor;
  13225. };
  13226. cc.base = function(me, opt_methodName, var_args) {
  13227. var caller = arguments.callee.caller;
  13228. if (caller.superClass_) {
  13229. ret = caller.superClass_.constructor.apply( me, Array.prototype.slice.call(arguments, 1));
  13230. return ret;
  13231. }
  13232. var args = Array.prototype.slice.call(arguments, 2);
  13233. var foundCaller = false;
  13234. for (var ctor = me.constructor; ctor; ctor = ctor.superClass_ && ctor.superClass_.constructor) {
  13235. if (ctor.prototype[opt_methodName] === caller) {
  13236. foundCaller = true;
  13237. } else if (foundCaller) {
  13238. return ctor.prototype[opt_methodName].apply(me, args);
  13239. }
  13240. }
  13241. if (me[opt_methodName] === caller) {
  13242. return me.constructor.prototype[opt_methodName].apply(me, args);
  13243. } else {
  13244. throw Error(
  13245. 'cc.base called from a method of one name ' +
  13246. 'to a method of a different name');
  13247. }
  13248. };
  13249. var GlobalVertexBuffer = (function () {
  13250. var VERTICES_SIZE = 888;
  13251. var GlobalVertexBuffer = function (gl) {
  13252. this.gl = gl;
  13253. this.vertexBuffer = gl.createBuffer();
  13254. this.size = VERTICES_SIZE;
  13255. this.byteLength = VERTICES_SIZE * 4 * cc.V3F_C4B_T2F_Quad.BYTES_PER_ELEMENT;
  13256. this.data = new ArrayBuffer(this.byteLength);
  13257. this.dataArray = new Float32Array(this.data);
  13258. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  13259. gl.bufferData(gl.ARRAY_BUFFER, this.dataArray, gl.DYNAMIC_DRAW);
  13260. this._dirty = false;
  13261. this._spaces = {
  13262. 0: this.byteLength
  13263. };
  13264. };
  13265. GlobalVertexBuffer.prototype = {
  13266. constructor: GlobalVertexBuffer,
  13267. allocBuffer: function (offset, size) {
  13268. var space = this._spaces[offset];
  13269. if (space && space >= size) {
  13270. delete this._spaces[offset];
  13271. if (space > size) {
  13272. var newOffset = offset + size;
  13273. this._spaces[newOffset] = space - size;
  13274. }
  13275. return true;
  13276. }
  13277. else {
  13278. return false;
  13279. }
  13280. },
  13281. requestBuffer: function (size) {
  13282. var key, offset, available;
  13283. for (key in this._spaces) {
  13284. offset = parseInt(key);
  13285. available = this._spaces[key];
  13286. if (available >= size && this.allocBuffer(offset, size)) {
  13287. return {
  13288. buffer: this,
  13289. offset: offset,
  13290. size: size
  13291. };
  13292. }
  13293. }
  13294. return null;
  13295. },
  13296. freeBuffer: function (offset, size) {
  13297. var spaces = this._spaces;
  13298. var i, key, end;
  13299. for (key in spaces) {
  13300. i = parseInt(key);
  13301. if (i > offset) {
  13302. break;
  13303. }
  13304. if (i + spaces[key] >= offset) {
  13305. size = size + offset - i;
  13306. offset = i;
  13307. break;
  13308. }
  13309. }
  13310. end = offset + size;
  13311. if (this._spaces[end]) {
  13312. size += this._spaces[end];
  13313. delete this._spaces[end];
  13314. }
  13315. this._spaces[offset] = size;
  13316. },
  13317. setDirty: function () {
  13318. this._dirty = true;
  13319. },
  13320. update: function () {
  13321. if (this._dirty) {
  13322. this.gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  13323. this.gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.dataArray);
  13324. this._dirty = false;
  13325. }
  13326. },
  13327. destroy: function () {
  13328. this.gl.deleteBuffer(this.vertexBuffer);
  13329. this.data = null;
  13330. this.positions = null;
  13331. this.colors = null;
  13332. this.texCoords = null;
  13333. this.vertexBuffer = null;
  13334. }
  13335. };
  13336. return GlobalVertexBuffer;
  13337. })();
  13338. cc.rendererCanvas = {
  13339. childrenOrderDirty: true,
  13340. assignedZ: 0,
  13341. assignedZStep: 1 / 10000,
  13342. _transformNodePool: [],
  13343. _renderCmds: [],
  13344. _isCacheToCanvasOn: false,
  13345. _cacheToCanvasCmds: {},
  13346. _cacheInstanceIds: [],
  13347. _currentID: 0,
  13348. _clearColor: cc.color(),
  13349. _clearFillStyle: "rgb(0, 0, 0)",
  13350. _dirtyRegion: null,
  13351. _allNeedDraw: true,
  13352. _enableDirtyRegion: false,
  13353. _debugDirtyRegion: false,
  13354. _canUseDirtyRegion: false,
  13355. _dirtyRegionCountThreshold: 10,
  13356. getRenderCmd: function (renderableObject) {
  13357. return renderableObject._createRenderCmd();
  13358. },
  13359. enableDirtyRegion: function (enabled) {
  13360. this._enableDirtyRegion = enabled;
  13361. },
  13362. isDirtyRegionEnabled: function () {
  13363. return this._enableDirtyRegion;
  13364. },
  13365. setDirtyRegionCountThreshold: function(threshold) {
  13366. this._dirtyRegionCountThreshold = threshold;
  13367. },
  13368. _collectDirtyRegion: function () {
  13369. var locCmds = this._renderCmds, i, len;
  13370. var dirtyRegion = this._dirtyRegion;
  13371. var dirtryRegionCount = 0;
  13372. var result = true;
  13373. var localStatus = cc.Node.CanvasRenderCmd.RegionStatus;
  13374. for (i = 0, len = locCmds.length; i < len; i++) {
  13375. var cmd = locCmds[i];
  13376. var regionFlag = cmd._regionFlag;
  13377. var oldRegion = cmd._oldRegion;
  13378. var currentRegion = cmd._currentRegion;
  13379. if (regionFlag > localStatus.NotDirty) {
  13380. ++dirtryRegionCount;
  13381. if(dirtryRegionCount > this._dirtyRegionCountThreshold)
  13382. result = false;
  13383. if(result) {
  13384. (!currentRegion.isEmpty()) && dirtyRegion.addRegion(currentRegion);
  13385. if (cmd._regionFlag > localStatus.Dirty) {
  13386. (!oldRegion.isEmpty()) && dirtyRegion.addRegion(oldRegion);
  13387. }
  13388. }
  13389. cmd._regionFlag = localStatus.NotDirty;
  13390. }
  13391. }
  13392. return result;
  13393. },
  13394. _beginDrawDirtyRegion: function (ctxWrapper) {
  13395. var ctx = ctxWrapper.getContext();
  13396. var dirtyList = this._dirtyRegion.getDirtyRegions();
  13397. ctx.save();
  13398. var scaleX = ctxWrapper._scaleX;
  13399. var scaleY = ctxWrapper._scaleY;
  13400. ctxWrapper.setTransform({a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0}, scaleX, scaleY);
  13401. ctx.beginPath();
  13402. for (var index = 0, count = dirtyList.length; index < count; ++index) {
  13403. var region = dirtyList[index];
  13404. ctx.rect(region._minX , -region._maxY , region._width , region._height );
  13405. }
  13406. ctx.clip();
  13407. },
  13408. _endDrawDirtyRegion: function (ctx) {
  13409. ctx.restore();
  13410. },
  13411. _debugDrawDirtyRegion: function (ctxWrapper) {
  13412. if (!this._debugDirtyRegion) return;
  13413. var ctx = ctxWrapper.getContext();
  13414. var dirtyList = this._dirtyRegion.getDirtyRegions();
  13415. var scaleX = ctxWrapper._scaleX;
  13416. var scaleY = ctxWrapper._scaleY;
  13417. ctxWrapper.setTransform({a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0}, scaleX, scaleY);
  13418. ctx.beginPath();
  13419. for (var index = 0, count = dirtyList.length; index < count; ++index) {
  13420. var region = dirtyList[index];
  13421. ctx.rect(region._minX, -region._maxY , region._width , region._height );
  13422. }
  13423. var oldstyle = ctx.fillStyle;
  13424. ctx.fillStyle = 'green';
  13425. ctx.fill();
  13426. ctx.fillStyle = oldstyle;
  13427. },
  13428. rendering: function (ctxWrapper) {
  13429. var dirtyRegion = this._dirtyRegion = this._dirtyRegion || new cc.DirtyRegion();
  13430. var viewport = cc._canvas;
  13431. var wrapper = ctxWrapper || cc._renderContext;
  13432. var ctx = wrapper.getContext();
  13433. var scaleX = cc.view.getScaleX(),
  13434. scaleY = cc.view.getScaleY();
  13435. wrapper.setViewScale(scaleX, scaleY);
  13436. wrapper.computeRealOffsetY();
  13437. var dirtyList = this._dirtyRegion.getDirtyRegions();
  13438. var locCmds = this._renderCmds, i, len;
  13439. var allNeedDraw = this._allNeedDraw || !this._enableDirtyRegion || !this._canUseDirtyRegion;
  13440. var collectResult = true;
  13441. if (!allNeedDraw) {
  13442. collectResult = this._collectDirtyRegion();
  13443. }
  13444. allNeedDraw = allNeedDraw || (!collectResult);
  13445. if(!allNeedDraw) {
  13446. this._beginDrawDirtyRegion(wrapper);
  13447. }
  13448. ctx.setTransform(1, 0, 0, 1, 0, 0);
  13449. ctx.clearRect(0, 0, viewport.width, viewport.height);
  13450. if (this._clearColor.r !== 0 ||
  13451. this._clearColor.g !== 0 ||
  13452. this._clearColor.b !== 0) {
  13453. wrapper.setFillStyle(this._clearFillStyle);
  13454. wrapper.setGlobalAlpha(this._clearColor.a);
  13455. ctx.fillRect(0, 0, viewport.width, viewport.height);
  13456. }
  13457. for (i = 0, len = locCmds.length; i < len; i++) {
  13458. var cmd = locCmds[i];
  13459. var needRendering = false;
  13460. var cmdRegion = cmd._currentRegion;
  13461. if (!cmdRegion || allNeedDraw) {
  13462. needRendering = true;
  13463. } else {
  13464. for (var index = 0, count = dirtyList.length; index < count; ++index) {
  13465. if (dirtyList[index].intersects(cmdRegion)) {
  13466. needRendering = true;
  13467. break;
  13468. }
  13469. }
  13470. }
  13471. if (needRendering) {
  13472. cmd.rendering(wrapper, scaleX, scaleY);
  13473. }
  13474. }
  13475. if (!allNeedDraw) {
  13476. this._debugDrawDirtyRegion(wrapper);
  13477. this._endDrawDirtyRegion(ctx);
  13478. }
  13479. dirtyRegion.clear();
  13480. this._allNeedDraw = false;
  13481. },
  13482. _renderingToCacheCanvas: function (ctx, instanceID, scaleX, scaleY) {
  13483. if (!ctx)
  13484. cc.log("The context of RenderTexture is invalid.");
  13485. scaleX = cc.isUndefined(scaleX) ? 1 : scaleX;
  13486. scaleY = cc.isUndefined(scaleY) ? 1 : scaleY;
  13487. instanceID = instanceID || this._currentID;
  13488. var locCmds = this._cacheToCanvasCmds[instanceID], i, len;
  13489. ctx.computeRealOffsetY();
  13490. for (i = 0, len = locCmds.length; i < len; i++) {
  13491. locCmds[i].rendering(ctx, scaleX, scaleY);
  13492. }
  13493. this._removeCache(instanceID);
  13494. var locIDs = this._cacheInstanceIds;
  13495. if (locIDs.length === 0)
  13496. this._isCacheToCanvasOn = false;
  13497. else
  13498. this._currentID = locIDs[locIDs.length - 1];
  13499. },
  13500. _turnToCacheMode: function (renderTextureID) {
  13501. this._isCacheToCanvasOn = true;
  13502. renderTextureID = renderTextureID || 0;
  13503. this._cacheToCanvasCmds[renderTextureID] = [];
  13504. if (this._cacheInstanceIds.indexOf(renderTextureID) === -1)
  13505. this._cacheInstanceIds.push(renderTextureID);
  13506. this._currentID = renderTextureID;
  13507. },
  13508. _turnToNormalMode: function () {
  13509. this._isCacheToCanvasOn = false;
  13510. },
  13511. _removeCache: function (instanceID) {
  13512. instanceID = instanceID || this._currentID;
  13513. var cmds = this._cacheToCanvasCmds[instanceID];
  13514. if (cmds) {
  13515. cmds.length = 0;
  13516. delete this._cacheToCanvasCmds[instanceID];
  13517. }
  13518. var locIDs = this._cacheInstanceIds;
  13519. cc.arrayRemoveObject(locIDs, instanceID);
  13520. },
  13521. resetFlag: function () {
  13522. this.childrenOrderDirty = false;
  13523. this._transformNodePool.length = 0;
  13524. },
  13525. transform: function () {
  13526. var locPool = this._transformNodePool;
  13527. locPool.sort(this._sortNodeByLevelAsc);
  13528. for (var i = 0, len = locPool.length; i < len; i++) {
  13529. if (locPool[i]._dirtyFlag !== 0)
  13530. locPool[i].updateStatus();
  13531. }
  13532. locPool.length = 0;
  13533. },
  13534. transformDirty: function () {
  13535. return this._transformNodePool.length > 0;
  13536. },
  13537. _sortNodeByLevelAsc: function (n1, n2) {
  13538. return n1._curLevel - n2._curLevel;
  13539. },
  13540. pushDirtyNode: function (node) {
  13541. this._transformNodePool.push(node);
  13542. },
  13543. clear: function () {
  13544. },
  13545. clearRenderCommands: function () {
  13546. this._renderCmds.length = 0;
  13547. this._cacheInstanceIds.length = 0;
  13548. this._isCacheToCanvasOn = false;
  13549. this._allNeedDraw = true;
  13550. this._canUseDirtyRegion = true;
  13551. },
  13552. pushRenderCommand: function (cmd) {
  13553. if (!cmd.needDraw())
  13554. return;
  13555. if (!cmd._canUseDirtyRegion) {
  13556. this._canUseDirtyRegion = false;
  13557. }
  13558. if (this._isCacheToCanvasOn) {
  13559. var currentId = this._currentID, locCmdBuffer = this._cacheToCanvasCmds;
  13560. var cmdList = locCmdBuffer[currentId];
  13561. if (cmdList.indexOf(cmd) === -1)
  13562. cmdList.push(cmd);
  13563. } else {
  13564. if (this._renderCmds.indexOf(cmd) === -1)
  13565. this._renderCmds.push(cmd);
  13566. }
  13567. }
  13568. };
  13569. (function () {
  13570. cc.CanvasContextWrapper = function (context) {
  13571. this._context = context;
  13572. this._saveCount = 0;
  13573. this._currentAlpha = context.globalAlpha;
  13574. this._currentCompositeOperation = context.globalCompositeOperation;
  13575. this._currentFillStyle = context.fillStyle;
  13576. this._currentStrokeStyle = context.strokeStyle;
  13577. this._offsetX = 0;
  13578. this._offsetY = 0;
  13579. this._realOffsetY = this.height;
  13580. this._armatureMode = 0;
  13581. };
  13582. var proto = cc.CanvasContextWrapper.prototype;
  13583. proto.resetCache = function () {
  13584. var context = this._context;
  13585. this._currentAlpha = context.globalAlpha;
  13586. this._currentCompositeOperation = context.globalCompositeOperation;
  13587. this._currentFillStyle = context.fillStyle;
  13588. this._currentStrokeStyle = context.strokeStyle;
  13589. this._realOffsetY = this._context.canvas.height + this._offsetY;
  13590. };
  13591. proto.setOffset = function (x, y) {
  13592. this._offsetX = x;
  13593. this._offsetY = y;
  13594. this._realOffsetY = this._context.canvas.height + this._offsetY;
  13595. };
  13596. proto.computeRealOffsetY = function () {
  13597. this._realOffsetY = this._context.canvas.height + this._offsetY;
  13598. };
  13599. proto.setViewScale = function (scaleX, scaleY) {
  13600. this._scaleX = scaleX;
  13601. this._scaleY = scaleY;
  13602. };
  13603. proto.getContext = function () {
  13604. return this._context;
  13605. };
  13606. proto.save = function () {
  13607. this._context.save();
  13608. this._saveCount++;
  13609. };
  13610. proto.restore = function () {
  13611. this._context.restore();
  13612. this._saveCount--;
  13613. };
  13614. proto.setGlobalAlpha = function (alpha) {
  13615. if (this._saveCount > 0) {
  13616. this._context.globalAlpha = alpha;
  13617. } else {
  13618. if (this._currentAlpha !== alpha) {
  13619. this._currentAlpha = alpha;
  13620. this._context.globalAlpha = alpha;
  13621. }
  13622. }
  13623. };
  13624. proto.setCompositeOperation = function (compositionOperation) {
  13625. if (this._saveCount > 0) {
  13626. this._context.globalCompositeOperation = compositionOperation;
  13627. } else {
  13628. if (this._currentCompositeOperation !== compositionOperation) {
  13629. this._currentCompositeOperation = compositionOperation;
  13630. this._context.globalCompositeOperation = compositionOperation;
  13631. }
  13632. }
  13633. };
  13634. proto.setFillStyle = function (fillStyle) {
  13635. if (this._saveCount > 0) {
  13636. this._context.fillStyle = fillStyle;
  13637. } else {
  13638. if (this._currentFillStyle !== fillStyle) {
  13639. this._currentFillStyle = fillStyle;
  13640. this._context.fillStyle = fillStyle;
  13641. }
  13642. }
  13643. };
  13644. proto.setStrokeStyle = function (strokeStyle) {
  13645. if (this._saveCount > 0) {
  13646. this._context.strokeStyle = strokeStyle;
  13647. } else {
  13648. if (this._currentStrokeStyle !== strokeStyle) {
  13649. this._currentStrokeStyle = strokeStyle;
  13650. this._context.strokeStyle = strokeStyle;
  13651. }
  13652. }
  13653. };
  13654. proto.setTransform = function (t, scaleX, scaleY) {
  13655. if (this._armatureMode > 0) {
  13656. this.restore();
  13657. this.save();
  13658. this._context.transform(t.a * scaleX, -t.b * scaleY, -t.c * scaleX, t.d * scaleY, t.tx * scaleX, -(t.ty * scaleY));
  13659. } else {
  13660. this._context.setTransform(t.a * scaleX, -t.b * scaleY, -t.c * scaleX, t.d * scaleY, this._offsetX + t.tx * scaleX, this._realOffsetY - (t.ty * scaleY));
  13661. }
  13662. };
  13663. proto._switchToArmatureMode = function (enable, t, scaleX, scaleY) {
  13664. if (enable) {
  13665. this._armatureMode++;
  13666. this._context.setTransform(t.a, t.c, t.b, t.d, this._offsetX + t.tx * scaleX, this._realOffsetY - (t.ty * scaleY));
  13667. this.save();
  13668. } else {
  13669. this._armatureMode--;
  13670. this.restore();
  13671. }
  13672. };
  13673. })();
  13674. var Region = function () {
  13675. this._minX = 0;
  13676. this._minY = 0;
  13677. this._maxX = 0;
  13678. this._maxY = 0;
  13679. this._width = 0;
  13680. this._height = 0;
  13681. this._area = 0;
  13682. };
  13683. var regionProto = Region.prototype;
  13684. var regionPool = [];
  13685. function regionCreate() {
  13686. var region = regionPool.pop();
  13687. if (!region) {
  13688. region = new Region();
  13689. }
  13690. return region;
  13691. }
  13692. function regionRelease(region) {
  13693. regionPool.push(region);
  13694. }
  13695. regionProto.setTo = function (minX, minY, maxX, maxY) {
  13696. this._minX = minX;
  13697. this._minY = minY;
  13698. this._maxX = maxX;
  13699. this._maxY = maxY;
  13700. this.updateArea();
  13701. return this;
  13702. };
  13703. regionProto.intValues = function () {
  13704. this._minX = Math.floor(this._minX);
  13705. this._minY = Math.floor(this._minY);
  13706. this._maxX = Math.ceil(this._maxX);
  13707. this._maxY = Math.ceil(this._maxY);
  13708. this.updateArea();
  13709. };
  13710. regionProto.updateArea = function () {
  13711. this._width = this._maxX - this._minX;
  13712. this._height = this._maxY - this._minY;
  13713. this._area = this._width * this._height;
  13714. };
  13715. regionProto.union = function (target) {
  13716. if(this._width <= 0 || this._height <= 0) {
  13717. this.setTo(target._minX, target._minY, target._maxX, target._maxY);
  13718. return;
  13719. }
  13720. if (this._minX > target._minX) {
  13721. this._minX = target._minX;
  13722. }
  13723. if (this._minY > target._minY) {
  13724. this._minY = target._minY;
  13725. }
  13726. if (this._maxX < target._maxX) {
  13727. this._maxX = target._maxX;
  13728. }
  13729. if (this._maxY < target._maxY) {
  13730. this._maxY = target._maxY;
  13731. }
  13732. this.updateArea();
  13733. };
  13734. regionProto.setEmpty = function () {
  13735. this._minX = 0;
  13736. this._minY = 0;
  13737. this._maxX = 0;
  13738. this._maxY = 0;
  13739. this._width = 0;
  13740. this._height = 0;
  13741. this._area = 0;
  13742. };
  13743. regionProto.isEmpty = function () {
  13744. return this._width <= 0 || this._height <= 0;
  13745. };
  13746. regionProto.intersects = function (target) {
  13747. if (this._width <= 0 || this._height <= 0 || target._width <= 0 || target._height <= 0) {
  13748. return false;
  13749. }
  13750. var max = this._minX > target._minX ? this._minX : target._minX;
  13751. var min = this._maxX < target._maxX ? this._maxX : target._maxX;
  13752. if (max > min) {
  13753. return false;
  13754. }
  13755. max = this._minY > target._minY ? this._minY : target._minY;
  13756. min = this._maxY < target._maxY ? this._maxY : target._maxY;
  13757. return max <= min;
  13758. };
  13759. regionProto.updateRegion = function (bounds, matrix) {
  13760. if (bounds.width == 0 || bounds.height == 0) {
  13761. this.setEmpty();
  13762. return;
  13763. }
  13764. var m = matrix;
  13765. var a = m.a;
  13766. var b = m.b;
  13767. var c = m.c;
  13768. var d = m.d;
  13769. var tx = m.tx;
  13770. var ty = m.ty;
  13771. var x = bounds.x;
  13772. var y = bounds.y;
  13773. var xMax = x + bounds.width;
  13774. var yMax = y + bounds.height;
  13775. var minX, minY, maxX, maxY;
  13776. if (a == 1.0 && b == 0.0 && c == 0.0 && d == 1.0) {
  13777. minX = x + tx - 1;
  13778. minY = y + ty - 1;
  13779. maxX = xMax + tx + 1;
  13780. maxY = yMax + ty + 1;
  13781. }
  13782. else {
  13783. var x0 = a * x + c * y + tx;
  13784. var y0 = b * x + d * y + ty;
  13785. var x1 = a * xMax + c * y + tx;
  13786. var y1 = b * xMax + d * y + ty;
  13787. var x2 = a * xMax + c * yMax + tx;
  13788. var y2 = b * xMax + d * yMax + ty;
  13789. var x3 = a * x + c * yMax + tx;
  13790. var y3 = b * x + d * yMax + ty;
  13791. var tmp = 0;
  13792. if (x0 > x1) {
  13793. tmp = x0;
  13794. x0 = x1;
  13795. x1 = tmp;
  13796. }
  13797. if (x2 > x3) {
  13798. tmp = x2;
  13799. x2 = x3;
  13800. x3 = tmp;
  13801. }
  13802. minX = (x0 < x2 ? x0 : x2) - 1;
  13803. maxX = (x1 > x3 ? x1 : x3) + 1;
  13804. if (y0 > y1) {
  13805. tmp = y0;
  13806. y0 = y1;
  13807. y1 = tmp;
  13808. }
  13809. if (y2 > y3) {
  13810. tmp = y2;
  13811. y2 = y3;
  13812. y3 = tmp;
  13813. }
  13814. minY = (y0 < y2 ? y0 : y2) - 1;
  13815. maxY = (y1 > y3 ? y1 : y3) + 1;
  13816. }
  13817. this._minX = minX;
  13818. this._minY = minY;
  13819. this._maxX = maxX;
  13820. this._maxY = maxY;
  13821. this._width = maxX - minX;
  13822. this._height = maxY - minY;
  13823. this._area = this._width * this._height;
  13824. };
  13825. function unionArea(r1, r2) {
  13826. var minX = r1._minX < r2._minX ? r1._minX : r2._minX;
  13827. var minY = r1._minY < r2._minY ? r1._minY : r2._minY;
  13828. var maxX = r1._maxX > r2._maxX ? r1._maxX : r2._maxX;
  13829. var maxY = r1._maxY > r2._maxY ? r1._maxY : r2._maxY;
  13830. return (maxX - minX) * (maxY - minY);
  13831. }
  13832. var DirtyRegion = function() {
  13833. this.dirtyList = [];
  13834. this.hasClipRect = false;
  13835. this.clipWidth = 0;
  13836. this.clipHeight = 0;
  13837. this.clipArea = 0;
  13838. this.clipRectChanged = false;
  13839. };
  13840. var dirtyRegionProto = DirtyRegion.prototype;
  13841. dirtyRegionProto.setClipRect = function(width, height) {
  13842. this.hasClipRect = true;
  13843. this.clipRectChanged = true;
  13844. this.clipWidth = Math.ceil(width);
  13845. this.clipHeight = Math.ceil(height);
  13846. this.clipArea = this.clipWidth * this.clipHeight;
  13847. };
  13848. dirtyRegionProto.addRegion = function(target) {
  13849. var minX = target._minX, minY = target._minY, maxX = target._maxX, maxY = target._maxY;
  13850. if (this.hasClipRect) {
  13851. if (minX < 0) {
  13852. minX = 0;
  13853. }
  13854. if (minY < 0) {
  13855. minY = 0;
  13856. }
  13857. if (maxX > this.clipWidth) {
  13858. maxX = this.clipWidth;
  13859. }
  13860. if (maxY > this.clipHeight) {
  13861. maxY = this.clipHeight;
  13862. }
  13863. }
  13864. if (minX >= maxX || minY >= maxY) {
  13865. return false;
  13866. }
  13867. if (this.clipRectChanged) {
  13868. return true;
  13869. }
  13870. var dirtyList = this.dirtyList;
  13871. var region = regionCreate();
  13872. dirtyList.push(region.setTo(minX, minY, maxX, maxY));
  13873. this.mergeDirtyList(dirtyList);
  13874. return true;
  13875. };
  13876. dirtyRegionProto.clear = function() {
  13877. var dirtyList = this.dirtyList;
  13878. var length = dirtyList.length;
  13879. for (var i = 0; i < length; i++) {
  13880. regionRelease(dirtyList[i]);
  13881. }
  13882. dirtyList.length = 0;
  13883. };
  13884. dirtyRegionProto.getDirtyRegions = function() {
  13885. var dirtyList = this.dirtyList;
  13886. if (this.clipRectChanged) {
  13887. this.clipRectChanged = false;
  13888. this.clear();
  13889. var region = regionCreate();
  13890. dirtyList.push(region.setTo(0, 0, this.clipWidth, this.clipHeight));
  13891. }
  13892. else {
  13893. while (this.mergeDirtyList(dirtyList)) {
  13894. }
  13895. }
  13896. var numDirty = this.dirtyList.length;
  13897. if (numDirty > 0) {
  13898. for (var i = 0; i < numDirty; i++) {
  13899. this.dirtyList[i].intValues();
  13900. }
  13901. }
  13902. return this.dirtyList;
  13903. };
  13904. dirtyRegionProto.mergeDirtyList = function(dirtyList) {
  13905. var length = dirtyList.length;
  13906. if (length < 2) {
  13907. return false;
  13908. }
  13909. var hasClipRect = this.hasClipRect;
  13910. var bestDelta = length > 3 ? Number.POSITIVE_INFINITY : 0;
  13911. var mergeA = 0;
  13912. var mergeB = 0;
  13913. var totalArea = 0;
  13914. for (var i = 0; i < length - 1; i++) {
  13915. var regionA = dirtyList[i];
  13916. hasClipRect && (totalArea += regionA.area);
  13917. for (var j = i + 1; j < length; j++) {
  13918. var regionB = dirtyList[j];
  13919. var delta = unionArea(regionA, regionB) - regionA.area - regionB.area;
  13920. if (bestDelta > delta) {
  13921. mergeA = i;
  13922. mergeB = j;
  13923. bestDelta = delta;
  13924. }
  13925. }
  13926. }
  13927. if (hasClipRect && (totalArea / this.clipArea) > 0.95) {
  13928. this.clipRectChanged = true;
  13929. }
  13930. if (mergeA != mergeB) {
  13931. var region = dirtyList[mergeB];
  13932. dirtyList[mergeA].union(region);
  13933. regionRelease(region);
  13934. dirtyList.splice(mergeB, 1);
  13935. return true;
  13936. }
  13937. return false;
  13938. };
  13939. cc.Region = Region;
  13940. cc.DirtyRegion = DirtyRegion;
  13941. cc.profiler = (function () {
  13942. var _showFPS = false;
  13943. var _inited = false;
  13944. var _frames = 0, _frameRate = 0, _lastSPF = 0, _accumDt = 0;
  13945. var _afterVisitListener = null,
  13946. _FPSLabel = document.createElement('div'),
  13947. _SPFLabel = document.createElement('div'),
  13948. _drawsLabel = document.createElement('div'),
  13949. _fps = document.createElement('div');
  13950. var LEVEL_DET_FACTOR = 0.6, _levelDetCycle = 10;
  13951. var LEVELS = [0, 10, 20, 30];
  13952. var _fpsCount = [0, 0, 0, 0];
  13953. var _currLevel = 3, _analyseCount = 0, _totalFPS = 0;
  13954. _fps.id = 'fps';
  13955. _fps.style.position = 'absolute';
  13956. _fps.style.padding = '3px';
  13957. _fps.style.textAlign = 'left';
  13958. _fps.style.backgroundColor = 'rgb(0, 0, 34)';
  13959. _fps.style.bottom = cc.DIRECTOR_STATS_POSITION.y + '0px';
  13960. _fps.style.left = cc.DIRECTOR_STATS_POSITION.x + 'px';
  13961. _fps.style.width = '45px';
  13962. _fps.style.height = '60px';
  13963. var labels = [_drawsLabel, _SPFLabel, _FPSLabel];
  13964. for (var i = 0; i < 3; ++i) {
  13965. var style = labels[i].style;
  13966. style.color = 'rgb(0, 255, 255)';
  13967. style.font = 'bold 12px Helvetica, Arial';
  13968. style.lineHeight = '20px';
  13969. style.width = '100%';
  13970. _fps.appendChild(labels[i]);
  13971. }
  13972. var analyseFPS = function (fps) {
  13973. var lastId = LEVELS.length - 1, i = lastId, ratio, average = 0;
  13974. _analyseCount++;
  13975. _totalFPS += fps;
  13976. for (; i >= 0; i--) {
  13977. if (fps >= LEVELS[i]) {
  13978. _fpsCount[i]++;
  13979. break;
  13980. }
  13981. }
  13982. if (_analyseCount >= _levelDetCycle) {
  13983. average = _totalFPS / _levelDetCycle;
  13984. for (i = lastId; i >0; i--) {
  13985. ratio = _fpsCount[i] / _levelDetCycle;
  13986. if (ratio >= LEVEL_DET_FACTOR && average >= LEVELS[i]) {
  13987. if (i != _currLevel) {
  13988. _currLevel = i;
  13989. profiler.onFrameRateChange && profiler.onFrameRateChange(average.toFixed(2));
  13990. }
  13991. break;
  13992. }
  13993. }
  13994. _changeCount = 0;
  13995. _analyseCount = 0;
  13996. _totalFPS = 0;
  13997. for (i = lastId; i > 0; i--) {
  13998. _fpsCount[i] = 0;
  13999. }
  14000. }
  14001. };
  14002. var afterVisit = function () {
  14003. _lastSPF = cc.director.getSecondsPerFrame();
  14004. _frames++;
  14005. _accumDt += cc.director.getDeltaTime();
  14006. if (_accumDt > cc.DIRECTOR_FPS_INTERVAL) {
  14007. _frameRate = _frames / _accumDt;
  14008. _frames = 0;
  14009. _accumDt = 0;
  14010. if (profiler.onFrameRateChange) {
  14011. analyseFPS(_frameRate);
  14012. }
  14013. if (_showFPS) {
  14014. _SPFLabel.innerText = _lastSPF.toFixed(3);
  14015. _FPSLabel.innerText = _frameRate.toFixed(1);
  14016. _drawsLabel.innerText = (0 | cc.g_NumberOfDraws).toString();
  14017. }
  14018. }
  14019. };
  14020. var profiler = {
  14021. onFrameRateChange: null,
  14022. getSecondsPerFrame: function () {
  14023. return _lastSPF;
  14024. },
  14025. getFrameRate: function () {
  14026. return _frameRate;
  14027. },
  14028. setProfileDuration: function (duration) {
  14029. if (!isNaN(duration) && duration > 0) {
  14030. _levelDetCycle = duration / cc.DIRECTOR_FPS_INTERVAL;
  14031. }
  14032. },
  14033. resumeProfiling: function () {
  14034. cc.eventManager.addListener(_afterVisitListener, 1);
  14035. },
  14036. stopProfiling: function () {
  14037. cc.eventManager.removeListener(_afterVisitListener);
  14038. },
  14039. isShowingStats: function () {
  14040. return _showFPS;
  14041. },
  14042. showStats: function () {
  14043. if (!_inited) {
  14044. this.init();
  14045. }
  14046. if (_fps.parentElement === null) {
  14047. cc.container.appendChild(_fps);
  14048. }
  14049. _showFPS = true;
  14050. },
  14051. hideStats: function () {
  14052. _showFPS = false;
  14053. if (_fps.parentElement === cc.container) {
  14054. cc.container.removeChild(_fps);
  14055. }
  14056. },
  14057. init: function () {
  14058. if (!_inited) {
  14059. _afterVisitListener = cc.eventManager.addCustomListener(cc.Director.EVENT_AFTER_VISIT, afterVisit);
  14060. _inited = true;
  14061. }
  14062. }
  14063. };
  14064. return profiler;
  14065. })();
  14066. cc._LogInfos = {
  14067. ActionManager_addAction: "cc.ActionManager.addAction(): action must be non-null",
  14068. ActionManager_removeAction: "cocos2d: removeAction: Target not found",
  14069. ActionManager_removeActionByTag: "cc.ActionManager.removeActionByTag(): an invalid tag",
  14070. ActionManager_removeActionByTag_2: "cc.ActionManager.removeActionByTag(): target must be non-null",
  14071. ActionManager_getActionByTag: "cc.ActionManager.getActionByTag(): an invalid tag",
  14072. ActionManager_getActionByTag_2: "cocos2d : getActionByTag(tag = %s): Action not found",
  14073. configuration_dumpInfo: "cocos2d: **** WARNING **** CC_ENABLE_PROFILERS is defined. Disable it when you finish profiling (from ccConfig.js)",
  14074. configuration_loadConfigFile: "Expected 'data' dict, but not found. Config file: %s",
  14075. configuration_loadConfigFile_2: "Please load the resource first : %s",
  14076. Director_resume: "cocos2d: Director: Error in gettimeofday",
  14077. Director_setProjection: "cocos2d: Director: unrecognized projection",
  14078. Director_popToSceneStackLevel: "cocos2d: Director: unrecognized projection",
  14079. Director_popToSceneStackLevel_2: "cocos2d: Director: Error in gettimeofday",
  14080. Director_popScene: "running scene should not null",
  14081. Director_pushScene: "the scene should not null",
  14082. arrayVerifyType: "element type is wrong!",
  14083. Scheduler_scheduleCallbackForTarget: "CCSheduler#scheduleCallback. Callback already scheduled. Updating interval from:%s to %s",
  14084. Scheduler_scheduleCallbackForTarget_2: "cc.scheduler.scheduleCallbackForTarget(): callback_fn should be non-null.",
  14085. Scheduler_scheduleCallbackForTarget_3: "cc.scheduler.scheduleCallbackForTarget(): target should be non-null.",
  14086. Scheduler_pauseTarget: "cc.Scheduler.pauseTarget():target should be non-null",
  14087. Scheduler_resumeTarget: "cc.Scheduler.resumeTarget():target should be non-null",
  14088. Scheduler_isTargetPaused: "cc.Scheduler.isTargetPaused():target should be non-null",
  14089. Node_getZOrder: "getZOrder is deprecated. Please use getLocalZOrder instead.",
  14090. Node_setZOrder: "setZOrder is deprecated. Please use setLocalZOrder instead.",
  14091. Node_getRotation: "RotationX != RotationY. Don't know which one to return",
  14092. Node_getScale: "ScaleX != ScaleY. Don't know which one to return",
  14093. Node_addChild: "An Node can't be added as a child of itself.",
  14094. Node_addChild_2: "child already added. It can't be added again",
  14095. Node_addChild_3: "child must be non-null",
  14096. Node_removeFromParentAndCleanup: "removeFromParentAndCleanup is deprecated. Use removeFromParent instead",
  14097. Node_boundingBox: "boundingBox is deprecated. Use getBoundingBox instead",
  14098. Node_removeChildByTag: "argument tag is an invalid tag",
  14099. Node_removeChildByTag_2: "cocos2d: removeChildByTag(tag = %s): child not found!",
  14100. Node_removeAllChildrenWithCleanup: "removeAllChildrenWithCleanup is deprecated. Use removeAllChildren instead",
  14101. Node_stopActionByTag: "cc.Node.stopActionBy(): argument tag an invalid tag",
  14102. Node_getActionByTag: "cc.Node.getActionByTag(): argument tag is an invalid tag",
  14103. Node_resumeSchedulerAndActions: "resumeSchedulerAndActions is deprecated, please use resume instead.",
  14104. Node_pauseSchedulerAndActions: "pauseSchedulerAndActions is deprecated, please use pause instead.",
  14105. Node__arrayMakeObjectsPerformSelector: "Unknown callback function",
  14106. Node_reorderChild: "child must be non-null",
  14107. Node_runAction: "cc.Node.runAction(): action must be non-null",
  14108. Node_schedule: "callback function must be non-null",
  14109. Node_schedule_2: "interval must be positive",
  14110. Node_initWithTexture: "cocos2d: Could not initialize cc.AtlasNode. Invalid Texture.",
  14111. AtlasNode_updateAtlasValues: "cc.AtlasNode.updateAtlasValues(): Shall be overridden in subclasses",
  14112. AtlasNode_initWithTileFile: "",
  14113. AtlasNode__initWithTexture: "cocos2d: Could not initialize cc.AtlasNode. Invalid Texture.",
  14114. _EventListenerKeyboard_checkAvailable: "cc._EventListenerKeyboard.checkAvailable(): Invalid EventListenerKeyboard!",
  14115. _EventListenerTouchOneByOne_checkAvailable: "cc._EventListenerTouchOneByOne.checkAvailable(): Invalid EventListenerTouchOneByOne!",
  14116. _EventListenerTouchAllAtOnce_checkAvailable: "cc._EventListenerTouchAllAtOnce.checkAvailable(): Invalid EventListenerTouchAllAtOnce!",
  14117. _EventListenerAcceleration_checkAvailable: "cc._EventListenerAcceleration.checkAvailable(): _onAccelerationEvent must be non-nil",
  14118. EventListener_create: "Invalid parameter.",
  14119. __getListenerID: "Don't call this method if the event is for touch.",
  14120. eventManager__forceAddEventListener: "Invalid scene graph priority!",
  14121. eventManager_addListener: "0 priority is forbidden for fixed priority since it's used for scene graph based priority.",
  14122. eventManager_removeListeners: "Invalid listener type!",
  14123. eventManager_setPriority: "Can't set fixed priority with scene graph based listener.",
  14124. eventManager_addListener_2: "Invalid parameters.",
  14125. eventManager_addListener_3: "listener must be a cc.EventListener object when adding a fixed priority listener",
  14126. eventManager_addListener_4: "The listener has been registered, please don't register it again.",
  14127. LayerMultiplex_initWithLayers: "parameters should not be ending with null in Javascript",
  14128. LayerMultiplex_switchTo: "Invalid index in MultiplexLayer switchTo message",
  14129. LayerMultiplex_switchToAndReleaseMe: "Invalid index in MultiplexLayer switchTo message",
  14130. LayerMultiplex_addLayer: "cc.Layer.addLayer(): layer should be non-null",
  14131. EGLView_setDesignResolutionSize: "Resolution not valid",
  14132. EGLView_setDesignResolutionSize_2: "should set resolutionPolicy",
  14133. inputManager_handleTouchesBegin: "The touches is more than MAX_TOUCHES, nUnusedIndex = %s",
  14134. swap: "cc.swap is being modified from original macro, please check usage",
  14135. checkGLErrorDebug: "WebGL error %s",
  14136. animationCache__addAnimationsWithDictionary: "cocos2d: cc.AnimationCache: No animations were found in provided dictionary.",
  14137. animationCache__addAnimationsWithDictionary_2: "cc.AnimationCache. Invalid animation format",
  14138. animationCache_addAnimations: "cc.AnimationCache.addAnimations(): File could not be found",
  14139. animationCache__parseVersion1: "cocos2d: cc.AnimationCache: Animation '%s' found in dictionary without any frames - cannot add to animation cache.",
  14140. animationCache__parseVersion1_2: "cocos2d: cc.AnimationCache: Animation '%s' refers to frame '%s' which is not currently in the cc.SpriteFrameCache. This frame will not be added to the animation.",
  14141. animationCache__parseVersion1_3: "cocos2d: cc.AnimationCache: None of the frames for animation '%s' were found in the cc.SpriteFrameCache. Animation is not being added to the Animation Cache.",
  14142. animationCache__parseVersion1_4: "cocos2d: cc.AnimationCache: An animation in your dictionary refers to a frame which is not in the cc.SpriteFrameCache. Some or all of the frames for the animation '%s' may be missing.",
  14143. animationCache__parseVersion2: "cocos2d: CCAnimationCache: Animation '%s' found in dictionary without any frames - cannot add to animation cache.",
  14144. animationCache__parseVersion2_2: "cocos2d: cc.AnimationCache: Animation '%s' refers to frame '%s' which is not currently in the cc.SpriteFrameCache. This frame will not be added to the animation.",
  14145. animationCache_addAnimations_2: "cc.AnimationCache.addAnimations(): Invalid texture file name",
  14146. Sprite_reorderChild: "cc.Sprite.reorderChild(): this child is not in children list",
  14147. Sprite_ignoreAnchorPointForPosition: "cc.Sprite.ignoreAnchorPointForPosition(): it is invalid in cc.Sprite when using SpriteBatchNode",
  14148. Sprite_setDisplayFrameWithAnimationName: "cc.Sprite.setDisplayFrameWithAnimationName(): Frame not found",
  14149. Sprite_setDisplayFrameWithAnimationName_2: "cc.Sprite.setDisplayFrameWithAnimationName(): Invalid frame index",
  14150. Sprite_setDisplayFrame: "setDisplayFrame is deprecated, please use setSpriteFrame instead.",
  14151. Sprite__updateBlendFunc: "cc.Sprite._updateBlendFunc(): _updateBlendFunc doesn't work when the sprite is rendered using a cc.CCSpriteBatchNode",
  14152. Sprite_initWithSpriteFrame: "cc.Sprite.initWithSpriteFrame(): spriteFrame should be non-null",
  14153. Sprite_initWithSpriteFrameName: "cc.Sprite.initWithSpriteFrameName(): spriteFrameName should be non-null",
  14154. Sprite_initWithSpriteFrameName1: " is null, please check.",
  14155. Sprite_initWithFile: "cc.Sprite.initWithFile(): filename should be non-null",
  14156. Sprite_setDisplayFrameWithAnimationName_3: "cc.Sprite.setDisplayFrameWithAnimationName(): animationName must be non-null",
  14157. Sprite_reorderChild_2: "cc.Sprite.reorderChild(): child should be non-null",
  14158. Sprite_addChild: "cc.Sprite.addChild(): cc.Sprite only supports cc.Sprites as children when using cc.SpriteBatchNode",
  14159. Sprite_addChild_2: "cc.Sprite.addChild(): cc.Sprite only supports a sprite using same texture as children when using cc.SpriteBatchNode",
  14160. Sprite_addChild_3: "cc.Sprite.addChild(): child should be non-null",
  14161. Sprite_setTexture: "cc.Sprite.texture setter: Batched sprites should use the same texture as the batchnode",
  14162. Sprite_updateQuadFromSprite: "cc.SpriteBatchNode.updateQuadFromSprite(): cc.SpriteBatchNode only supports cc.Sprites as children",
  14163. Sprite_insertQuadFromSprite: "cc.SpriteBatchNode.insertQuadFromSprite(): cc.SpriteBatchNode only supports cc.Sprites as children",
  14164. Sprite_addChild_4: "cc.SpriteBatchNode.addChild(): cc.SpriteBatchNode only supports cc.Sprites as children",
  14165. Sprite_addChild_5: "cc.SpriteBatchNode.addChild(): cc.Sprite is not using the same texture",
  14166. Sprite_initWithTexture: "Sprite.initWithTexture(): Argument must be non-nil ",
  14167. Sprite_setSpriteFrame: "Invalid spriteFrameName",
  14168. Sprite_setTexture_2: "Invalid argument: cc.Sprite.texture setter expects a CCTexture2D.",
  14169. Sprite_updateQuadFromSprite_2: "cc.SpriteBatchNode.updateQuadFromSprite(): sprite should be non-null",
  14170. Sprite_insertQuadFromSprite_2: "cc.SpriteBatchNode.insertQuadFromSprite(): sprite should be non-null",
  14171. SpriteBatchNode_addSpriteWithoutQuad: "cc.SpriteBatchNode.addQuadFromSprite(): SpriteBatchNode only supports cc.Sprites as children",
  14172. SpriteBatchNode_increaseAtlasCapacity: "cocos2d: CCSpriteBatchNode: resizing TextureAtlas capacity from %s to %s.",
  14173. SpriteBatchNode_increaseAtlasCapacity_2: "cocos2d: WARNING: Not enough memory to resize the atlas",
  14174. SpriteBatchNode_reorderChild: "cc.SpriteBatchNode.addChild(): Child doesn't belong to Sprite",
  14175. SpriteBatchNode_removeChild: "cc.SpriteBatchNode.addChild(): sprite batch node should contain the child",
  14176. SpriteBatchNode_addSpriteWithoutQuad_2: "cc.SpriteBatchNode.addQuadFromSprite(): child should be non-null",
  14177. SpriteBatchNode_reorderChild_2: "cc.SpriteBatchNode.addChild(): child should be non-null",
  14178. spriteFrameCache__getFrameConfig: "cocos2d: WARNING: originalWidth/Height not found on the cc.SpriteFrame. AnchorPoint won't work as expected. Regenrate the .plist",
  14179. spriteFrameCache_addSpriteFrames: "cocos2d: WARNING: an alias with name %s already exists",
  14180. spriteFrameCache__checkConflict: "cocos2d: WARNING: Sprite frame: %s has already been added by another source, please fix name conflit",
  14181. spriteFrameCache_getSpriteFrame: "cocos2d: cc.SpriteFrameCahce: Frame %s not found",
  14182. spriteFrameCache__getFrameConfig_2: "Please load the resource first : %s",
  14183. spriteFrameCache_addSpriteFrames_2: "cc.SpriteFrameCache.addSpriteFrames(): plist should be non-null",
  14184. spriteFrameCache_addSpriteFrames_3: "Argument must be non-nil",
  14185. CCSpriteBatchNode_updateQuadFromSprite: "cc.SpriteBatchNode.updateQuadFromSprite(): cc.SpriteBatchNode only supports cc.Sprites as children",
  14186. CCSpriteBatchNode_insertQuadFromSprite: "cc.SpriteBatchNode.insertQuadFromSprite(): cc.SpriteBatchNode only supports cc.Sprites as children",
  14187. CCSpriteBatchNode_addChild: "cc.SpriteBatchNode.addChild(): cc.SpriteBatchNode only supports cc.Sprites as children",
  14188. CCSpriteBatchNode_initWithTexture: "Sprite.initWithTexture(): Argument must be non-nil ",
  14189. CCSpriteBatchNode_addChild_2: "cc.Sprite.addChild(): child should be non-null",
  14190. CCSpriteBatchNode_setSpriteFrame: "Invalid spriteFrameName",
  14191. CCSpriteBatchNode_setTexture: "Invalid argument: cc.Sprite texture setter expects a CCTexture2D.",
  14192. CCSpriteBatchNode_updateQuadFromSprite_2: "cc.SpriteBatchNode.updateQuadFromSprite(): sprite should be non-null",
  14193. CCSpriteBatchNode_insertQuadFromSprite_2: "cc.SpriteBatchNode.insertQuadFromSprite(): sprite should be non-null",
  14194. CCSpriteBatchNode_addChild_3: "cc.SpriteBatchNode.addChild(): child should be non-null",
  14195. TextureAtlas_initWithFile: "cocos2d: Could not open file: %s",
  14196. TextureAtlas_insertQuad: "cc.TextureAtlas.insertQuad(): invalid totalQuads",
  14197. TextureAtlas_initWithTexture: "cc.TextureAtlas.initWithTexture():texture should be non-null",
  14198. TextureAtlas_updateQuad: "cc.TextureAtlas.updateQuad(): quad should be non-null",
  14199. TextureAtlas_updateQuad_2: "cc.TextureAtlas.updateQuad(): Invalid index",
  14200. TextureAtlas_insertQuad_2: "cc.TextureAtlas.insertQuad(): Invalid index",
  14201. TextureAtlas_insertQuads: "cc.TextureAtlas.insertQuad(): Invalid index + amount",
  14202. TextureAtlas_insertQuadFromIndex: "cc.TextureAtlas.insertQuadFromIndex(): Invalid newIndex",
  14203. TextureAtlas_insertQuadFromIndex_2: "cc.TextureAtlas.insertQuadFromIndex(): Invalid fromIndex",
  14204. TextureAtlas_removeQuadAtIndex: "cc.TextureAtlas.removeQuadAtIndex(): Invalid index",
  14205. TextureAtlas_removeQuadsAtIndex: "cc.TextureAtlas.removeQuadsAtIndex(): index + amount out of bounds",
  14206. TextureAtlas_moveQuadsFromIndex: "cc.TextureAtlas.moveQuadsFromIndex(): move is out of bounds",
  14207. TextureAtlas_moveQuadsFromIndex_2: "cc.TextureAtlas.moveQuadsFromIndex(): Invalid newIndex",
  14208. TextureAtlas_moveQuadsFromIndex_3: "cc.TextureAtlas.moveQuadsFromIndex(): Invalid oldIndex",
  14209. textureCache_addPVRTCImage: "TextureCache:addPVRTCImage does not support on HTML5",
  14210. textureCache_addETCImage: "TextureCache:addPVRTCImage does not support on HTML5",
  14211. textureCache_textureForKey: "textureForKey is deprecated. Please use getTextureForKey instead.",
  14212. textureCache_addPVRImage: "addPVRImage does not support on HTML5",
  14213. textureCache_addUIImage: "cocos2d: Couldn't add UIImage in TextureCache",
  14214. textureCache_dumpCachedTextureInfo: "cocos2d: '%s' id=%s %s x %s",
  14215. textureCache_dumpCachedTextureInfo_2: "cocos2d: '%s' id= HTMLCanvasElement %s x %s",
  14216. textureCache_dumpCachedTextureInfo_3: "cocos2d: TextureCache dumpDebugInfo: %s textures, HTMLCanvasElement for %s KB (%s MB)",
  14217. textureCache_addUIImage_2: "cc.Texture.addUIImage(): image should be non-null",
  14218. Texture2D_initWithETCFile: "initWithETCFile does not support on HTML5",
  14219. Texture2D_initWithPVRFile: "initWithPVRFile does not support on HTML5",
  14220. Texture2D_initWithPVRTCData: "initWithPVRTCData does not support on HTML5",
  14221. Texture2D_addImage: "cc.Texture.addImage(): path should be non-null",
  14222. Texture2D_initWithImage: "cocos2d: cc.Texture2D. Can't create Texture. UIImage is nil",
  14223. Texture2D_initWithImage_2: "cocos2d: WARNING: Image (%s x %s) is bigger than the supported %s x %s",
  14224. Texture2D_initWithString: "initWithString isn't supported on cocos2d-html5",
  14225. Texture2D_initWithETCFile_2: "initWithETCFile does not support on HTML5",
  14226. Texture2D_initWithPVRFile_2: "initWithPVRFile does not support on HTML5",
  14227. Texture2D_initWithPVRTCData_2: "initWithPVRTCData does not support on HTML5",
  14228. Texture2D_bitsPerPixelForFormat: "bitsPerPixelForFormat: %s, cannot give useful result, it's a illegal pixel format",
  14229. Texture2D__initPremultipliedATextureWithImage: "cocos2d: cc.Texture2D: Using RGB565 texture since image has no alpha",
  14230. Texture2D_addImage_2: "cc.Texture.addImage(): path should be non-null",
  14231. Texture2D_initWithData: "NSInternalInconsistencyException",
  14232. MissingFile: "Missing file: %s",
  14233. radiansToDegress: "cc.radiansToDegress() should be called cc.radiansToDegrees()",
  14234. RectWidth: "Rect width exceeds maximum margin: %s",
  14235. RectHeight: "Rect height exceeds maximum margin: %s",
  14236. EventManager__updateListeners: "If program goes here, there should be event in dispatch.",
  14237. EventManager__updateListeners_2: "_inDispatch should be 1 here."
  14238. };
  14239. cc._logToWebPage = function (msg) {
  14240. if (!cc._canvas)
  14241. return;
  14242. var logList = cc._logList;
  14243. var doc = document;
  14244. if (!logList) {
  14245. var logDiv = doc.createElement("Div");
  14246. var logDivStyle = logDiv.style;
  14247. logDiv.setAttribute("id", "logInfoDiv");
  14248. cc._canvas.parentNode.appendChild(logDiv);
  14249. logDiv.setAttribute("width", "200");
  14250. logDiv.setAttribute("height", cc._canvas.height);
  14251. logDivStyle.zIndex = "99999";
  14252. logDivStyle.position = "absolute";
  14253. logDivStyle.top = "0";
  14254. logDivStyle.left = "0";
  14255. logList = cc._logList = doc.createElement("textarea");
  14256. var logListStyle = logList.style;
  14257. logList.setAttribute("rows", "20");
  14258. logList.setAttribute("cols", "30");
  14259. logList.setAttribute("disabled", true);
  14260. logDiv.appendChild(logList);
  14261. logListStyle.backgroundColor = "transparent";
  14262. logListStyle.borderBottom = "1px solid #cccccc";
  14263. logListStyle.borderRightWidth = "0px";
  14264. logListStyle.borderLeftWidth = "0px";
  14265. logListStyle.borderTopWidth = "0px";
  14266. logListStyle.borderTopStyle = "none";
  14267. logListStyle.borderRightStyle = "none";
  14268. logListStyle.borderLeftStyle = "none";
  14269. logListStyle.padding = "0px";
  14270. logListStyle.margin = 0;
  14271. }
  14272. logList.value = logList.value + msg + "\r\n";
  14273. logList.scrollTop = logList.scrollHeight;
  14274. };
  14275. cc._formatString = function (arg) {
  14276. if (cc.isObject(arg)) {
  14277. try {
  14278. return JSON.stringify(arg);
  14279. } catch (err) {
  14280. return "";
  14281. }
  14282. } else
  14283. return arg;
  14284. };
  14285. cc._initDebugSetting = function (mode) {
  14286. var ccGame = cc.game;
  14287. if(mode === ccGame.DEBUG_MODE_NONE)
  14288. return;
  14289. var locLog;
  14290. if(mode > ccGame.DEBUG_MODE_ERROR){
  14291. locLog = cc._logToWebPage.bind(cc);
  14292. cc.error = function(){
  14293. locLog("ERROR : " + cc.formatStr.apply(cc, arguments));
  14294. };
  14295. cc.assert = function(cond, msg) {
  14296. if (!cond && msg) {
  14297. for (var i = 2; i < arguments.length; i++)
  14298. msg = msg.replace(/(%s)|(%d)/, cc._formatString(arguments[i]));
  14299. locLog("Assert: " + msg);
  14300. }
  14301. };
  14302. if(mode !== ccGame.DEBUG_MODE_ERROR_FOR_WEB_PAGE){
  14303. cc.warn = function(){
  14304. locLog("WARN : " + cc.formatStr.apply(cc, arguments));
  14305. };
  14306. }
  14307. if(mode === ccGame.DEBUG_MODE_INFO_FOR_WEB_PAGE){
  14308. cc.log = function(){
  14309. locLog(cc.formatStr.apply(cc, arguments));
  14310. };
  14311. }
  14312. } else if(console && console.log.apply){//console is null when user doesn't open dev tool on IE9
  14313. cc.error = Function.prototype.bind.call(console.error, console);
  14314. if (console.assert) {
  14315. cc.assert = Function.prototype.bind.call(console.assert, console);
  14316. } else {
  14317. cc.assert = function (cond, msg) {
  14318. if (!cond && msg) {
  14319. for (var i = 2; i < arguments.length; i++)
  14320. msg = msg.replace(/(%s)|(%d)/, cc._formatString(arguments[i]));
  14321. throw new Error(msg);
  14322. }
  14323. };
  14324. }
  14325. if (mode !== ccGame.DEBUG_MODE_ERROR)
  14326. cc.warn = Function.prototype.bind.call(console.warn, console);
  14327. if (mode === ccGame.DEBUG_MODE_INFO)
  14328. cc.log = Function.prototype.bind.call(console.log, console);
  14329. }
  14330. };
  14331. cc.HashElement = cc.Class.extend({
  14332. actions:null,
  14333. target:null,
  14334. actionIndex:0,
  14335. currentAction:null,
  14336. currentActionSalvaged:false,
  14337. paused:false,
  14338. hh:null,
  14339. ctor:function () {
  14340. this.actions = [];
  14341. this.target = null;
  14342. this.actionIndex = 0;
  14343. this.currentAction = null;
  14344. this.currentActionSalvaged = false;
  14345. this.paused = false;
  14346. this.hh = null;
  14347. }
  14348. });
  14349. cc.ActionManager = cc.Class.extend({
  14350. _hashTargets:null,
  14351. _arrayTargets:null,
  14352. _currentTarget:null,
  14353. _currentTargetSalvaged:false,
  14354. _searchElementByTarget:function (arr, target) {
  14355. for (var k = 0; k < arr.length; k++) {
  14356. if (target === arr[k].target)
  14357. return arr[k];
  14358. }
  14359. return null;
  14360. },
  14361. ctor:function () {
  14362. this._hashTargets = {};
  14363. this._arrayTargets = [];
  14364. this._currentTarget = null;
  14365. this._currentTargetSalvaged = false;
  14366. },
  14367. addAction:function (action, target, paused) {
  14368. if(!action)
  14369. throw new Error("cc.ActionManager.addAction(): action must be non-null");
  14370. if(!target)
  14371. throw new Error("cc.ActionManager.addAction(): action must be non-null");
  14372. var element = this._hashTargets[target.__instanceId];
  14373. if (!element) {
  14374. element = new cc.HashElement();
  14375. element.paused = paused;
  14376. element.target = target;
  14377. this._hashTargets[target.__instanceId] = element;
  14378. this._arrayTargets.push(element);
  14379. }
  14380. this._actionAllocWithHashElement(element);
  14381. element.actions.push(action);
  14382. action.startWithTarget(target);
  14383. },
  14384. removeAllActions:function () {
  14385. var locTargets = this._arrayTargets;
  14386. for (var i = 0; i < locTargets.length; i++) {
  14387. var element = locTargets[i];
  14388. if (element)
  14389. this.removeAllActionsFromTarget(element.target, true);
  14390. }
  14391. },
  14392. removeAllActionsFromTarget:function (target, forceDelete) {
  14393. if (target == null)
  14394. return;
  14395. var element = this._hashTargets[target.__instanceId];
  14396. if (element) {
  14397. if (element.actions.indexOf(element.currentAction) !== -1 && !(element.currentActionSalvaged))
  14398. element.currentActionSalvaged = true;
  14399. element.actions.length = 0;
  14400. if (this._currentTarget === element && !forceDelete) {
  14401. this._currentTargetSalvaged = true;
  14402. } else {
  14403. this._deleteHashElement(element);
  14404. }
  14405. }
  14406. },
  14407. removeAction:function (action) {
  14408. if (action == null)
  14409. return;
  14410. var target = action.getOriginalTarget();
  14411. var element = this._hashTargets[target.__instanceId];
  14412. if (element) {
  14413. for (var i = 0; i < element.actions.length; i++) {
  14414. if (element.actions[i] === action) {
  14415. element.actions.splice(i, 1);
  14416. break;
  14417. }
  14418. }
  14419. } else {
  14420. cc.log(cc._LogInfos.ActionManager_removeAction);
  14421. }
  14422. },
  14423. removeActionByTag:function (tag, target) {
  14424. if(tag === cc.ACTION_TAG_INVALID)
  14425. cc.log(cc._LogInfos.ActionManager_addAction);
  14426. cc.assert(target, cc._LogInfos.ActionManager_addAction);
  14427. var element = this._hashTargets[target.__instanceId];
  14428. if (element) {
  14429. var limit = element.actions.length;
  14430. for (var i = 0; i < limit; ++i) {
  14431. var action = element.actions[i];
  14432. if (action && action.getTag() === tag && action.getOriginalTarget() === target) {
  14433. this._removeActionAtIndex(i, element);
  14434. break;
  14435. }
  14436. }
  14437. }
  14438. },
  14439. getActionByTag:function (tag, target) {
  14440. if(tag === cc.ACTION_TAG_INVALID)
  14441. cc.log(cc._LogInfos.ActionManager_getActionByTag);
  14442. var element = this._hashTargets[target.__instanceId];
  14443. if (element) {
  14444. if (element.actions != null) {
  14445. for (var i = 0; i < element.actions.length; ++i) {
  14446. var action = element.actions[i];
  14447. if (action && action.getTag() === tag)
  14448. return action;
  14449. }
  14450. }
  14451. cc.log(cc._LogInfos.ActionManager_getActionByTag_2, tag);
  14452. }
  14453. return null;
  14454. },
  14455. numberOfRunningActionsInTarget:function (target) {
  14456. var element = this._hashTargets[target.__instanceId];
  14457. if (element)
  14458. return (element.actions) ? element.actions.length : 0;
  14459. return 0;
  14460. },
  14461. pauseTarget:function (target) {
  14462. var element = this._hashTargets[target.__instanceId];
  14463. if (element)
  14464. element.paused = true;
  14465. },
  14466. resumeTarget:function (target) {
  14467. var element = this._hashTargets[target.__instanceId];
  14468. if (element)
  14469. element.paused = false;
  14470. },
  14471. pauseAllRunningActions:function(){
  14472. var idsWithActions = [];
  14473. var locTargets = this._arrayTargets;
  14474. for(var i = 0; i< locTargets.length; i++){
  14475. var element = locTargets[i];
  14476. if(element && !element.paused){
  14477. element.paused = true;
  14478. idsWithActions.push(element.target);
  14479. }
  14480. }
  14481. return idsWithActions;
  14482. },
  14483. resumeTargets:function(targetsToResume){
  14484. if(!targetsToResume)
  14485. return;
  14486. for(var i = 0 ; i< targetsToResume.length; i++){
  14487. if(targetsToResume[i])
  14488. this.resumeTarget(targetsToResume[i]);
  14489. }
  14490. },
  14491. purgeSharedManager:function () {
  14492. cc.director.getScheduler().unscheduleUpdate(this);
  14493. },
  14494. _removeActionAtIndex:function (index, element) {
  14495. var action = element.actions[index];
  14496. if ((action === element.currentAction) && (!element.currentActionSalvaged))
  14497. element.currentActionSalvaged = true;
  14498. element.actions.splice(index, 1);
  14499. if (element.actionIndex >= index)
  14500. element.actionIndex--;
  14501. if (element.actions.length === 0) {
  14502. if (this._currentTarget === element) {
  14503. this._currentTargetSalvaged = true;
  14504. } else {
  14505. this._deleteHashElement(element);
  14506. }
  14507. }
  14508. },
  14509. _deleteHashElement:function (element) {
  14510. var ret = false;
  14511. if (element) {
  14512. if(this._hashTargets[element.target.__instanceId]){
  14513. delete this._hashTargets[element.target.__instanceId];
  14514. cc.arrayRemoveObject(this._arrayTargets, element);
  14515. ret = true;
  14516. }
  14517. element.actions = null;
  14518. element.target = null;
  14519. }
  14520. return ret;
  14521. },
  14522. _actionAllocWithHashElement:function (element) {
  14523. if (element.actions == null) {
  14524. element.actions = [];
  14525. }
  14526. },
  14527. update:function (dt) {
  14528. var locTargets = this._arrayTargets , locCurrTarget;
  14529. for (var elt = 0; elt < locTargets.length; elt++) {
  14530. this._currentTarget = locTargets[elt];
  14531. locCurrTarget = this._currentTarget;
  14532. if (!locCurrTarget.paused) {
  14533. for (locCurrTarget.actionIndex = 0;
  14534. locCurrTarget.actionIndex < (locCurrTarget.actions ? locCurrTarget.actions.length : 0);
  14535. locCurrTarget.actionIndex++) {
  14536. locCurrTarget.currentAction = locCurrTarget.actions[locCurrTarget.actionIndex];
  14537. if (!locCurrTarget.currentAction)
  14538. continue;
  14539. locCurrTarget.currentActionSalvaged = false;
  14540. locCurrTarget.currentAction.step(dt * ( locCurrTarget.currentAction._speedMethod ? locCurrTarget.currentAction._speed : 1 ) );
  14541. if (locCurrTarget.currentActionSalvaged) {
  14542. locCurrTarget.currentAction = null;//release
  14543. } else if (locCurrTarget.currentAction.isDone()) {
  14544. locCurrTarget.currentAction.stop();
  14545. var action = locCurrTarget.currentAction;
  14546. locCurrTarget.currentAction = null;
  14547. this.removeAction(action);
  14548. }
  14549. locCurrTarget.currentAction = null;
  14550. }
  14551. }
  14552. if (this._currentTargetSalvaged && locCurrTarget.actions.length === 0) {
  14553. this._deleteHashElement(locCurrTarget) && elt--;
  14554. }
  14555. }
  14556. }
  14557. });
  14558. cc.ACTION_TAG_INVALID = -1;
  14559. cc.Action = cc.Class.extend({
  14560. originalTarget:null,
  14561. target:null,
  14562. tag:cc.ACTION_TAG_INVALID,
  14563. ctor:function () {
  14564. this.originalTarget = null;
  14565. this.target = null;
  14566. this.tag = cc.ACTION_TAG_INVALID;
  14567. },
  14568. copy:function () {
  14569. cc.log("copy is deprecated. Please use clone instead.");
  14570. return this.clone();
  14571. },
  14572. clone:function () {
  14573. var action = new cc.Action();
  14574. action.originalTarget = null;
  14575. action.target = null;
  14576. action.tag = this.tag;
  14577. return action;
  14578. },
  14579. isDone:function () {
  14580. return true;
  14581. },
  14582. startWithTarget:function (target) {
  14583. this.originalTarget = target;
  14584. this.target = target;
  14585. },
  14586. stop:function () {
  14587. this.target = null;
  14588. },
  14589. step:function (dt) {
  14590. cc.log("[Action step]. override me");
  14591. },
  14592. update:function (dt) {
  14593. cc.log("[Action update]. override me");
  14594. },
  14595. getTarget:function () {
  14596. return this.target;
  14597. },
  14598. setTarget:function (target) {
  14599. this.target = target;
  14600. },
  14601. getOriginalTarget:function () {
  14602. return this.originalTarget;
  14603. },
  14604. setOriginalTarget:function (originalTarget) {
  14605. this.originalTarget = originalTarget;
  14606. },
  14607. getTag:function () {
  14608. return this.tag;
  14609. },
  14610. setTag:function (tag) {
  14611. this.tag = tag;
  14612. },
  14613. retain:function () {
  14614. },
  14615. release:function () {
  14616. }
  14617. });
  14618. cc.action = function () {
  14619. return new cc.Action();
  14620. };
  14621. cc.Action.create = cc.action;
  14622. cc.FiniteTimeAction = cc.Action.extend({
  14623. _duration:0,
  14624. ctor:function () {
  14625. cc.Action.prototype.ctor.call(this);
  14626. this._duration = 0;
  14627. },
  14628. getDuration:function () {
  14629. return this._duration * (this._timesForRepeat || 1);
  14630. },
  14631. setDuration:function (duration) {
  14632. this._duration = duration;
  14633. },
  14634. reverse:function () {
  14635. cc.log("cocos2d: FiniteTimeAction#reverse: Implement me");
  14636. return null;
  14637. },
  14638. clone:function () {
  14639. return new cc.FiniteTimeAction();
  14640. }
  14641. });
  14642. cc.Speed = cc.Action.extend({
  14643. _speed:0.0,
  14644. _innerAction:null,
  14645. ctor:function (action, speed) {
  14646. cc.Action.prototype.ctor.call(this);
  14647. this._speed = 0;
  14648. this._innerAction = null;
  14649. action && this.initWithAction(action, speed);
  14650. },
  14651. getSpeed:function () {
  14652. return this._speed;
  14653. },
  14654. setSpeed:function (speed) {
  14655. this._speed = speed;
  14656. },
  14657. initWithAction:function (action, speed) {
  14658. if(!action)
  14659. throw new Error("cc.Speed.initWithAction(): action must be non nil");
  14660. this._innerAction = action;
  14661. this._speed = speed;
  14662. return true;
  14663. },
  14664. clone:function () {
  14665. var action = new cc.Speed();
  14666. action.initWithAction(this._innerAction.clone(), this._speed);
  14667. return action;
  14668. },
  14669. startWithTarget:function (target) {
  14670. cc.Action.prototype.startWithTarget.call(this, target);
  14671. this._innerAction.startWithTarget(target);
  14672. },
  14673. stop:function () {
  14674. this._innerAction.stop();
  14675. cc.Action.prototype.stop.call(this);
  14676. },
  14677. step:function (dt) {
  14678. this._innerAction.step(dt * this._speed);
  14679. },
  14680. isDone:function () {
  14681. return this._innerAction.isDone();
  14682. },
  14683. reverse:function () {
  14684. return new cc.Speed(this._innerAction.reverse(), this._speed);
  14685. },
  14686. setInnerAction:function (action) {
  14687. if (this._innerAction !== action) {
  14688. this._innerAction = action;
  14689. }
  14690. },
  14691. getInnerAction:function () {
  14692. return this._innerAction;
  14693. }
  14694. });
  14695. cc.speed = function (action, speed) {
  14696. return new cc.Speed(action, speed);
  14697. };
  14698. cc.Speed.create = cc.speed;
  14699. cc.Follow = cc.Action.extend({
  14700. _followedNode:null,
  14701. _boundarySet:false,
  14702. _boundaryFullyCovered:false,
  14703. _halfScreenSize:null,
  14704. _fullScreenSize:null,
  14705. _worldRect:null,
  14706. leftBoundary:0.0,
  14707. rightBoundary:0.0,
  14708. topBoundary:0.0,
  14709. bottomBoundary:0.0,
  14710. ctor:function (followedNode, rect) {
  14711. cc.Action.prototype.ctor.call(this);
  14712. this._followedNode = null;
  14713. this._boundarySet = false;
  14714. this._boundaryFullyCovered = false;
  14715. this._halfScreenSize = null;
  14716. this._fullScreenSize = null;
  14717. this.leftBoundary = 0.0;
  14718. this.rightBoundary = 0.0;
  14719. this.topBoundary = 0.0;
  14720. this.bottomBoundary = 0.0;
  14721. this._worldRect = cc.rect(0, 0, 0, 0);
  14722. if(followedNode)
  14723. rect ? this.initWithTarget(followedNode, rect)
  14724. : this.initWithTarget(followedNode);
  14725. },
  14726. clone:function () {
  14727. var action = new cc.Follow();
  14728. var locRect = this._worldRect;
  14729. var rect = new cc.Rect(locRect.x, locRect.y, locRect.width, locRect.height);
  14730. action.initWithTarget(this._followedNode, rect);
  14731. return action;
  14732. },
  14733. isBoundarySet:function () {
  14734. return this._boundarySet;
  14735. },
  14736. setBoudarySet:function (value) {
  14737. this._boundarySet = value;
  14738. },
  14739. initWithTarget:function (followedNode, rect) {
  14740. if(!followedNode)
  14741. throw new Error("cc.Follow.initWithAction(): followedNode must be non nil");
  14742. var _this = this;
  14743. rect = rect || cc.rect(0, 0, 0, 0);
  14744. _this._followedNode = followedNode;
  14745. _this._worldRect = rect;
  14746. _this._boundarySet = !cc._rectEqualToZero(rect);
  14747. _this._boundaryFullyCovered = false;
  14748. var winSize = cc.director.getWinSize();
  14749. _this._fullScreenSize = cc.p(winSize.width, winSize.height);
  14750. _this._halfScreenSize = cc.pMult(_this._fullScreenSize, 0.5);
  14751. if (_this._boundarySet) {
  14752. _this.leftBoundary = -((rect.x + rect.width) - _this._fullScreenSize.x);
  14753. _this.rightBoundary = -rect.x;
  14754. _this.topBoundary = -rect.y;
  14755. _this.bottomBoundary = -((rect.y + rect.height) - _this._fullScreenSize.y);
  14756. if (_this.rightBoundary < _this.leftBoundary) {
  14757. _this.rightBoundary = _this.leftBoundary = (_this.leftBoundary + _this.rightBoundary) / 2;
  14758. }
  14759. if (_this.topBoundary < _this.bottomBoundary) {
  14760. _this.topBoundary = _this.bottomBoundary = (_this.topBoundary + _this.bottomBoundary) / 2;
  14761. }
  14762. if ((_this.topBoundary === _this.bottomBoundary) && (_this.leftBoundary === _this.rightBoundary))
  14763. _this._boundaryFullyCovered = true;
  14764. }
  14765. return true;
  14766. },
  14767. step:function (dt) {
  14768. var tempPosX = this._followedNode.x;
  14769. var tempPosY = this._followedNode.y;
  14770. tempPosX = this._halfScreenSize.x - tempPosX;
  14771. tempPosY = this._halfScreenSize.y - tempPosY;
  14772. this.target._renderCmd._dirtyFlag = 0;
  14773. if (this._boundarySet) {
  14774. if (this._boundaryFullyCovered)
  14775. return;
  14776. this.target.setPosition(cc.clampf(tempPosX, this.leftBoundary, this.rightBoundary), cc.clampf(tempPosY, this.bottomBoundary, this.topBoundary));
  14777. } else {
  14778. this.target.setPosition(tempPosX, tempPosY);
  14779. }
  14780. },
  14781. isDone:function () {
  14782. return ( !this._followedNode.running );
  14783. },
  14784. stop:function () {
  14785. this.target = null;
  14786. cc.Action.prototype.stop.call(this);
  14787. }
  14788. });
  14789. cc.follow = function (followedNode, rect) {
  14790. return new cc.Follow(followedNode, rect);
  14791. };
  14792. cc.Follow.create = cc.follow;
  14793. cc.ActionInterval = cc.FiniteTimeAction.extend({
  14794. _elapsed:0,
  14795. _firstTick:false,
  14796. _easeList: null,
  14797. _timesForRepeat:1,
  14798. _repeatForever: false,
  14799. _repeatMethod: false,//Compatible with repeat class, Discard after can be deleted
  14800. _speed: 1,
  14801. _speedMethod: false,//Compatible with speed class, Discard after can be deleted
  14802. ctor:function (d) {
  14803. this._speed = 1;
  14804. this._timesForRepeat = 1;
  14805. this._repeatForever = false;
  14806. this.MAX_VALUE = 2;
  14807. this._repeatMethod = false;//Compatible with repeat class, Discard after can be deleted
  14808. this._speedMethod = false;//Compatible with repeat class, Discard after can be deleted
  14809. cc.FiniteTimeAction.prototype.ctor.call(this);
  14810. d !== undefined && this.initWithDuration(d);
  14811. },
  14812. getElapsed:function () {
  14813. return this._elapsed;
  14814. },
  14815. initWithDuration:function (d) {
  14816. this._duration = (d === 0) ? cc.FLT_EPSILON : d;
  14817. this._elapsed = 0;
  14818. this._firstTick = true;
  14819. return true;
  14820. },
  14821. isDone:function () {
  14822. return (this._elapsed >= this._duration);
  14823. },
  14824. _cloneDecoration: function(action){
  14825. action._repeatForever = this._repeatForever;
  14826. action._speed = this._speed;
  14827. action._timesForRepeat = this._timesForRepeat;
  14828. action._easeList = this._easeList;
  14829. action._speedMethod = this._speedMethod;
  14830. action._repeatMethod = this._repeatMethod;
  14831. },
  14832. _reverseEaseList: function(action){
  14833. if(this._easeList){
  14834. action._easeList = [];
  14835. for(var i=0; i<this._easeList.length; i++){
  14836. action._easeList.push(this._easeList[i].reverse());
  14837. }
  14838. }
  14839. },
  14840. clone:function () {
  14841. var action = new cc.ActionInterval(this._duration);
  14842. this._cloneDecoration(action);
  14843. return action;
  14844. },
  14845. easing: function (easeObj) {
  14846. if (this._easeList)
  14847. this._easeList.length = 0;
  14848. else
  14849. this._easeList = [];
  14850. for (var i = 0; i < arguments.length; i++)
  14851. this._easeList.push(arguments[i]);
  14852. return this;
  14853. },
  14854. _computeEaseTime: function (dt) {
  14855. var locList = this._easeList;
  14856. if ((!locList) || (locList.length === 0))
  14857. return dt;
  14858. for (var i = 0, n = locList.length; i < n; i++)
  14859. dt = locList[i].easing(dt);
  14860. return dt;
  14861. },
  14862. step:function (dt) {
  14863. if (this._firstTick) {
  14864. this._firstTick = false;
  14865. this._elapsed = 0;
  14866. } else
  14867. this._elapsed += dt;
  14868. var t = this._elapsed / (this._duration > 0.0000001192092896 ? this._duration : 0.0000001192092896);
  14869. t = (1 > t ? t : 1);
  14870. this.update(t > 0 ? t : 0);
  14871. if(this._repeatMethod && this._timesForRepeat > 1 && this.isDone()){
  14872. if(!this._repeatForever){
  14873. this._timesForRepeat--;
  14874. }
  14875. this.startWithTarget(this.target);
  14876. this.step(this._elapsed - this._duration);
  14877. }
  14878. },
  14879. startWithTarget:function (target) {
  14880. cc.Action.prototype.startWithTarget.call(this, target);
  14881. this._elapsed = 0;
  14882. this._firstTick = true;
  14883. },
  14884. reverse:function () {
  14885. cc.log("cc.IntervalAction: reverse not implemented.");
  14886. return null;
  14887. },
  14888. setAmplitudeRate:function (amp) {
  14889. cc.log("cc.ActionInterval.setAmplitudeRate(): it should be overridden in subclass.");
  14890. },
  14891. getAmplitudeRate:function () {
  14892. cc.log("cc.ActionInterval.getAmplitudeRate(): it should be overridden in subclass.");
  14893. return 0;
  14894. },
  14895. speed: function(speed){
  14896. if(speed <= 0){
  14897. cc.log("The speed parameter error");
  14898. return this;
  14899. }
  14900. this._speedMethod = true;//Compatible with repeat class, Discard after can be deleted
  14901. this._speed *= speed;
  14902. return this;
  14903. },
  14904. getSpeed: function(){
  14905. return this._speed;
  14906. },
  14907. setSpeed: function(speed){
  14908. this._speed = speed;
  14909. return this;
  14910. },
  14911. repeat: function(times){
  14912. times = Math.round(times);
  14913. if(isNaN(times) || times < 1){
  14914. cc.log("The repeat parameter error");
  14915. return this;
  14916. }
  14917. this._repeatMethod = true;//Compatible with repeat class, Discard after can be deleted
  14918. this._timesForRepeat *= times;
  14919. return this;
  14920. },
  14921. repeatForever: function(){
  14922. this._repeatMethod = true;//Compatible with repeat class, Discard after can be deleted
  14923. this._timesForRepeat = this.MAX_VALUE;
  14924. this._repeatForever = true;
  14925. return this;
  14926. }
  14927. });
  14928. cc.actionInterval = function (d) {
  14929. return new cc.ActionInterval(d);
  14930. };
  14931. cc.ActionInterval.create = cc.actionInterval;
  14932. cc.Sequence = cc.ActionInterval.extend({
  14933. _actions:null,
  14934. _split:null,
  14935. _last:0,
  14936. ctor:function (tempArray) {
  14937. cc.ActionInterval.prototype.ctor.call(this);
  14938. this._actions = [];
  14939. var paramArray = (tempArray instanceof Array) ? tempArray : arguments;
  14940. var last = paramArray.length - 1;
  14941. if ((last >= 0) && (paramArray[last] == null))
  14942. cc.log("parameters should not be ending with null in Javascript");
  14943. if (last >= 0) {
  14944. var prev = paramArray[0], action1;
  14945. for (var i = 1; i < last; i++) {
  14946. if (paramArray[i]) {
  14947. action1 = prev;
  14948. prev = cc.Sequence._actionOneTwo(action1, paramArray[i]);
  14949. }
  14950. }
  14951. this.initWithTwoActions(prev, paramArray[last]);
  14952. }
  14953. },
  14954. initWithTwoActions:function (actionOne, actionTwo) {
  14955. if(!actionOne || !actionTwo)
  14956. throw new Error("cc.Sequence.initWithTwoActions(): arguments must all be non nil");
  14957. var d = actionOne._duration + actionTwo._duration;
  14958. this.initWithDuration(d);
  14959. this._actions[0] = actionOne;
  14960. this._actions[1] = actionTwo;
  14961. return true;
  14962. },
  14963. clone:function () {
  14964. var action = new cc.Sequence();
  14965. this._cloneDecoration(action);
  14966. action.initWithTwoActions(this._actions[0].clone(), this._actions[1].clone());
  14967. return action;
  14968. },
  14969. startWithTarget:function (target) {
  14970. cc.ActionInterval.prototype.startWithTarget.call(this, target);
  14971. this._split = this._actions[0]._duration / this._duration;
  14972. this._last = -1;
  14973. },
  14974. stop:function () {
  14975. if (this._last !== -1)
  14976. this._actions[this._last].stop();
  14977. cc.Action.prototype.stop.call(this);
  14978. },
  14979. update:function (dt) {
  14980. var new_t, found = 0;
  14981. var locSplit = this._split, locActions = this._actions, locLast = this._last, actionFound;
  14982. dt = this._computeEaseTime(dt);
  14983. if (dt < locSplit) {
  14984. new_t = (locSplit !== 0) ? dt / locSplit : 1;
  14985. if (found === 0 && locLast === 1) {
  14986. locActions[1].update(0);
  14987. locActions[1].stop();
  14988. }
  14989. } else {
  14990. found = 1;
  14991. new_t = (locSplit === 1) ? 1 : (dt - locSplit) / (1 - locSplit);
  14992. if (locLast === -1) {
  14993. locActions[0].startWithTarget(this.target);
  14994. locActions[0].update(1);
  14995. locActions[0].stop();
  14996. }
  14997. if (!locLast) {
  14998. locActions[0].update(1);
  14999. locActions[0].stop();
  15000. }
  15001. }
  15002. actionFound = locActions[found];
  15003. if (locLast === found && actionFound.isDone())
  15004. return;
  15005. if (locLast !== found)
  15006. actionFound.startWithTarget(this.target);
  15007. new_t = new_t * actionFound._timesForRepeat;
  15008. actionFound.update(new_t > 1 ? new_t % 1 : new_t);
  15009. this._last = found;
  15010. },
  15011. reverse:function () {
  15012. var action = cc.Sequence._actionOneTwo(this._actions[1].reverse(), this._actions[0].reverse());
  15013. this._cloneDecoration(action);
  15014. this._reverseEaseList(action);
  15015. return action;
  15016. }
  15017. });
  15018. cc.sequence = function (tempArray) {
  15019. var paramArray = (tempArray instanceof Array) ? tempArray : arguments;
  15020. if ((paramArray.length > 0) && (paramArray[paramArray.length - 1] == null))
  15021. cc.log("parameters should not be ending with null in Javascript");
  15022. var result, current, i, repeat;
  15023. while(paramArray && paramArray.length > 0){
  15024. current = Array.prototype.shift.call(paramArray);
  15025. repeat = current._timesForRepeat || 1;
  15026. current._repeatMethod = false;
  15027. current._timesForRepeat = 1;
  15028. i = 0;
  15029. if(!result){
  15030. result = current;
  15031. i = 1;
  15032. }
  15033. for(i; i<repeat; i++){
  15034. result = cc.Sequence._actionOneTwo(result, current);
  15035. }
  15036. }
  15037. return result;
  15038. };
  15039. cc.Sequence.create = cc.sequence;
  15040. cc.Sequence._actionOneTwo = function (actionOne, actionTwo) {
  15041. var sequence = new cc.Sequence();
  15042. sequence.initWithTwoActions(actionOne, actionTwo);
  15043. return sequence;
  15044. };
  15045. cc.Repeat = cc.ActionInterval.extend({
  15046. _times:0,
  15047. _total:0,
  15048. _nextDt:0,
  15049. _actionInstant:false,
  15050. _innerAction:null,
  15051. ctor: function (action, times) {
  15052. cc.ActionInterval.prototype.ctor.call(this);
  15053. times !== undefined && this.initWithAction(action, times);
  15054. },
  15055. initWithAction:function (action, times) {
  15056. var duration = action._duration * times;
  15057. if (this.initWithDuration(duration)) {
  15058. this._times = times;
  15059. this._innerAction = action;
  15060. if (action instanceof cc.ActionInstant){
  15061. this._actionInstant = true;
  15062. this._times -= 1;
  15063. }
  15064. this._total = 0;
  15065. return true;
  15066. }
  15067. return false;
  15068. },
  15069. clone:function () {
  15070. var action = new cc.Repeat();
  15071. this._cloneDecoration(action);
  15072. action.initWithAction(this._innerAction.clone(), this._times);
  15073. return action;
  15074. },
  15075. startWithTarget:function (target) {
  15076. this._total = 0;
  15077. this._nextDt = this._innerAction._duration / this._duration;
  15078. cc.ActionInterval.prototype.startWithTarget.call(this, target);
  15079. this._innerAction.startWithTarget(target);
  15080. },
  15081. stop:function () {
  15082. this._innerAction.stop();
  15083. cc.Action.prototype.stop.call(this);
  15084. },
  15085. update:function (dt) {
  15086. dt = this._computeEaseTime(dt);
  15087. var locInnerAction = this._innerAction;
  15088. var locDuration = this._duration;
  15089. var locTimes = this._times;
  15090. var locNextDt = this._nextDt;
  15091. if (dt >= locNextDt) {
  15092. while (dt > locNextDt && this._total < locTimes) {
  15093. locInnerAction.update(1);
  15094. this._total++;
  15095. locInnerAction.stop();
  15096. locInnerAction.startWithTarget(this.target);
  15097. locNextDt += locInnerAction._duration / locDuration;
  15098. this._nextDt = locNextDt;
  15099. }
  15100. if (dt >= 1.0 && this._total < locTimes)
  15101. this._total++;
  15102. if (!this._actionInstant) {
  15103. if (this._total === locTimes) {
  15104. locInnerAction.update(1);
  15105. locInnerAction.stop();
  15106. } else {
  15107. locInnerAction.update(dt - (locNextDt - locInnerAction._duration / locDuration));
  15108. }
  15109. }
  15110. } else {
  15111. locInnerAction.update((dt * locTimes) % 1.0);
  15112. }
  15113. },
  15114. isDone:function () {
  15115. return this._total === this._times;
  15116. },
  15117. reverse:function () {
  15118. var action = new cc.Repeat(this._innerAction.reverse(), this._times);
  15119. this._cloneDecoration(action);
  15120. this._reverseEaseList(action);
  15121. return action;
  15122. },
  15123. setInnerAction:function (action) {
  15124. if (this._innerAction !== action) {
  15125. this._innerAction = action;
  15126. }
  15127. },
  15128. getInnerAction:function () {
  15129. return this._innerAction;
  15130. }
  15131. });
  15132. cc.repeat = function (action, times) {
  15133. return new cc.Repeat(action, times);
  15134. };
  15135. cc.Repeat.create = cc.repeat;
  15136. cc.RepeatForever = cc.ActionInterval.extend({
  15137. _innerAction:null,
  15138. ctor:function (action) {
  15139. cc.ActionInterval.prototype.ctor.call(this);
  15140. this._innerAction = null;
  15141. action && this.initWithAction(action);
  15142. },
  15143. initWithAction:function (action) {
  15144. if(!action)
  15145. throw new Error("cc.RepeatForever.initWithAction(): action must be non null");
  15146. this._innerAction = action;
  15147. return true;
  15148. },
  15149. clone:function () {
  15150. var action = new cc.RepeatForever();
  15151. this._cloneDecoration(action);
  15152. action.initWithAction(this._innerAction.clone());
  15153. return action;
  15154. },
  15155. startWithTarget:function (target) {
  15156. cc.ActionInterval.prototype.startWithTarget.call(this, target);
  15157. this._innerAction.startWithTarget(target);
  15158. },
  15159. step:function (dt) {
  15160. var locInnerAction = this._innerAction;
  15161. locInnerAction.step(dt);
  15162. if (locInnerAction.isDone()) {
  15163. locInnerAction.startWithTarget(this.target);
  15164. locInnerAction.step(locInnerAction.getElapsed() - locInnerAction._duration);
  15165. }
  15166. },
  15167. isDone:function () {
  15168. return false;
  15169. },
  15170. reverse:function () {
  15171. var action = new cc.RepeatForever(this._innerAction.reverse());
  15172. this._cloneDecoration(action);
  15173. this._reverseEaseList(action);
  15174. return action;
  15175. },
  15176. setInnerAction:function (action) {
  15177. if (this._innerAction !== action) {
  15178. this._innerAction = action;
  15179. }
  15180. },
  15181. getInnerAction:function () {
  15182. return this._innerAction;
  15183. }
  15184. });
  15185. cc.repeatForever = function (action) {
  15186. return new cc.RepeatForever(action);
  15187. };
  15188. cc.RepeatForever.create = cc.repeatForever;
  15189. cc.Spawn = cc.ActionInterval.extend({
  15190. _one:null,
  15191. _two:null,
  15192. ctor:function (tempArray) {
  15193. cc.ActionInterval.prototype.ctor.call(this);
  15194. this._one = null;
  15195. this._two = null;
  15196. var paramArray = (tempArray instanceof Array) ? tempArray : arguments;
  15197. var last = paramArray.length - 1;
  15198. if ((last >= 0) && (paramArray[last] == null))
  15199. cc.log("parameters should not be ending with null in Javascript");
  15200. if (last >= 0) {
  15201. var prev = paramArray[0], action1;
  15202. for (var i = 1; i < last; i++) {
  15203. if (paramArray[i]) {
  15204. action1 = prev;
  15205. prev = cc.Spawn._actionOneTwo(action1, paramArray[i]);
  15206. }
  15207. }
  15208. this.initWithTwoActions(prev, paramArray[last]);
  15209. }
  15210. },
  15211. initWithTwoActions:function (action1, action2) {
  15212. if(!action1 || !action2)
  15213. throw new Error("cc.Spawn.initWithTwoActions(): arguments must all be non null");
  15214. var ret = false;
  15215. var d1 = action1._duration;
  15216. var d2 = action2._duration;
  15217. if (this.initWithDuration(Math.max(d1, d2))) {
  15218. this._one = action1;
  15219. this._two = action2;
  15220. if (d1 > d2) {
  15221. this._two = cc.Sequence._actionOneTwo(action2, cc.delayTime(d1 - d2));
  15222. } else if (d1 < d2) {
  15223. this._one = cc.Sequence._actionOneTwo(action1, cc.delayTime(d2 - d1));
  15224. }
  15225. ret = true;
  15226. }
  15227. return ret;
  15228. },
  15229. clone:function () {
  15230. var action = new cc.Spawn();
  15231. this._cloneDecoration(action);
  15232. action.initWithTwoActions(this._one.clone(), this._two.clone());
  15233. return action;
  15234. },
  15235. startWithTarget:function (target) {
  15236. cc.ActionInterval.prototype.startWithTarget.call(this, target);
  15237. this._one.startWithTarget(target);
  15238. this._two.startWithTarget(target);
  15239. },
  15240. stop:function () {
  15241. this._one.stop();
  15242. this._two.stop();
  15243. cc.Action.prototype.stop.call(this);
  15244. },
  15245. update:function (dt) {
  15246. dt = this._computeEaseTime(dt);
  15247. if (this._one)
  15248. this._one.update(dt);
  15249. if (this._two)
  15250. this._two.update(dt);
  15251. },
  15252. reverse:function () {
  15253. var action = cc.Spawn._actionOneTwo(this._one.reverse(), this._two.reverse());
  15254. this._cloneDecoration(action);
  15255. this._reverseEaseList(action);
  15256. return action;
  15257. }
  15258. });
  15259. cc.spawn = function (tempArray) {
  15260. var paramArray = (tempArray instanceof Array) ? tempArray : arguments;
  15261. if ((paramArray.length > 0) && (paramArray[paramArray.length - 1] == null))
  15262. cc.log("parameters should not be ending with null in Javascript");
  15263. var prev = paramArray[0];
  15264. for (var i = 1; i < paramArray.length; i++) {
  15265. if (paramArray[i] != null)
  15266. prev = cc.Spawn._actionOneTwo(prev, paramArray[i]);
  15267. }
  15268. return prev;
  15269. };
  15270. cc.Spawn.create = cc.spawn;
  15271. cc.Spawn._actionOneTwo = function (action1, action2) {
  15272. var pSpawn = new cc.Spawn();
  15273. pSpawn.initWithTwoActions(action1, action2);
  15274. return pSpawn;
  15275. };
  15276. cc.RotateTo = cc.ActionInterval.extend({
  15277. _dstAngleX:0,
  15278. _startAngleX:0,
  15279. _diffAngleX:0,
  15280. _dstAngleY:0,
  15281. _startAngleY:0,
  15282. _diffAngleY:0,
  15283. ctor:function (duration, deltaAngleX, deltaAngleY) {
  15284. cc.ActionInterval.prototype.ctor.call(this);
  15285. deltaAngleX !== undefined && this.initWithDuration(duration, deltaAngleX, deltaAngleY);
  15286. },
  15287. initWithDuration:function (duration, deltaAngleX, deltaAngleY) {
  15288. if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) {
  15289. this._dstAngleX = deltaAngleX || 0;
  15290. this._dstAngleY = deltaAngleY || this._dstAngleX;
  15291. return true;
  15292. }
  15293. return false;
  15294. },
  15295. clone:function () {
  15296. var action = new cc.RotateTo();
  15297. this._cloneDecoration(action);
  15298. action.initWithDuration(this._duration, this._dstAngleX, this._dstAngleY);
  15299. return action;
  15300. },
  15301. startWithTarget:function (target) {
  15302. cc.ActionInterval.prototype.startWithTarget.call(this, target);
  15303. var locStartAngleX = target.rotationX % 360.0;
  15304. var locDiffAngleX = this._dstAngleX - locStartAngleX;
  15305. if (locDiffAngleX > 180)
  15306. locDiffAngleX -= 360;
  15307. if (locDiffAngleX < -180)
  15308. locDiffAngleX += 360;
  15309. this._startAngleX = locStartAngleX;
  15310. this._diffAngleX = locDiffAngleX;
  15311. this._startAngleY = target.rotationY % 360.0;
  15312. var locDiffAngleY = this._dstAngleY - this._startAngleY;
  15313. if (locDiffAngleY > 180)
  15314. locDiffAngleY -= 360;
  15315. if (locDiffAngleY < -180)
  15316. locDiffAngleY += 360;
  15317. this._diffAngleY = locDiffAngleY;
  15318. },
  15319. reverse:function () {
  15320. cc.log("cc.RotateTo.reverse(): it should be overridden in subclass.");
  15321. },
  15322. update:function (dt) {
  15323. dt = this._computeEaseTime(dt);
  15324. if (this.target) {
  15325. this.target.rotationX = this._startAngleX + this._diffAngleX * dt;
  15326. this.target.rotationY = this._startAngleY + this._diffAngleY * dt;
  15327. }
  15328. }
  15329. });
  15330. cc.rotateTo = function (duration, deltaAngleX, deltaAngleY) {
  15331. return new cc.RotateTo(duration, deltaAngleX, deltaAngleY);
  15332. };
  15333. cc.RotateTo.create = cc.rotateTo;
  15334. cc.RotateBy = cc.ActionInterval.extend({
  15335. _angleX:0,
  15336. _startAngleX:0,
  15337. _angleY:0,
  15338. _startAngleY:0,
  15339. ctor: function (duration, deltaAngleX, deltaAngleY) {
  15340. cc.ActionInterval.prototype.ctor.call(this);
  15341. deltaAngleX !== undefined && this.initWithDuration(duration, deltaAngleX, deltaAngleY);
  15342. },
  15343. initWithDuration:function (duration, deltaAngleX, deltaAngleY) {
  15344. if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) {
  15345. this._angleX = deltaAngleX || 0;
  15346. this._angleY = deltaAngleY || this._angleX;
  15347. return true;
  15348. }
  15349. return false;
  15350. },
  15351. clone:function () {
  15352. var action = new cc.RotateBy();
  15353. this._cloneDecoration(action);
  15354. action.initWithDuration(this._duration, this._angleX, this._angleY);
  15355. return action;
  15356. },
  15357. startWithTarget:function (target) {
  15358. cc.ActionInterval.prototype.startWithTarget.call(this, target);
  15359. this._startAngleX = target.rotationX;
  15360. this._startAngleY = target.rotationY;
  15361. },
  15362. update:function (dt) {
  15363. dt = this._computeEaseTime(dt);
  15364. if (this.target) {
  15365. this.target.rotationX = this._startAngleX + this._angleX * dt;
  15366. this.target.rotationY = this._startAngleY + this._angleY * dt;
  15367. }
  15368. },
  15369. reverse:function () {
  15370. var action = new cc.RotateBy(this._duration, -this._angleX, -this._angleY);
  15371. this._cloneDecoration(action);
  15372. this._reverseEaseList(action);
  15373. return action;
  15374. }
  15375. });
  15376. cc.rotateBy = function (duration, deltaAngleX, deltaAngleY) {
  15377. return new cc.RotateBy(duration, deltaAngleX, deltaAngleY);
  15378. };
  15379. cc.RotateBy.create = cc.rotateBy;
  15380. cc.MoveBy = cc.ActionInterval.extend({
  15381. _positionDelta:null,
  15382. _startPosition:null,
  15383. _previousPosition:null,
  15384. ctor:function (duration, deltaPos, deltaY) {
  15385. cc.ActionInterval.prototype.ctor.call(this);
  15386. this._positionDelta = cc.p(0, 0);
  15387. this._startPosition = cc.p(0, 0);
  15388. this._previousPosition = cc.p(0, 0);
  15389. deltaPos !== undefined && this.initWithDuration(duration, deltaPos, deltaY);
  15390. },
  15391. initWithDuration:function (duration, position, y) {
  15392. if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) {
  15393. if(position.x !== undefined) {
  15394. y = position.y;
  15395. position = position.x;
  15396. }
  15397. this._positionDelta.x = position;
  15398. this._positionDelta.y = y;
  15399. return true;
  15400. }
  15401. return false;
  15402. },
  15403. clone:function () {
  15404. var action = new cc.MoveBy();
  15405. this._cloneDecoration(action);
  15406. action.initWithDuration(this._duration, this._positionDelta);
  15407. return action;
  15408. },
  15409. startWithTarget:function (target) {
  15410. cc.ActionInterval.prototype.startWithTarget.call(this, target);
  15411. var locPosX = target.getPositionX();
  15412. var locPosY = target.getPositionY();
  15413. this._previousPosition.x = locPosX;
  15414. this._previousPosition.y = locPosY;
  15415. this._startPosition.x = locPosX;
  15416. this._startPosition.y = locPosY;
  15417. },
  15418. update:function (dt) {
  15419. dt = this._computeEaseTime(dt);
  15420. if (this.target) {
  15421. var x = this._positionDelta.x * dt;
  15422. var y = this._positionDelta.y * dt;
  15423. var locStartPosition = this._startPosition;
  15424. if (cc.ENABLE_STACKABLE_ACTIONS) {
  15425. var targetX = this.target.getPositionX();
  15426. var targetY = this.target.getPositionY();
  15427. var locPreviousPosition = this._previousPosition;
  15428. locStartPosition.x = locStartPosition.x + targetX - locPreviousPosition.x;
  15429. locStartPosition.y = locStartPosition.y + targetY - locPreviousPosition.y;
  15430. x = x + locStartPosition.x;
  15431. y = y + locStartPosition.y;
  15432. locPreviousPosition.x = x;
  15433. locPreviousPosition.y = y;
  15434. this.target.setPosition(x, y);
  15435. } else {
  15436. this.target.setPosition(locStartPosition.x + x, locStartPosition.y + y);
  15437. }
  15438. }
  15439. },
  15440. reverse:function () {
  15441. var action = new cc.MoveBy(this._duration, cc.p(-this._positionDelta.x, -this._positionDelta.y));
  15442. this._cloneDecoration(action);
  15443. this._reverseEaseList(action);
  15444. return action;
  15445. }
  15446. });
  15447. cc.moveBy = function (duration, deltaPos, deltaY) {
  15448. return new cc.MoveBy(duration, deltaPos, deltaY);
  15449. };
  15450. cc.MoveBy.create = cc.moveBy;
  15451. cc.MoveTo = cc.MoveBy.extend({
  15452. _endPosition:null,
  15453. ctor:function (duration, position, y) {
  15454. cc.MoveBy.prototype.ctor.call(this);
  15455. this._endPosition = cc.p(0, 0);
  15456. position !== undefined && this.initWithDuration(duration, position, y);
  15457. },
  15458. initWithDuration:function (duration, position, y) {
  15459. if (cc.MoveBy.prototype.initWithDuration.call(this, duration, position, y)) {
  15460. if(position.x !== undefined) {
  15461. y = position.y;
  15462. position = position.x;
  15463. }
  15464. this._endPosition.x = position;
  15465. this._endPosition.y = y;
  15466. return true;
  15467. }
  15468. return false;
  15469. },
  15470. clone:function () {
  15471. var action = new cc.MoveTo();
  15472. this._cloneDecoration(action);
  15473. action.initWithDuration(this._duration, this._endPosition);
  15474. return action;
  15475. },
  15476. startWithTarget:function (target) {
  15477. cc.MoveBy.prototype.startWithTarget.call(this, target);
  15478. this._positionDelta.x = this._endPosition.x - target.getPositionX();
  15479. this._positionDelta.y = this._endPosition.y - target.getPositionY();
  15480. }
  15481. });
  15482. cc.moveTo = function (duration, position, y) {
  15483. return new cc.MoveTo(duration, position, y);
  15484. };
  15485. cc.MoveTo.create = cc.moveTo;
  15486. cc.SkewTo = cc.ActionInterval.extend({
  15487. _skewX:0,
  15488. _skewY:0,
  15489. _startSkewX:0,
  15490. _startSkewY:0,
  15491. _endSkewX:0,
  15492. _endSkewY:0,
  15493. _deltaX:0,
  15494. _deltaY:0,
  15495. ctor: function (t, sx, sy) {
  15496. cc.ActionInterval.prototype.ctor.call(this);
  15497. sy !== undefined && this.initWithDuration(t, sx, sy);
  15498. },
  15499. initWithDuration:function (t, sx, sy) {
  15500. var ret = false;
  15501. if (cc.ActionInterval.prototype.initWithDuration.call(this, t)) {
  15502. this._endSkewX = sx;
  15503. this._endSkewY = sy;
  15504. ret = true;
  15505. }
  15506. return ret;
  15507. },
  15508. clone:function () {
  15509. var action = new cc.SkewTo();
  15510. this._cloneDecoration(action);
  15511. action.initWithDuration(this._duration, this._endSkewX, this._endSkewY);
  15512. return action;
  15513. },
  15514. startWithTarget:function (target) {
  15515. cc.ActionInterval.prototype.startWithTarget.call(this, target);
  15516. this._startSkewX = target.skewX % 180;
  15517. this._deltaX = this._endSkewX - this._startSkewX;
  15518. if (this._deltaX > 180)
  15519. this._deltaX -= 360;
  15520. if (this._deltaX < -180)
  15521. this._deltaX += 360;
  15522. this._startSkewY = target.skewY % 360;
  15523. this._deltaY = this._endSkewY - this._startSkewY;
  15524. if (this._deltaY > 180)
  15525. this._deltaY -= 360;
  15526. if (this._deltaY < -180)
  15527. this._deltaY += 360;
  15528. },
  15529. update:function (dt) {
  15530. dt = this._computeEaseTime(dt);
  15531. this.target.skewX = this._startSkewX + this._deltaX * dt;
  15532. this.target.skewY = this._startSkewY + this._deltaY * dt;
  15533. }
  15534. });
  15535. cc.skewTo = function (t, sx, sy) {
  15536. return new cc.SkewTo(t, sx, sy);
  15537. };
  15538. cc.SkewTo.create = cc.skewTo;
  15539. cc.SkewBy = cc.SkewTo.extend({
  15540. ctor: function(t, sx, sy) {
  15541. cc.SkewTo.prototype.ctor.call(this);
  15542. sy !== undefined && this.initWithDuration(t, sx, sy);
  15543. },
  15544. initWithDuration:function (t, deltaSkewX, deltaSkewY) {
  15545. var ret = false;
  15546. if (cc.SkewTo.prototype.initWithDuration.call(this, t, deltaSkewX, deltaSkewY)) {
  15547. this._skewX = deltaSkewX;
  15548. this._skewY = deltaSkewY;
  15549. ret = true;
  15550. }
  15551. return ret;
  15552. },
  15553. clone:function () {
  15554. var action = new cc.SkewBy();
  15555. this._cloneDecoration(action);
  15556. action.initWithDuration(this._duration, this._skewX, this._skewY);
  15557. return action;
  15558. },
  15559. startWithTarget:function (target) {
  15560. cc.SkewTo.prototype.startWithTarget.call(this, target);
  15561. this._deltaX = this._skewX;
  15562. this._deltaY = this._skewY;
  15563. this._endSkewX = this._startSkewX + this._deltaX;
  15564. this._endSkewY = this._startSkewY + this._deltaY;
  15565. },
  15566. reverse:function () {
  15567. var action = new cc.SkewBy(this._duration, -this._skewX, -this._skewY);
  15568. this._cloneDecoration(action);
  15569. this._reverseEaseList(action);
  15570. return action;
  15571. }
  15572. });
  15573. cc.skewBy = function (t, sx, sy) {
  15574. return new cc.SkewBy(t, sx, sy);
  15575. };
  15576. cc.SkewBy.create = cc.skewBy;
  15577. cc.JumpBy = cc.ActionInterval.extend({
  15578. _startPosition:null,
  15579. _delta:null,
  15580. _height:0,
  15581. _jumps:0,
  15582. _previousPosition:null,
  15583. ctor:function (duration, position, y, height, jumps) {
  15584. cc.ActionInterval.prototype.ctor.call(this);
  15585. this._startPosition = cc.p(0, 0);
  15586. this._previousPosition = cc.p(0, 0);
  15587. this._delta = cc.p(0, 0);
  15588. height !== undefined && this.initWithDuration(duration, position, y, height, jumps);
  15589. },
  15590. initWithDuration:function (duration, position, y, height, jumps) {
  15591. if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) {
  15592. if (jumps === undefined) {
  15593. jumps = height;
  15594. height = y;
  15595. y = position.y;
  15596. position = position.x;
  15597. }
  15598. this._delta.x = position;
  15599. this._delta.y = y;
  15600. this._height = height;
  15601. this._jumps = jumps;
  15602. return true;
  15603. }
  15604. return false;
  15605. },
  15606. clone:function () {
  15607. var action = new cc.JumpBy();
  15608. this._cloneDecoration(action);
  15609. action.initWithDuration(this._duration, this._delta, this._height, this._jumps);
  15610. return action;
  15611. },
  15612. startWithTarget:function (target) {
  15613. cc.ActionInterval.prototype.startWithTarget.call(this, target);
  15614. var locPosX = target.getPositionX();
  15615. var locPosY = target.getPositionY();
  15616. this._previousPosition.x = locPosX;
  15617. this._previousPosition.y = locPosY;
  15618. this._startPosition.x = locPosX;
  15619. this._startPosition.y = locPosY;
  15620. },
  15621. update:function (dt) {
  15622. dt = this._computeEaseTime(dt);
  15623. if (this.target) {
  15624. var frac = dt * this._jumps % 1.0;
  15625. var y = this._height * 4 * frac * (1 - frac);
  15626. y += this._delta.y * dt;
  15627. var x = this._delta.x * dt;
  15628. var locStartPosition = this._startPosition;
  15629. if (cc.ENABLE_STACKABLE_ACTIONS) {
  15630. var targetX = this.target.getPositionX();
  15631. var targetY = this.target.getPositionY();
  15632. var locPreviousPosition = this._previousPosition;
  15633. locStartPosition.x = locStartPosition.x + targetX - locPreviousPosition.x;
  15634. locStartPosition.y = locStartPosition.y + targetY - locPreviousPosition.y;
  15635. x = x + locStartPosition.x;
  15636. y = y + locStartPosition.y;
  15637. locPreviousPosition.x = x;
  15638. locPreviousPosition.y = y;
  15639. this.target.setPosition(x, y);
  15640. } else {
  15641. this.target.setPosition(locStartPosition.x + x, locStartPosition.y + y);
  15642. }
  15643. }
  15644. },
  15645. reverse:function () {
  15646. var action = new cc.JumpBy(this._duration, cc.p(-this._delta.x, -this._delta.y), this._height, this._jumps);
  15647. this._cloneDecoration(action);
  15648. this._reverseEaseList(action);
  15649. return action;
  15650. }
  15651. });
  15652. cc.jumpBy = function (duration, position, y, height, jumps) {
  15653. return new cc.JumpBy(duration, position, y, height, jumps);
  15654. };
  15655. cc.JumpBy.create = cc.jumpBy;
  15656. cc.JumpTo = cc.JumpBy.extend({
  15657. _endPosition:null,
  15658. ctor:function (duration, position, y, height, jumps) {
  15659. cc.JumpBy.prototype.ctor.call(this);
  15660. this._endPosition = cc.p(0, 0);
  15661. height !== undefined && this.initWithDuration(duration, position, y, height, jumps);
  15662. },
  15663. initWithDuration:function (duration, position, y, height, jumps) {
  15664. if (cc.JumpBy.prototype.initWithDuration.call(this, duration, position, y, height, jumps)) {
  15665. if (jumps === undefined) {
  15666. y = position.y;
  15667. position = position.x;
  15668. }
  15669. this._endPosition.x = position;
  15670. this._endPosition.y = y;
  15671. return true;
  15672. }
  15673. return false;
  15674. },
  15675. startWithTarget:function (target) {
  15676. cc.JumpBy.prototype.startWithTarget.call(this, target);
  15677. this._delta.x = this._endPosition.x - this._startPosition.x;
  15678. this._delta.y = this._endPosition.y - this._startPosition.y;
  15679. },
  15680. clone:function () {
  15681. var action = new cc.JumpTo();
  15682. this._cloneDecoration(action);
  15683. action.initWithDuration(this._duration, this._endPosition, this._height, this._jumps);
  15684. return action;
  15685. }
  15686. });
  15687. cc.jumpTo = function (duration, position, y, height, jumps) {
  15688. return new cc.JumpTo(duration, position, y, height, jumps);
  15689. };
  15690. cc.JumpTo.create = cc.jumpTo;
  15691. cc.bezierAt = function (a, b, c, d, t) {
  15692. return (Math.pow(1 - t, 3) * a +
  15693. 3 * t * (Math.pow(1 - t, 2)) * b +
  15694. 3 * Math.pow(t, 2) * (1 - t) * c +
  15695. Math.pow(t, 3) * d );
  15696. };
  15697. cc.BezierBy = cc.ActionInterval.extend({
  15698. _config:null,
  15699. _startPosition:null,
  15700. _previousPosition:null,
  15701. ctor:function (t, c) {
  15702. cc.ActionInterval.prototype.ctor.call(this);
  15703. this._config = [];
  15704. this._startPosition = cc.p(0, 0);
  15705. this._previousPosition = cc.p(0, 0);
  15706. c && this.initWithDuration(t, c);
  15707. },
  15708. initWithDuration:function (t, c) {
  15709. if (cc.ActionInterval.prototype.initWithDuration.call(this, t)) {
  15710. this._config = c;
  15711. return true;
  15712. }
  15713. return false;
  15714. },
  15715. clone:function () {
  15716. var action = new cc.BezierBy();
  15717. this._cloneDecoration(action);
  15718. var newConfigs = [];
  15719. for (var i = 0; i < this._config.length; i++) {
  15720. var selConf = this._config[i];
  15721. newConfigs.push(cc.p(selConf.x, selConf.y));
  15722. }
  15723. action.initWithDuration(this._duration, newConfigs);
  15724. return action;
  15725. },
  15726. startWithTarget:function (target) {
  15727. cc.ActionInterval.prototype.startWithTarget.call(this, target);
  15728. var locPosX = target.getPositionX();
  15729. var locPosY = target.getPositionY();
  15730. this._previousPosition.x = locPosX;
  15731. this._previousPosition.y = locPosY;
  15732. this._startPosition.x = locPosX;
  15733. this._startPosition.y = locPosY;
  15734. },
  15735. update:function (dt) {
  15736. dt = this._computeEaseTime(dt);
  15737. if (this.target) {
  15738. var locConfig = this._config;
  15739. var xa = 0;
  15740. var xb = locConfig[0].x;
  15741. var xc = locConfig[1].x;
  15742. var xd = locConfig[2].x;
  15743. var ya = 0;
  15744. var yb = locConfig[0].y;
  15745. var yc = locConfig[1].y;
  15746. var yd = locConfig[2].y;
  15747. var x = cc.bezierAt(xa, xb, xc, xd, dt);
  15748. var y = cc.bezierAt(ya, yb, yc, yd, dt);
  15749. var locStartPosition = this._startPosition;
  15750. if (cc.ENABLE_STACKABLE_ACTIONS) {
  15751. var targetX = this.target.getPositionX();
  15752. var targetY = this.target.getPositionY();
  15753. var locPreviousPosition = this._previousPosition;
  15754. locStartPosition.x = locStartPosition.x + targetX - locPreviousPosition.x;
  15755. locStartPosition.y = locStartPosition.y + targetY - locPreviousPosition.y;
  15756. x = x + locStartPosition.x;
  15757. y = y + locStartPosition.y;
  15758. locPreviousPosition.x = x;
  15759. locPreviousPosition.y = y;
  15760. this.target.setPosition(x, y);
  15761. } else {
  15762. this.target.setPosition(locStartPosition.x + x, locStartPosition.y + y);
  15763. }
  15764. }
  15765. },
  15766. reverse:function () {
  15767. var locConfig = this._config;
  15768. var r = [
  15769. cc.pAdd(locConfig[1], cc.pNeg(locConfig[2])),
  15770. cc.pAdd(locConfig[0], cc.pNeg(locConfig[2])),
  15771. cc.pNeg(locConfig[2]) ];
  15772. var action = new cc.BezierBy(this._duration, r);
  15773. this._cloneDecoration(action);
  15774. this._reverseEaseList(action);
  15775. return action;
  15776. }
  15777. });
  15778. cc.bezierBy = function (t, c) {
  15779. return new cc.BezierBy(t, c);
  15780. };
  15781. cc.BezierBy.create = cc.bezierBy;
  15782. cc.BezierTo = cc.BezierBy.extend({
  15783. _toConfig:null,
  15784. ctor:function (t, c) {
  15785. cc.BezierBy.prototype.ctor.call(this);
  15786. this._toConfig = [];
  15787. c && this.initWithDuration(t, c);
  15788. },
  15789. initWithDuration:function (t, c) {
  15790. if (cc.ActionInterval.prototype.initWithDuration.call(this, t)) {
  15791. this._toConfig = c;
  15792. return true;
  15793. }
  15794. return false;
  15795. },
  15796. clone:function () {
  15797. var action = new cc.BezierTo();
  15798. this._cloneDecoration(action);
  15799. action.initWithDuration(this._duration, this._toConfig);
  15800. return action;
  15801. },
  15802. startWithTarget:function (target) {
  15803. cc.BezierBy.prototype.startWithTarget.call(this, target);
  15804. var locStartPos = this._startPosition;
  15805. var locToConfig = this._toConfig;
  15806. var locConfig = this._config;
  15807. locConfig[0] = cc.pSub(locToConfig[0], locStartPos);
  15808. locConfig[1] = cc.pSub(locToConfig[1], locStartPos);
  15809. locConfig[2] = cc.pSub(locToConfig[2], locStartPos);
  15810. }
  15811. });
  15812. cc.bezierTo = function (t, c) {
  15813. return new cc.BezierTo(t, c);
  15814. };
  15815. cc.BezierTo.create = cc.bezierTo;
  15816. cc.ScaleTo = cc.ActionInterval.extend({
  15817. _scaleX:1,
  15818. _scaleY:1,
  15819. _startScaleX:1,
  15820. _startScaleY:1,
  15821. _endScaleX:0,
  15822. _endScaleY:0,
  15823. _deltaX:0,
  15824. _deltaY:0,
  15825. ctor:function (duration, sx, sy) {
  15826. cc.ActionInterval.prototype.ctor.call(this);
  15827. sx !== undefined && this.initWithDuration(duration, sx, sy);
  15828. },
  15829. initWithDuration:function (duration, sx, sy) {
  15830. if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) {
  15831. this._endScaleX = sx;
  15832. this._endScaleY = (sy != null) ? sy : sx;
  15833. return true;
  15834. }
  15835. return false;
  15836. },
  15837. clone:function () {
  15838. var action = new cc.ScaleTo();
  15839. this._cloneDecoration(action);
  15840. action.initWithDuration(this._duration, this._endScaleX, this._endScaleY);
  15841. return action;
  15842. },
  15843. startWithTarget:function (target) {
  15844. cc.ActionInterval.prototype.startWithTarget.call(this, target);
  15845. this._startScaleX = target.scaleX;
  15846. this._startScaleY = target.scaleY;
  15847. this._deltaX = this._endScaleX - this._startScaleX;
  15848. this._deltaY = this._endScaleY - this._startScaleY;
  15849. },
  15850. update:function (dt) {
  15851. dt = this._computeEaseTime(dt);
  15852. if (this.target) {
  15853. this.target.scaleX = this._startScaleX + this._deltaX * dt;
  15854. this.target.scaleY = this._startScaleY + this._deltaY * dt;
  15855. }
  15856. }
  15857. });
  15858. cc.scaleTo = function (duration, sx, sy) {
  15859. return new cc.ScaleTo(duration, sx, sy);
  15860. };
  15861. cc.ScaleTo.create = cc.scaleTo;
  15862. cc.ScaleBy = cc.ScaleTo.extend({
  15863. startWithTarget:function (target) {
  15864. cc.ScaleTo.prototype.startWithTarget.call(this, target);
  15865. this._deltaX = this._startScaleX * this._endScaleX - this._startScaleX;
  15866. this._deltaY = this._startScaleY * this._endScaleY - this._startScaleY;
  15867. },
  15868. reverse:function () {
  15869. var action = new cc.ScaleBy(this._duration, 1 / this._endScaleX, 1 / this._endScaleY);
  15870. this._cloneDecoration(action);
  15871. this._reverseEaseList(action);
  15872. return action;
  15873. },
  15874. clone:function () {
  15875. var action = new cc.ScaleBy();
  15876. this._cloneDecoration(action);
  15877. action.initWithDuration(this._duration, this._endScaleX, this._endScaleY);
  15878. return action;
  15879. }
  15880. });
  15881. cc.scaleBy = function (duration, sx, sy) {
  15882. return new cc.ScaleBy(duration, sx, sy);
  15883. };
  15884. cc.ScaleBy.create = cc.scaleBy;
  15885. cc.Blink = cc.ActionInterval.extend({
  15886. _times:0,
  15887. _originalState:false,
  15888. ctor:function (duration, blinks) {
  15889. cc.ActionInterval.prototype.ctor.call(this);
  15890. blinks !== undefined && this.initWithDuration(duration, blinks);
  15891. },
  15892. initWithDuration:function (duration, blinks) {
  15893. if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) {
  15894. this._times = blinks;
  15895. return true;
  15896. }
  15897. return false;
  15898. },
  15899. clone:function () {
  15900. var action = new cc.Blink();
  15901. this._cloneDecoration(action);
  15902. action.initWithDuration(this._duration, this._times);
  15903. return action;
  15904. },
  15905. update:function (dt) {
  15906. dt = this._computeEaseTime(dt);
  15907. if (this.target && !this.isDone()) {
  15908. var slice = 1.0 / this._times;
  15909. var m = dt % slice;
  15910. this.target.visible = (m > (slice / 2));
  15911. }
  15912. },
  15913. startWithTarget:function (target) {
  15914. cc.ActionInterval.prototype.startWithTarget.call(this, target);
  15915. this._originalState = target.visible;
  15916. },
  15917. stop:function () {
  15918. this.target.visible = this._originalState;
  15919. cc.ActionInterval.prototype.stop.call(this);
  15920. },
  15921. reverse:function () {
  15922. var action = new cc.Blink(this._duration, this._times);
  15923. this._cloneDecoration(action);
  15924. this._reverseEaseList(action);
  15925. return action;
  15926. }
  15927. });
  15928. cc.blink = function (duration, blinks) {
  15929. return new cc.Blink(duration, blinks);
  15930. };
  15931. cc.Blink.create = cc.blink;
  15932. cc.FadeTo = cc.ActionInterval.extend({
  15933. _toOpacity:0,
  15934. _fromOpacity:0,
  15935. ctor:function (duration, opacity) {
  15936. cc.ActionInterval.prototype.ctor.call(this);
  15937. opacity !== undefined && this.initWithDuration(duration, opacity);
  15938. },
  15939. initWithDuration:function (duration, opacity) {
  15940. if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) {
  15941. this._toOpacity = opacity;
  15942. return true;
  15943. }
  15944. return false;
  15945. },
  15946. clone:function () {
  15947. var action = new cc.FadeTo();
  15948. this._cloneDecoration(action);
  15949. action.initWithDuration(this._duration, this._toOpacity);
  15950. return action;
  15951. },
  15952. update:function (time) {
  15953. time = this._computeEaseTime(time);
  15954. var fromOpacity = this._fromOpacity !== undefined ? this._fromOpacity : 255;
  15955. this.target.opacity = fromOpacity + (this._toOpacity - fromOpacity) * time;
  15956. },
  15957. startWithTarget:function (target) {
  15958. cc.ActionInterval.prototype.startWithTarget.call(this, target);
  15959. this._fromOpacity = target.opacity;
  15960. }
  15961. });
  15962. cc.fadeTo = function (duration, opacity) {
  15963. return new cc.FadeTo(duration, opacity);
  15964. };
  15965. cc.FadeTo.create = cc.fadeTo;
  15966. cc.FadeIn = cc.FadeTo.extend({
  15967. _reverseAction: null,
  15968. ctor:function (duration) {
  15969. cc.FadeTo.prototype.ctor.call(this);
  15970. if (duration == null)
  15971. duration = 0;
  15972. this.initWithDuration(duration, 255);
  15973. },
  15974. reverse:function () {
  15975. var action = new cc.FadeOut();
  15976. action.initWithDuration(this._duration, 0);
  15977. this._cloneDecoration(action);
  15978. this._reverseEaseList(action);
  15979. return action;
  15980. },
  15981. clone:function () {
  15982. var action = new cc.FadeIn();
  15983. this._cloneDecoration(action);
  15984. action.initWithDuration(this._duration, this._toOpacity);
  15985. return action;
  15986. },
  15987. startWithTarget:function (target) {
  15988. if(this._reverseAction)
  15989. this._toOpacity = this._reverseAction._fromOpacity;
  15990. cc.FadeTo.prototype.startWithTarget.call(this, target);
  15991. }
  15992. });
  15993. cc.fadeIn = function (duration) {
  15994. return new cc.FadeIn(duration);
  15995. };
  15996. cc.FadeIn.create = cc.fadeIn;
  15997. cc.FadeOut = cc.FadeTo.extend({
  15998. ctor:function (duration) {
  15999. cc.FadeTo.prototype.ctor.call(this);
  16000. if (duration == null)
  16001. duration = 0;
  16002. this.initWithDuration(duration, 0);
  16003. },
  16004. reverse:function () {
  16005. var action = new cc.FadeIn();
  16006. action._reverseAction = this;
  16007. action.initWithDuration(this._duration, 255);
  16008. this._cloneDecoration(action);
  16009. this._reverseEaseList(action);
  16010. return action;
  16011. },
  16012. clone:function () {
  16013. var action = new cc.FadeOut();
  16014. this._cloneDecoration(action);
  16015. action.initWithDuration(this._duration, this._toOpacity);
  16016. return action;
  16017. }
  16018. });
  16019. cc.fadeOut = function (d) {
  16020. return new cc.FadeOut(d);
  16021. };
  16022. cc.FadeOut.create = cc.fadeOut;
  16023. cc.TintTo = cc.ActionInterval.extend({
  16024. _to:null,
  16025. _from:null,
  16026. ctor:function (duration, red, green, blue) {
  16027. cc.ActionInterval.prototype.ctor.call(this);
  16028. this._to = cc.color(0, 0, 0);
  16029. this._from = cc.color(0, 0, 0);
  16030. blue !== undefined && this.initWithDuration(duration, red, green, blue);
  16031. },
  16032. initWithDuration:function (duration, red, green, blue) {
  16033. if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) {
  16034. this._to = cc.color(red, green, blue);
  16035. return true;
  16036. }
  16037. return false;
  16038. },
  16039. clone:function () {
  16040. var action = new cc.TintTo();
  16041. this._cloneDecoration(action);
  16042. var locTo = this._to;
  16043. action.initWithDuration(this._duration, locTo.r, locTo.g, locTo.b);
  16044. return action;
  16045. },
  16046. startWithTarget:function (target) {
  16047. cc.ActionInterval.prototype.startWithTarget.call(this, target);
  16048. this._from = this.target.color;
  16049. },
  16050. update:function (dt) {
  16051. dt = this._computeEaseTime(dt);
  16052. var locFrom = this._from, locTo = this._to;
  16053. if (locFrom) {
  16054. this.target.setColor(
  16055. cc.color(
  16056. locFrom.r + (locTo.r - locFrom.r) * dt,
  16057. locFrom.g + (locTo.g - locFrom.g) * dt,
  16058. locFrom.b + (locTo.b - locFrom.b) * dt)
  16059. );
  16060. }
  16061. }
  16062. });
  16063. cc.tintTo = function (duration, red, green, blue) {
  16064. return new cc.TintTo(duration, red, green, blue);
  16065. };
  16066. cc.TintTo.create = cc.tintTo;
  16067. cc.TintBy = cc.ActionInterval.extend({
  16068. _deltaR:0,
  16069. _deltaG:0,
  16070. _deltaB:0,
  16071. _fromR:0,
  16072. _fromG:0,
  16073. _fromB:0,
  16074. ctor:function (duration, deltaRed, deltaGreen, deltaBlue) {
  16075. cc.ActionInterval.prototype.ctor.call(this);
  16076. deltaBlue !== undefined && this.initWithDuration(duration, deltaRed, deltaGreen, deltaBlue);
  16077. },
  16078. initWithDuration:function (duration, deltaRed, deltaGreen, deltaBlue) {
  16079. if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) {
  16080. this._deltaR = deltaRed;
  16081. this._deltaG = deltaGreen;
  16082. this._deltaB = deltaBlue;
  16083. return true;
  16084. }
  16085. return false;
  16086. },
  16087. clone:function () {
  16088. var action = new cc.TintBy();
  16089. this._cloneDecoration(action);
  16090. action.initWithDuration(this._duration, this._deltaR, this._deltaG, this._deltaB);
  16091. return action;
  16092. },
  16093. startWithTarget:function (target) {
  16094. cc.ActionInterval.prototype.startWithTarget.call(this, target);
  16095. var color = target.color;
  16096. this._fromR = color.r;
  16097. this._fromG = color.g;
  16098. this._fromB = color.b;
  16099. },
  16100. update:function (dt) {
  16101. dt = this._computeEaseTime(dt);
  16102. this.target.color = cc.color(this._fromR + this._deltaR * dt,
  16103. this._fromG + this._deltaG * dt,
  16104. this._fromB + this._deltaB * dt);
  16105. },
  16106. reverse:function () {
  16107. var action = new cc.TintBy(this._duration, -this._deltaR, -this._deltaG, -this._deltaB);
  16108. this._cloneDecoration(action);
  16109. this._reverseEaseList(action);
  16110. return action;
  16111. }
  16112. });
  16113. cc.tintBy = function (duration, deltaRed, deltaGreen, deltaBlue) {
  16114. return new cc.TintBy(duration, deltaRed, deltaGreen, deltaBlue);
  16115. };
  16116. cc.TintBy.create = cc.tintBy;
  16117. cc.DelayTime = cc.ActionInterval.extend({
  16118. update:function (dt) {},
  16119. reverse:function () {
  16120. var action = new cc.DelayTime(this._duration);
  16121. this._cloneDecoration(action);
  16122. this._reverseEaseList(action);
  16123. return action;
  16124. },
  16125. clone:function () {
  16126. var action = new cc.DelayTime();
  16127. this._cloneDecoration(action);
  16128. action.initWithDuration(this._duration);
  16129. return action;
  16130. }
  16131. });
  16132. cc.delayTime = function (d) {
  16133. return new cc.DelayTime(d);
  16134. };
  16135. cc.DelayTime.create = cc.delayTime;
  16136. cc.ReverseTime = cc.ActionInterval.extend({
  16137. _other:null,
  16138. ctor:function (action) {
  16139. cc.ActionInterval.prototype.ctor.call(this);
  16140. this._other = null;
  16141. action && this.initWithAction(action);
  16142. },
  16143. initWithAction:function (action) {
  16144. if(!action)
  16145. throw new Error("cc.ReverseTime.initWithAction(): action must be non null");
  16146. if(action === this._other)
  16147. throw new Error("cc.ReverseTime.initWithAction(): the action was already passed in.");
  16148. if (cc.ActionInterval.prototype.initWithDuration.call(this, action._duration)) {
  16149. this._other = action;
  16150. return true;
  16151. }
  16152. return false;
  16153. },
  16154. clone:function () {
  16155. var action = new cc.ReverseTime();
  16156. this._cloneDecoration(action);
  16157. action.initWithAction(this._other.clone());
  16158. return action;
  16159. },
  16160. startWithTarget:function (target) {
  16161. cc.ActionInterval.prototype.startWithTarget.call(this, target);
  16162. this._other.startWithTarget(target);
  16163. },
  16164. update:function (dt) {
  16165. dt = this._computeEaseTime(dt);
  16166. if (this._other)
  16167. this._other.update(1 - dt);
  16168. },
  16169. reverse:function () {
  16170. return this._other.clone();
  16171. },
  16172. stop:function () {
  16173. this._other.stop();
  16174. cc.Action.prototype.stop.call(this);
  16175. }
  16176. });
  16177. cc.reverseTime = function (action) {
  16178. return new cc.ReverseTime(action);
  16179. };
  16180. cc.ReverseTime.create = cc.reverseTime;
  16181. cc.Animate = cc.ActionInterval.extend({
  16182. _animation:null,
  16183. _nextFrame:0,
  16184. _origFrame:null,
  16185. _executedLoops:0,
  16186. _splitTimes: null,
  16187. _currFrameIndex:0,
  16188. ctor:function (animation) {
  16189. cc.ActionInterval.prototype.ctor.call(this);
  16190. this._splitTimes = [];
  16191. animation && this.initWithAnimation(animation);
  16192. },
  16193. getAnimation:function () {
  16194. return this._animation;
  16195. },
  16196. setAnimation:function (animation) {
  16197. this._animation = animation;
  16198. },
  16199. getCurrentFrameIndex: function () {
  16200. return this._currFrameIndex;
  16201. },
  16202. initWithAnimation:function (animation) {
  16203. if(!animation)
  16204. throw new Error("cc.Animate.initWithAnimation(): animation must be non-NULL");
  16205. var singleDuration = animation.getDuration();
  16206. if (this.initWithDuration(singleDuration * animation.getLoops())) {
  16207. this._nextFrame = 0;
  16208. this.setAnimation(animation);
  16209. this._origFrame = null;
  16210. this._executedLoops = 0;
  16211. var locTimes = this._splitTimes;
  16212. locTimes.length = 0;
  16213. var accumUnitsOfTime = 0;
  16214. var newUnitOfTimeValue = singleDuration / animation.getTotalDelayUnits();
  16215. var frames = animation.getFrames();
  16216. cc.arrayVerifyType(frames, cc.AnimationFrame);
  16217. for (var i = 0; i < frames.length; i++) {
  16218. var frame = frames[i];
  16219. var value = (accumUnitsOfTime * newUnitOfTimeValue) / singleDuration;
  16220. accumUnitsOfTime += frame.getDelayUnits();
  16221. locTimes.push(value);
  16222. }
  16223. return true;
  16224. }
  16225. return false;
  16226. },
  16227. clone:function () {
  16228. var action = new cc.Animate();
  16229. this._cloneDecoration(action);
  16230. action.initWithAnimation(this._animation.clone());
  16231. return action;
  16232. },
  16233. startWithTarget:function (target) {
  16234. cc.ActionInterval.prototype.startWithTarget.call(this, target);
  16235. if (this._animation.getRestoreOriginalFrame())
  16236. this._origFrame = target.displayFrame();
  16237. this._nextFrame = 0;
  16238. this._executedLoops = 0;
  16239. },
  16240. update:function (dt) {
  16241. dt = this._computeEaseTime(dt);
  16242. if (dt < 1.0) {
  16243. dt *= this._animation.getLoops();
  16244. var loopNumber = 0 | dt;
  16245. if (loopNumber > this._executedLoops) {
  16246. this._nextFrame = 0;
  16247. this._executedLoops++;
  16248. }
  16249. dt = dt % 1.0;
  16250. }
  16251. var frames = this._animation.getFrames();
  16252. var numberOfFrames = frames.length, locSplitTimes = this._splitTimes;
  16253. for (var i = this._nextFrame; i < numberOfFrames; i++) {
  16254. if (locSplitTimes[i] <= dt) {
  16255. _currFrameIndex = i;
  16256. this.target.setSpriteFrame(frames[_currFrameIndex].getSpriteFrame());
  16257. this._nextFrame = i + 1;
  16258. } else {
  16259. break;
  16260. }
  16261. }
  16262. },
  16263. reverse:function () {
  16264. var locAnimation = this._animation;
  16265. var oldArray = locAnimation.getFrames();
  16266. var newArray = [];
  16267. cc.arrayVerifyType(oldArray, cc.AnimationFrame);
  16268. if (oldArray.length > 0) {
  16269. for (var i = oldArray.length - 1; i >= 0; i--) {
  16270. var element = oldArray[i];
  16271. if (!element)
  16272. break;
  16273. newArray.push(element.clone());
  16274. }
  16275. }
  16276. var newAnim = new cc.Animation(newArray, locAnimation.getDelayPerUnit(), locAnimation.getLoops());
  16277. newAnim.setRestoreOriginalFrame(locAnimation.getRestoreOriginalFrame());
  16278. var action = new cc.Animate(newAnim);
  16279. this._cloneDecoration(action);
  16280. this._reverseEaseList(action);
  16281. return action;
  16282. },
  16283. stop:function () {
  16284. if (this._animation.getRestoreOriginalFrame() && this.target)
  16285. this.target.setSpriteFrame(this._origFrame);
  16286. cc.Action.prototype.stop.call(this);
  16287. }
  16288. });
  16289. cc.animate = function (animation) {
  16290. return new cc.Animate(animation);
  16291. };
  16292. cc.Animate.create = cc.animate;
  16293. cc.TargetedAction = cc.ActionInterval.extend({
  16294. _action:null,
  16295. _forcedTarget:null,
  16296. ctor: function (target, action) {
  16297. cc.ActionInterval.prototype.ctor.call(this);
  16298. action && this.initWithTarget(target, action);
  16299. },
  16300. initWithTarget:function (target, action) {
  16301. if (this.initWithDuration(action._duration)) {
  16302. this._forcedTarget = target;
  16303. this._action = action;
  16304. return true;
  16305. }
  16306. return false;
  16307. },
  16308. clone:function () {
  16309. var action = new cc.TargetedAction();
  16310. this._cloneDecoration(action);
  16311. action.initWithTarget(this._forcedTarget, this._action.clone());
  16312. return action;
  16313. },
  16314. startWithTarget:function (target) {
  16315. cc.ActionInterval.prototype.startWithTarget.call(this, target);
  16316. this._action.startWithTarget(this._forcedTarget);
  16317. },
  16318. stop:function () {
  16319. this._action.stop();
  16320. },
  16321. update:function (dt) {
  16322. dt = this._computeEaseTime(dt);
  16323. this._action.update(dt);
  16324. },
  16325. getForcedTarget:function () {
  16326. return this._forcedTarget;
  16327. },
  16328. setForcedTarget:function (forcedTarget) {
  16329. if (this._forcedTarget !== forcedTarget)
  16330. this._forcedTarget = forcedTarget;
  16331. }
  16332. });
  16333. cc.targetedAction = function (target, action) {
  16334. return new cc.TargetedAction(target, action);
  16335. };
  16336. cc.TargetedAction.create = cc.targetedAction;
  16337. cc.ActionInstant = cc.FiniteTimeAction.extend({
  16338. isDone:function () {
  16339. return true;
  16340. },
  16341. step:function (dt) {
  16342. this.update(1);
  16343. },
  16344. update:function (dt) {
  16345. },
  16346. reverse:function(){
  16347. return this.clone();
  16348. },
  16349. clone:function(){
  16350. return new cc.ActionInstant();
  16351. }
  16352. });
  16353. cc.Show = cc.ActionInstant.extend({
  16354. update:function (dt) {
  16355. this.target.visible = true;
  16356. },
  16357. reverse:function () {
  16358. return new cc.Hide();
  16359. },
  16360. clone:function(){
  16361. return new cc.Show();
  16362. }
  16363. });
  16364. cc.show = function () {
  16365. return new cc.Show();
  16366. };
  16367. cc.Show.create = cc.show;
  16368. cc.Hide = cc.ActionInstant.extend({
  16369. update:function (dt) {
  16370. this.target.visible = false;
  16371. },
  16372. reverse:function () {
  16373. return new cc.Show();
  16374. },
  16375. clone:function(){
  16376. return new cc.Hide();
  16377. }
  16378. });
  16379. cc.hide = function () {
  16380. return new cc.Hide();
  16381. };
  16382. cc.Hide.create = cc.hide;
  16383. cc.ToggleVisibility = cc.ActionInstant.extend({
  16384. update:function (dt) {
  16385. this.target.visible = !this.target.visible;
  16386. },
  16387. reverse:function () {
  16388. return new cc.ToggleVisibility();
  16389. },
  16390. clone:function(){
  16391. return new cc.ToggleVisibility();
  16392. }
  16393. });
  16394. cc.toggleVisibility = function () {
  16395. return new cc.ToggleVisibility();
  16396. };
  16397. cc.ToggleVisibility.create = cc.toggleVisibility;
  16398. cc.RemoveSelf = cc.ActionInstant.extend({
  16399. _isNeedCleanUp: true,
  16400. ctor:function(isNeedCleanUp){
  16401. cc.FiniteTimeAction.prototype.ctor.call(this);
  16402. isNeedCleanUp !== undefined && this.init(isNeedCleanUp);
  16403. },
  16404. update:function(dt){
  16405. this.target.removeFromParent(this._isNeedCleanUp);
  16406. },
  16407. /**
  16408. * Initialization of the node, please do not call this function by yourself, you should pass the parameters to constructor to initialize it
.
  16409. * @param isNeedCleanUp
  16410. * @returns {boolean}
  16411. */
  16412. init:function(isNeedCleanUp){
  16413. this._isNeedCleanUp = isNeedCleanUp;
  16414. return true;
  16415. },
  16416. reverse:function(){
  16417. return new cc.RemoveSelf(this._isNeedCleanUp);
  16418. },
  16419. clone:function(){
  16420. return new cc.RemoveSelf(this._isNeedCleanUp);
  16421. }
  16422. });
  16423. cc.removeSelf = function(isNeedCleanUp){
  16424. return new cc.RemoveSelf(isNeedCleanUp);
  16425. };
  16426. cc.RemoveSelf.create = cc.removeSelf;
  16427. cc.FlipX = cc.ActionInstant.extend({
  16428. _flippedX:false,
  16429. ctor:function(flip){
  16430. cc.FiniteTimeAction.prototype.ctor.call(this);
  16431. this._flippedX = false;
  16432. flip !== undefined && this.initWithFlipX(flip);
  16433. },
  16434. initWithFlipX:function (flip) {
  16435. this._flippedX = flip;
  16436. return true;
  16437. },
  16438. update:function (dt) {
  16439. this.target.flippedX = this._flippedX;
  16440. },
  16441. reverse:function () {
  16442. return new cc.FlipX(!this._flippedX);
  16443. },
  16444. clone:function(){
  16445. var action = new cc.FlipX();
  16446. action.initWithFlipX(this._flippedX);
  16447. return action;
  16448. }
  16449. });
  16450. cc.flipX = function (flip) {
  16451. return new cc.FlipX(flip);
  16452. };
  16453. cc.FlipX.create = cc.flipX;
  16454. cc.FlipY = cc.ActionInstant.extend({
  16455. _flippedY:false,
  16456. ctor: function(flip){
  16457. cc.FiniteTimeAction.prototype.ctor.call(this);
  16458. this._flippedY = false;
  16459. flip !== undefined && this.initWithFlipY(flip);
  16460. },
  16461. initWithFlipY:function (flip) {
  16462. this._flippedY = flip;
  16463. return true;
  16464. },
  16465. update:function (dt) {
  16466. this.target.flippedY = this._flippedY;
  16467. },
  16468. reverse:function () {
  16469. return new cc.FlipY(!this._flippedY);
  16470. },
  16471. clone:function(){
  16472. var action = new cc.FlipY();
  16473. action.initWithFlipY(this._flippedY);
  16474. return action;
  16475. }
  16476. });
  16477. cc.flipY = function (flip) {
  16478. return new cc.FlipY(flip);
  16479. };
  16480. cc.FlipY.create = cc.flipY;
  16481. cc.Place = cc.ActionInstant.extend({
  16482. _x: 0,
  16483. _y: 0,
  16484. ctor:function(pos, y){
  16485. cc.FiniteTimeAction.prototype.ctor.call(this);
  16486. this._x = 0;
  16487. this._y = 0;
  16488. if (pos !== undefined) {
  16489. if (pos.x !== undefined) {
  16490. y = pos.y;
  16491. pos = pos.x;
  16492. }
  16493. this.initWithPosition(pos, y);
  16494. }
  16495. },
  16496. initWithPosition: function (x, y) {
  16497. this._x = x;
  16498. this._y = y;
  16499. return true;
  16500. },
  16501. update:function (dt) {
  16502. this.target.setPosition(this._x, this._y);
  16503. },
  16504. clone:function(){
  16505. var action = new cc.Place();
  16506. action.initWithPosition(this._x, this._y);
  16507. return action;
  16508. }
  16509. });
  16510. cc.place = function (pos, y) {
  16511. return new cc.Place(pos, y);
  16512. };
  16513. cc.Place.create = cc.place;
  16514. cc.CallFunc = cc.ActionInstant.extend({
  16515. _selectorTarget:null,
  16516. _function:null,
  16517. _data:null,
  16518. ctor:function(selector, selectorTarget, data){
  16519. cc.FiniteTimeAction.prototype.ctor.call(this);
  16520. this.initWithFunction(selector, selectorTarget, data);
  16521. },
  16522. initWithFunction:function (selector, selectorTarget, data) {
  16523. if (selector) {
  16524. this._function = selector;
  16525. }
  16526. if (selectorTarget) {
  16527. this._selectorTarget = selectorTarget;
  16528. }
  16529. if (data !== undefined) {
  16530. this._data = data;
  16531. }
  16532. return true;
  16533. },
  16534. execute:function () {
  16535. if (this._function) {
  16536. this._function.call(this._selectorTarget, this.target, this._data);
  16537. }
  16538. },
  16539. update:function (dt) {
  16540. this.execute();
  16541. },
  16542. getTargetCallback:function () {
  16543. return this._selectorTarget;
  16544. },
  16545. setTargetCallback:function (sel) {
  16546. if (sel !== this._selectorTarget) {
  16547. if (this._selectorTarget)
  16548. this._selectorTarget = null;
  16549. this._selectorTarget = sel;
  16550. }
  16551. },
  16552. clone:function(){
  16553. var action = new cc.CallFunc();
  16554. action.initWithFunction(this._function, this._selectorTarget, this._data);
  16555. return action;
  16556. }
  16557. });
  16558. cc.callFunc = function (selector, selectorTarget, data) {
  16559. return new cc.CallFunc(selector, selectorTarget, data);
  16560. };
  16561. cc.CallFunc.create = cc.callFunc;
  16562. cc.ActionEase = cc.ActionInterval.extend({
  16563. _inner:null,
  16564. ctor: function (action) {
  16565. cc.ActionInterval.prototype.ctor.call(this);
  16566. action && this.initWithAction(action);
  16567. },
  16568. initWithAction:function (action) {
  16569. if(!action)
  16570. throw new Error("cc.ActionEase.initWithAction(): action must be non nil");
  16571. if (this.initWithDuration(action.getDuration())) {
  16572. this._inner = action;
  16573. return true;
  16574. }
  16575. return false;
  16576. },
  16577. clone:function(){
  16578. var action = new cc.ActionEase();
  16579. action.initWithAction(this._inner.clone());
  16580. return action;
  16581. },
  16582. startWithTarget:function (target) {
  16583. cc.ActionInterval.prototype.startWithTarget.call(this, target);
  16584. this._inner.startWithTarget(this.target);
  16585. },
  16586. stop:function () {
  16587. this._inner.stop();
  16588. cc.ActionInterval.prototype.stop.call(this);
  16589. },
  16590. update:function (dt) {
  16591. this._inner.update(dt);
  16592. },
  16593. reverse:function () {
  16594. return new cc.ActionEase(this._inner.reverse());
  16595. },
  16596. getInnerAction:function(){
  16597. return this._inner;
  16598. }
  16599. });
  16600. cc.actionEase = function (action) {
  16601. return new cc.ActionEase(action);
  16602. };
  16603. cc.ActionEase.create = cc.actionEase;
  16604. cc.EaseRateAction = cc.ActionEase.extend({
  16605. _rate:0,
  16606. ctor: function(action, rate){
  16607. cc.ActionEase.prototype.ctor.call(this);
  16608. rate !== undefined && this.initWithAction(action, rate);
  16609. },
  16610. setRate:function (rate) {
  16611. this._rate = rate;
  16612. },
  16613. getRate:function () {
  16614. return this._rate;
  16615. },
  16616. initWithAction:function (action, rate) {
  16617. if (cc.ActionEase.prototype.initWithAction.call(this, action)) {
  16618. this._rate = rate;
  16619. return true;
  16620. }
  16621. return false;
  16622. },
  16623. clone:function(){
  16624. var action = new cc.EaseRateAction();
  16625. action.initWithAction(this._inner.clone(), this._rate);
  16626. return action;
  16627. },
  16628. reverse:function () {
  16629. return new cc.EaseRateAction(this._inner.reverse(), 1 / this._rate);
  16630. }
  16631. });
  16632. cc.easeRateAction = function (action, rate) {
  16633. return new cc.EaseRateAction(action, rate);
  16634. };
  16635. cc.EaseRateAction.create = cc.easeRateAction;
  16636. cc.EaseIn = cc.EaseRateAction.extend({
  16637. update:function (dt) {
  16638. this._inner.update(Math.pow(dt, this._rate));
  16639. },
  16640. reverse:function () {
  16641. return new cc.EaseIn(this._inner.reverse(), 1 / this._rate);
  16642. },
  16643. clone:function(){
  16644. var action = new cc.EaseIn();
  16645. action.initWithAction(this._inner.clone(), this._rate);
  16646. return action;
  16647. }
  16648. });
  16649. cc.EaseIn.create = function (action, rate) {
  16650. return new cc.EaseIn(action, rate);
  16651. };
  16652. cc.easeIn = function (rate) {
  16653. return {
  16654. _rate: rate,
  16655. easing: function (dt) {
  16656. return Math.pow(dt, this._rate);
  16657. },
  16658. reverse: function(){
  16659. return cc.easeIn(1 / this._rate);
  16660. }
  16661. };
  16662. };
  16663. cc.EaseOut = cc.EaseRateAction.extend({
  16664. update:function (dt) {
  16665. this._inner.update(Math.pow(dt, 1 / this._rate));
  16666. },
  16667. reverse:function () {
  16668. return new cc.EaseOut(this._inner.reverse(), 1 / this._rate);
  16669. },
  16670. clone:function(){
  16671. var action = new cc.EaseOut();
  16672. action.initWithAction(this._inner.clone(),this._rate);
  16673. return action;
  16674. }
  16675. });
  16676. cc.EaseOut.create = function (action, rate) {
  16677. return new cc.EaseOut(action, rate);
  16678. };
  16679. cc.easeOut = function (rate) {
  16680. return {
  16681. _rate: rate,
  16682. easing: function (dt) {
  16683. return Math.pow(dt, 1 / this._rate);
  16684. },
  16685. reverse: function(){
  16686. return cc.easeOut(1 / this._rate)
  16687. }
  16688. };
  16689. };
  16690. cc.EaseInOut = cc.EaseRateAction.extend({
  16691. update:function (dt) {
  16692. dt *= 2;
  16693. if (dt < 1)
  16694. this._inner.update(0.5 * Math.pow(dt, this._rate));
  16695. else
  16696. this._inner.update(1.0 - 0.5 * Math.pow(2 - dt, this._rate));
  16697. },
  16698. clone:function(){
  16699. var action = new cc.EaseInOut();
  16700. action.initWithAction(this._inner.clone(), this._rate);
  16701. return action;
  16702. },
  16703. reverse:function () {
  16704. return new cc.EaseInOut(this._inner.reverse(), this._rate);
  16705. }
  16706. });
  16707. cc.EaseInOut.create = function (action, rate) {
  16708. return new cc.EaseInOut(action, rate);
  16709. };
  16710. cc.easeInOut = function (rate) {
  16711. return {
  16712. _rate: rate,
  16713. easing: function (dt) {
  16714. dt *= 2;
  16715. if (dt < 1)
  16716. return 0.5 * Math.pow(dt, this._rate);
  16717. else
  16718. return 1.0 - 0.5 * Math.pow(2 - dt, this._rate);
  16719. },
  16720. reverse: function(){
  16721. return cc.easeInOut(this._rate);
  16722. }
  16723. };
  16724. };
  16725. cc.EaseExponentialIn = cc.ActionEase.extend({
  16726. update:function (dt) {
  16727. this._inner.update(dt === 0 ? 0 : Math.pow(2, 10 * (dt - 1)));
  16728. },
  16729. reverse:function () {
  16730. return new cc.EaseExponentialOut(this._inner.reverse());
  16731. },
  16732. clone:function(){
  16733. var action = new cc.EaseExponentialIn();
  16734. action.initWithAction(this._inner.clone());
  16735. return action;
  16736. }
  16737. });
  16738. cc.EaseExponentialIn.create = function (action) {
  16739. return new cc.EaseExponentialIn(action);
  16740. };
  16741. cc._easeExponentialInObj = {
  16742. easing: function(dt){
  16743. return dt === 0 ? 0 : Math.pow(2, 10 * (dt - 1));
  16744. },
  16745. reverse: function(){
  16746. return cc._easeExponentialOutObj;
  16747. }
  16748. };
  16749. cc.easeExponentialIn = function(){
  16750. return cc._easeExponentialInObj;
  16751. };
  16752. cc.EaseExponentialOut = cc.ActionEase.extend({
  16753. update:function (dt) {
  16754. this._inner.update(dt === 1 ? 1 : (-(Math.pow(2, -10 * dt)) + 1));
  16755. },
  16756. reverse:function () {
  16757. return new cc.EaseExponentialIn(this._inner.reverse());
  16758. },
  16759. clone:function(){
  16760. var action = new cc.EaseExponentialOut();
  16761. action.initWithAction(this._inner.clone());
  16762. return action;
  16763. }
  16764. });
  16765. cc.EaseExponentialOut.create = function (action) {
  16766. return new cc.EaseExponentialOut(action);
  16767. };
  16768. cc._easeExponentialOutObj = {
  16769. easing: function(dt){
  16770. return dt === 1 ? 1 : (-(Math.pow(2, -10 * dt)) + 1);
  16771. },
  16772. reverse: function(){
  16773. return cc._easeExponentialInObj;
  16774. }
  16775. };
  16776. cc.easeExponentialOut = function(){
  16777. return cc._easeExponentialOutObj;
  16778. };
  16779. cc.EaseExponentialInOut = cc.ActionEase.extend({
  16780. update:function (dt) {
  16781. if( dt !== 1 && dt !== 0) {
  16782. dt *= 2;
  16783. if (dt < 1)
  16784. dt = 0.5 * Math.pow(2, 10 * (dt - 1));
  16785. else
  16786. dt = 0.5 * (-Math.pow(2, -10 * (dt - 1)) + 2);
  16787. }
  16788. this._inner.update(dt);
  16789. },
  16790. reverse:function () {
  16791. return new cc.EaseExponentialInOut(this._inner.reverse());
  16792. },
  16793. clone:function(){
  16794. var action = new cc.EaseExponentialInOut();
  16795. action.initWithAction(this._inner.clone());
  16796. return action;
  16797. }
  16798. });
  16799. cc.EaseExponentialInOut.create = function (action) {
  16800. return new cc.EaseExponentialInOut(action);
  16801. };
  16802. cc._easeExponentialInOutObj = {
  16803. easing: function(dt){
  16804. if( dt !== 1 && dt !== 0) {
  16805. dt *= 2;
  16806. if (dt < 1)
  16807. return 0.5 * Math.pow(2, 10 * (dt - 1));
  16808. else
  16809. return 0.5 * (-Math.pow(2, -10 * (dt - 1)) + 2);
  16810. }
  16811. return dt;
  16812. },
  16813. reverse: function(){
  16814. return cc._easeExponentialInOutObj;
  16815. }
  16816. };
  16817. cc.easeExponentialInOut = function(){
  16818. return cc._easeExponentialInOutObj;
  16819. };
  16820. cc.EaseSineIn = cc.ActionEase.extend({
  16821. update:function (dt) {
  16822. dt = dt===0 || dt===1 ? dt : -1 * Math.cos(dt * Math.PI / 2) + 1;
  16823. this._inner.update(dt);
  16824. },
  16825. reverse:function () {
  16826. return new cc.EaseSineOut(this._inner.reverse());
  16827. },
  16828. clone:function(){
  16829. var action = new cc.EaseSineIn();
  16830. action.initWithAction(this._inner.clone());
  16831. return action;
  16832. }
  16833. });
  16834. cc.EaseSineIn.create = function (action) {
  16835. return new cc.EaseSineIn(action);
  16836. };
  16837. cc._easeSineInObj = {
  16838. easing: function(dt){
  16839. return (dt===0 || dt===1) ? dt : -1 * Math.cos(dt * Math.PI / 2) + 1;
  16840. },
  16841. reverse: function(){
  16842. return cc._easeSineOutObj;
  16843. }
  16844. };
  16845. cc.easeSineIn = function(){
  16846. return cc._easeSineInObj;
  16847. };
  16848. cc.EaseSineOut = cc.ActionEase.extend({
  16849. update:function (dt) {
  16850. dt = dt===0 || dt===1 ? dt : Math.sin(dt * Math.PI / 2);
  16851. this._inner.update(dt);
  16852. },
  16853. reverse:function () {
  16854. return new cc.EaseSineIn(this._inner.reverse());
  16855. },
  16856. clone:function(){
  16857. var action = new cc.EaseSineOut();
  16858. action.initWithAction(this._inner.clone());
  16859. return action;
  16860. }
  16861. });
  16862. cc.EaseSineOut.create = function (action) {
  16863. return new cc.EaseSineOut(action);
  16864. };
  16865. cc._easeSineOutObj = {
  16866. easing: function(dt){
  16867. return (dt===0 || dt===1) ? dt : Math.sin(dt * Math.PI / 2);
  16868. },
  16869. reverse: function(){
  16870. return cc._easeSineInObj;
  16871. }
  16872. };
  16873. cc.easeSineOut = function(){
  16874. return cc._easeSineOutObj;
  16875. };
  16876. cc.EaseSineInOut = cc.ActionEase.extend({
  16877. update:function (dt) {
  16878. dt = dt===0 || dt===1 ? dt : -0.5 * (Math.cos(Math.PI * dt) - 1);
  16879. this._inner.update(dt);
  16880. },
  16881. clone:function(){
  16882. var action = new cc.EaseSineInOut();
  16883. action.initWithAction(this._inner.clone());
  16884. return action;
  16885. },
  16886. reverse:function () {
  16887. return new cc.EaseSineInOut(this._inner.reverse());
  16888. }
  16889. });
  16890. cc.EaseSineInOut.create = function (action) {
  16891. return new cc.EaseSineInOut(action);
  16892. };
  16893. cc._easeSineInOutObj = {
  16894. easing: function(dt){
  16895. return (dt === 0 || dt === 1) ? dt : -0.5 * (Math.cos(Math.PI * dt) - 1);
  16896. },
  16897. reverse: function(){
  16898. return cc._easeSineInOutObj;
  16899. }
  16900. };
  16901. cc.easeSineInOut = function(){
  16902. return cc._easeSineInOutObj;
  16903. };
  16904. cc.EaseElastic = cc.ActionEase.extend({
  16905. _period: 0.3,
  16906. ctor:function(action, period){
  16907. cc.ActionEase.prototype.ctor.call(this);
  16908. action && this.initWithAction(action, period);
  16909. },
  16910. getPeriod:function () {
  16911. return this._period;
  16912. },
  16913. setPeriod:function (period) {
  16914. this._period = period;
  16915. },
  16916. initWithAction:function (action, period) {
  16917. cc.ActionEase.prototype.initWithAction.call(this, action);
  16918. this._period = (period == null) ? 0.3 : period;
  16919. return true;
  16920. },
  16921. reverse:function () {
  16922. cc.log("cc.EaseElastic.reverse(): it should be overridden in subclass.");
  16923. return null;
  16924. },
  16925. clone:function(){
  16926. var action = new cc.EaseElastic();
  16927. action.initWithAction(this._inner.clone(), this._period);
  16928. return action;
  16929. }
  16930. });
  16931. cc.EaseElastic.create = function (action, period) {
  16932. return new cc.EaseElastic(action, period);
  16933. };
  16934. cc.EaseElasticIn = cc.EaseElastic.extend({
  16935. update:function (dt) {
  16936. var newT = 0;
  16937. if (dt === 0 || dt === 1) {
  16938. newT = dt;
  16939. } else {
  16940. var s = this._period / 4;
  16941. dt = dt - 1;
  16942. newT = -Math.pow(2, 10 * dt) * Math.sin((dt - s) * Math.PI * 2 / this._period);
  16943. }
  16944. this._inner.update(newT);
  16945. },
  16946. reverse:function () {
  16947. return new cc.EaseElasticOut(this._inner.reverse(), this._period);
  16948. },
  16949. clone:function(){
  16950. var action = new cc.EaseElasticIn();
  16951. action.initWithAction(this._inner.clone(), this._period);
  16952. return action;
  16953. }
  16954. });
  16955. cc.EaseElasticIn.create = function (action, period) {
  16956. return new cc.EaseElasticIn(action, period);
  16957. };
  16958. cc._easeElasticInObj = {
  16959. easing:function(dt){
  16960. if (dt === 0 || dt === 1)
  16961. return dt;
  16962. dt = dt - 1;
  16963. return -Math.pow(2, 10 * dt) * Math.sin((dt - (0.3 / 4)) * Math.PI * 2 / 0.3);
  16964. },
  16965. reverse:function(){
  16966. return cc._easeElasticOutObj;
  16967. }
  16968. };
  16969. cc.easeElasticIn = function (period) {
  16970. if(period && period !== 0.3){
  16971. return {
  16972. _period: period,
  16973. easing: function (dt) {
  16974. if (dt === 0 || dt === 1)
  16975. return dt;
  16976. dt = dt - 1;
  16977. return -Math.pow(2, 10 * dt) * Math.sin((dt - (this._period / 4)) * Math.PI * 2 / this._period);
  16978. },
  16979. reverse:function () {
  16980. return cc.easeElasticOut(this._period);
  16981. }
  16982. };
  16983. }
  16984. return cc._easeElasticInObj;
  16985. };
  16986. cc.EaseElasticOut = cc.EaseElastic.extend({
  16987. update:function (dt) {
  16988. var newT = 0;
  16989. if (dt === 0 || dt === 1) {
  16990. newT = dt;
  16991. } else {
  16992. var s = this._period / 4;
  16993. newT = Math.pow(2, -10 * dt) * Math.sin((dt - s) * Math.PI * 2 / this._period) + 1;
  16994. }
  16995. this._inner.update(newT);
  16996. },
  16997. reverse:function () {
  16998. return new cc.EaseElasticIn(this._inner.reverse(), this._period);
  16999. },
  17000. clone:function(){
  17001. var action = new cc.EaseElasticOut();
  17002. action.initWithAction(this._inner.clone(), this._period);
  17003. return action;
  17004. }
  17005. });
  17006. cc.EaseElasticOut.create = function (action, period) {
  17007. return new cc.EaseElasticOut(action, period);
  17008. };
  17009. cc._easeElasticOutObj = {
  17010. easing: function (dt) {
  17011. return (dt === 0 || dt === 1) ? dt : Math.pow(2, -10 * dt) * Math.sin((dt - (0.3 / 4)) * Math.PI * 2 / 0.3) + 1;
  17012. },
  17013. reverse:function(){
  17014. return cc._easeElasticInObj;
  17015. }
  17016. };
  17017. cc.easeElasticOut = function (period) {
  17018. if(period && period !== 0.3){
  17019. return {
  17020. _period: period,
  17021. easing: function (dt) {
  17022. return (dt === 0 || dt === 1) ? dt : Math.pow(2, -10 * dt) * Math.sin((dt - (this._period / 4)) * Math.PI * 2 / this._period) + 1;
  17023. },
  17024. reverse:function(){
  17025. return cc.easeElasticIn(this._period);
  17026. }
  17027. };
  17028. }
  17029. return cc._easeElasticOutObj;
  17030. };
  17031. cc.EaseElasticInOut = cc.EaseElastic.extend({
  17032. update:function (dt) {
  17033. var newT = 0;
  17034. var locPeriod = this._period;
  17035. if (dt === 0 || dt === 1) {
  17036. newT = dt;
  17037. } else {
  17038. dt = dt * 2;
  17039. if (!locPeriod)
  17040. locPeriod = this._period = 0.3 * 1.5;
  17041. var s = locPeriod / 4;
  17042. dt = dt - 1;
  17043. if (dt < 0)
  17044. newT = -0.5 * Math.pow(2, 10 * dt) * Math.sin((dt - s) * Math.PI * 2 / locPeriod);
  17045. else
  17046. newT = Math.pow(2, -10 * dt) * Math.sin((dt - s) * Math.PI * 2 / locPeriod) * 0.5 + 1;
  17047. }
  17048. this._inner.update(newT);
  17049. },
  17050. reverse:function () {
  17051. return new cc.EaseElasticInOut(this._inner.reverse(), this._period);
  17052. },
  17053. clone:function(){
  17054. var action = new cc.EaseElasticInOut();
  17055. action.initWithAction(this._inner.clone(), this._period);
  17056. return action;
  17057. }
  17058. });
  17059. cc.EaseElasticInOut.create = function (action, period) {
  17060. return new cc.EaseElasticInOut(action, period);
  17061. };
  17062. cc.easeElasticInOut = function (period) {
  17063. period = period || 0.3;
  17064. return {
  17065. _period: period,
  17066. easing: function (dt) {
  17067. var newT = 0;
  17068. var locPeriod = this._period;
  17069. if (dt === 0 || dt === 1) {
  17070. newT = dt;
  17071. } else {
  17072. dt = dt * 2;
  17073. if (!locPeriod)
  17074. locPeriod = this._period = 0.3 * 1.5;
  17075. var s = locPeriod / 4;
  17076. dt = dt - 1;
  17077. if (dt < 0)
  17078. newT = -0.5 * Math.pow(2, 10 * dt) * Math.sin((dt - s) * Math.PI * 2 / locPeriod);
  17079. else
  17080. newT = Math.pow(2, -10 * dt) * Math.sin((dt - s) * Math.PI * 2 / locPeriod) * 0.5 + 1;
  17081. }
  17082. return newT;
  17083. },
  17084. reverse: function(){
  17085. return cc.easeElasticInOut(this._period);
  17086. }
  17087. };
  17088. };
  17089. cc.EaseBounce = cc.ActionEase.extend({
  17090. bounceTime:function (time1) {
  17091. if (time1 < 1 / 2.75) {
  17092. return 7.5625 * time1 * time1;
  17093. } else if (time1 < 2 / 2.75) {
  17094. time1 -= 1.5 / 2.75;
  17095. return 7.5625 * time1 * time1 + 0.75;
  17096. } else if (time1 < 2.5 / 2.75) {
  17097. time1 -= 2.25 / 2.75;
  17098. return 7.5625 * time1 * time1 + 0.9375;
  17099. }
  17100. time1 -= 2.625 / 2.75;
  17101. return 7.5625 * time1 * time1 + 0.984375;
  17102. },
  17103. clone:function(){
  17104. var action = new cc.EaseBounce();
  17105. action.initWithAction(this._inner.clone());
  17106. return action;
  17107. },
  17108. reverse:function () {
  17109. return new cc.EaseBounce(this._inner.reverse());
  17110. }
  17111. });
  17112. cc.EaseBounce.create = function (action) {
  17113. return new cc.EaseBounce(action);
  17114. };
  17115. cc.EaseBounceIn = cc.EaseBounce.extend({
  17116. update:function (dt) {
  17117. var newT = 1 - this.bounceTime(1 - dt);
  17118. this._inner.update(newT);
  17119. },
  17120. reverse:function () {
  17121. return new cc.EaseBounceOut(this._inner.reverse());
  17122. },
  17123. clone:function(){
  17124. var action = new cc.EaseBounceIn();
  17125. action.initWithAction(this._inner.clone());
  17126. return action;
  17127. }
  17128. });
  17129. cc.EaseBounceIn.create = function (action) {
  17130. return new cc.EaseBounceIn(action);
  17131. };
  17132. cc._bounceTime = function (time1) {
  17133. if (time1 < 1 / 2.75) {
  17134. return 7.5625 * time1 * time1;
  17135. } else if (time1 < 2 / 2.75) {
  17136. time1 -= 1.5 / 2.75;
  17137. return 7.5625 * time1 * time1 + 0.75;
  17138. } else if (time1 < 2.5 / 2.75) {
  17139. time1 -= 2.25 / 2.75;
  17140. return 7.5625 * time1 * time1 + 0.9375;
  17141. }
  17142. time1 -= 2.625 / 2.75;
  17143. return 7.5625 * time1 * time1 + 0.984375;
  17144. };
  17145. cc._easeBounceInObj = {
  17146. easing: function(dt){
  17147. return 1 - cc._bounceTime(1 - dt);
  17148. },
  17149. reverse: function(){
  17150. return cc._easeBounceOutObj;
  17151. }
  17152. };
  17153. cc.easeBounceIn = function(){
  17154. return cc._easeBounceInObj;
  17155. };
  17156. cc.EaseBounceOut = cc.EaseBounce.extend({
  17157. update:function (dt) {
  17158. var newT = this.bounceTime(dt);
  17159. this._inner.update(newT);
  17160. },
  17161. reverse:function () {
  17162. return new cc.EaseBounceIn(this._inner.reverse());
  17163. },
  17164. clone:function(){
  17165. var action = new cc.EaseBounceOut();
  17166. action.initWithAction(this._inner.clone());
  17167. return action;
  17168. }
  17169. });
  17170. cc.EaseBounceOut.create = function (action) {
  17171. return new cc.EaseBounceOut(action);
  17172. };
  17173. cc._easeBounceOutObj = {
  17174. easing: function(dt){
  17175. return cc._bounceTime(dt);
  17176. },
  17177. reverse:function () {
  17178. return cc._easeBounceInObj;
  17179. }
  17180. };
  17181. cc.easeBounceOut = function(){
  17182. return cc._easeBounceOutObj;
  17183. };
  17184. cc.EaseBounceInOut = cc.EaseBounce.extend({
  17185. update:function (dt) {
  17186. var newT = 0;
  17187. if (dt < 0.5) {
  17188. dt = dt * 2;
  17189. newT = (1 - this.bounceTime(1 - dt)) * 0.5;
  17190. } else {
  17191. newT = this.bounceTime(dt * 2 - 1) * 0.5 + 0.5;
  17192. }
  17193. this._inner.update(newT);
  17194. },
  17195. clone:function(){
  17196. var action = new cc.EaseBounceInOut();
  17197. action.initWithAction(this._inner.clone());
  17198. return action;
  17199. },
  17200. reverse:function () {
  17201. return new cc.EaseBounceInOut(this._inner.reverse());
  17202. }
  17203. });
  17204. cc.EaseBounceInOut.create = function (action) {
  17205. return new cc.EaseBounceInOut(action);
  17206. };
  17207. cc._easeBounceInOutObj = {
  17208. easing: function (time1) {
  17209. var newT;
  17210. if (time1 < 0.5) {
  17211. time1 = time1 * 2;
  17212. newT = (1 - cc._bounceTime(1 - time1)) * 0.5;
  17213. } else {
  17214. newT = cc._bounceTime(time1 * 2 - 1) * 0.5 + 0.5;
  17215. }
  17216. return newT;
  17217. },
  17218. reverse: function(){
  17219. return cc._easeBounceInOutObj;
  17220. }
  17221. };
  17222. cc.easeBounceInOut = function(){
  17223. return cc._easeBounceInOutObj;
  17224. };
  17225. cc.EaseBackIn = cc.ActionEase.extend({
  17226. update:function (dt) {
  17227. var overshoot = 1.70158;
  17228. dt = dt===0 || dt===1 ? dt : dt * dt * ((overshoot + 1) * dt - overshoot);
  17229. this._inner.update(dt);
  17230. },
  17231. reverse:function () {
  17232. return new cc.EaseBackOut(this._inner.reverse());
  17233. },
  17234. clone:function(){
  17235. var action = new cc.EaseBackIn();
  17236. action.initWithAction(this._inner.clone());
  17237. return action;
  17238. }
  17239. });
  17240. cc.EaseBackIn.create = function (action) {
  17241. return new cc.EaseBackIn(action);
  17242. };
  17243. cc._easeBackInObj = {
  17244. easing: function (time1) {
  17245. var overshoot = 1.70158;
  17246. return (time1===0 || time1===1) ? time1 : time1 * time1 * ((overshoot + 1) * time1 - overshoot);
  17247. },
  17248. reverse: function(){
  17249. return cc._easeBackOutObj;
  17250. }
  17251. };
  17252. cc.easeBackIn = function(){
  17253. return cc._easeBackInObj;
  17254. };
  17255. cc.EaseBackOut = cc.ActionEase.extend({
  17256. update:function (dt) {
  17257. var overshoot = 1.70158;
  17258. dt = dt - 1;
  17259. this._inner.update(dt * dt * ((overshoot + 1) * dt + overshoot) + 1);
  17260. },
  17261. reverse:function () {
  17262. return new cc.EaseBackIn(this._inner.reverse());
  17263. },
  17264. clone:function(){
  17265. var action = new cc.EaseBackOut();
  17266. action.initWithAction(this._inner.clone());
  17267. return action;
  17268. }
  17269. });
  17270. cc.EaseBackOut.create = function (action) {
  17271. return new cc.EaseBackOut(action);
  17272. };
  17273. cc._easeBackOutObj = {
  17274. easing: function (time1) {
  17275. var overshoot = 1.70158;
  17276. time1 = time1 - 1;
  17277. return time1 * time1 * ((overshoot + 1) * time1 + overshoot) + 1;
  17278. },
  17279. reverse: function(){
  17280. return cc._easeBackInObj;
  17281. }
  17282. };
  17283. cc.easeBackOut = function(){
  17284. return cc._easeBackOutObj;
  17285. };
  17286. cc.EaseBackInOut = cc.ActionEase.extend({
  17287. update:function (dt) {
  17288. var overshoot = 1.70158 * 1.525;
  17289. dt = dt * 2;
  17290. if (dt < 1) {
  17291. this._inner.update((dt * dt * ((overshoot + 1) * dt - overshoot)) / 2);
  17292. } else {
  17293. dt = dt - 2;
  17294. this._inner.update((dt * dt * ((overshoot + 1) * dt + overshoot)) / 2 + 1);
  17295. }
  17296. },
  17297. clone:function(){
  17298. var action = new cc.EaseBackInOut();
  17299. action.initWithAction(this._inner.clone());
  17300. return action;
  17301. },
  17302. reverse:function () {
  17303. return new cc.EaseBackInOut(this._inner.reverse());
  17304. }
  17305. });
  17306. cc.EaseBackInOut.create = function (action) {
  17307. return new cc.EaseBackInOut(action);
  17308. };
  17309. cc._easeBackInOutObj = {
  17310. easing: function (time1) {
  17311. var overshoot = 1.70158 * 1.525;
  17312. time1 = time1 * 2;
  17313. if (time1 < 1) {
  17314. return (time1 * time1 * ((overshoot + 1) * time1 - overshoot)) / 2;
  17315. } else {
  17316. time1 = time1 - 2;
  17317. return (time1 * time1 * ((overshoot + 1) * time1 + overshoot)) / 2 + 1;
  17318. }
  17319. },
  17320. reverse: function(){
  17321. return cc._easeBackInOutObj;
  17322. }
  17323. };
  17324. cc.easeBackInOut = function(){
  17325. return cc._easeBackInOutObj;
  17326. };
  17327. cc.EaseBezierAction = cc.ActionEase.extend({
  17328. _p0: null,
  17329. _p1: null,
  17330. _p2: null,
  17331. _p3: null,
  17332. ctor: function(action){
  17333. cc.ActionEase.prototype.ctor.call(this, action);
  17334. },
  17335. _updateTime: function(a, b, c, d, t){
  17336. return (Math.pow(1-t,3) * a + 3*t*(Math.pow(1-t,2))*b + 3*Math.pow(t,2)*(1-t)*c + Math.pow(t,3)*d );
  17337. },
  17338. update: function(dt){
  17339. var t = this._updateTime(this._p0, this._p1, this._p2, this._p3, dt);
  17340. this._inner.update(t);
  17341. },
  17342. clone: function(){
  17343. var action = new cc.EaseBezierAction();
  17344. action.initWithAction(this._inner.clone());
  17345. action.setBezierParamer(this._p0, this._p1, this._p2, this._p3);
  17346. return action;
  17347. },
  17348. reverse: function(){
  17349. var action = new cc.EaseBezierAction(this._inner.reverse());
  17350. action.setBezierParamer(this._p3, this._p2, this._p1, this._p0);
  17351. return action;
  17352. },
  17353. setBezierParamer: function(p0, p1, p2, p3){
  17354. this._p0 = p0 || 0;
  17355. this._p1 = p1 || 0;
  17356. this._p2 = p2 || 0;
  17357. this._p3 = p3 || 0;
  17358. }
  17359. });
  17360. cc.EaseBezierAction.create = function(action){
  17361. return new cc.EaseBezierAction(action);
  17362. };
  17363. cc.easeBezierAction = function(p0, p1, p2, p3){
  17364. return {
  17365. easing: function(time){
  17366. return cc.EaseBezierAction.prototype._updateTime(p0, p1, p2, p3, time);
  17367. },
  17368. reverse: function(){
  17369. return cc.easeBezierAction(p3, p2, p1, p0);
  17370. }
  17371. };
  17372. };
  17373. cc.EaseQuadraticActionIn = cc.ActionEase.extend({
  17374. _updateTime: function(time){
  17375. return Math.pow(time, 2);
  17376. },
  17377. update: function(dt){
  17378. this._inner.update(this._updateTime(dt));
  17379. },
  17380. clone: function(){
  17381. var action = new cc.EaseQuadraticActionIn();
  17382. action.initWithAction(this._inner.clone());
  17383. return action;
  17384. },
  17385. reverse: function(){
  17386. return new cc.EaseQuadraticActionIn(this._inner.reverse());
  17387. }
  17388. });
  17389. cc.EaseQuadraticActionIn.create = function(action){
  17390. return new cc.EaseQuadraticActionIn(action);
  17391. };
  17392. cc._easeQuadraticActionIn = {
  17393. easing: cc.EaseQuadraticActionIn.prototype._updateTime,
  17394. reverse: function(){
  17395. return cc._easeQuadraticActionIn;
  17396. }
  17397. };
  17398. cc.easeQuadraticActionIn = function(){
  17399. return cc._easeQuadraticActionIn;
  17400. };
  17401. cc.EaseQuadraticActionOut = cc.ActionEase.extend({
  17402. _updateTime: function(time){
  17403. return -time*(time-2);
  17404. },
  17405. update: function(dt){
  17406. this._inner.update(this._updateTime(dt));
  17407. },
  17408. clone: function(){
  17409. var action = new cc.EaseQuadraticActionOut();
  17410. action.initWithAction();
  17411. return action;
  17412. },
  17413. reverse: function(){
  17414. return new cc.EaseQuadraticActionOut(this._inner.reverse());
  17415. }
  17416. });
  17417. cc.EaseQuadraticActionOut.create = function(action){
  17418. return new cc.EaseQuadraticActionOut(action);
  17419. };
  17420. cc._easeQuadraticActionOut = {
  17421. easing: cc.EaseQuadraticActionOut.prototype._updateTime,
  17422. reverse: function(){
  17423. return cc._easeQuadraticActionOut;
  17424. }
  17425. };
  17426. cc.easeQuadraticActionOut = function(){
  17427. return cc._easeQuadraticActionOut;
  17428. };
  17429. cc.EaseQuadraticActionInOut = cc.ActionEase.extend({
  17430. _updateTime: function(time){
  17431. var resultTime = time;
  17432. time *= 2;
  17433. if(time < 1){
  17434. resultTime = time * time * 0.5;
  17435. }else{
  17436. --time;
  17437. resultTime = -0.5 * ( time * ( time - 2 ) - 1)
  17438. }
  17439. return resultTime;
  17440. },
  17441. update: function(dt){
  17442. this._inner.update(this._updateTime(dt));
  17443. },
  17444. clone: function(){
  17445. var action = new cc.EaseQuadraticActionInOut();
  17446. action.initWithAction(this._inner.clone());
  17447. return action;
  17448. },
  17449. reverse: function(){
  17450. return new cc.EaseQuadraticActionInOut(this._inner.reverse());
  17451. }
  17452. });
  17453. cc.EaseQuadraticActionInOut.create = function(action){
  17454. return new cc.EaseQuadraticActionInOut(action);
  17455. };
  17456. cc._easeQuadraticActionInOut = {
  17457. easing: cc.EaseQuadraticActionInOut.prototype._updateTime,
  17458. reverse: function(){
  17459. return cc._easeQuadraticActionInOut;
  17460. }
  17461. };
  17462. cc.easeQuadraticActionInOut = function(){
  17463. return cc._easeQuadraticActionInOut;
  17464. };
  17465. cc.EaseQuarticActionIn = cc.ActionEase.extend({
  17466. _updateTime: function(time){
  17467. return time * time * time * time;
  17468. },
  17469. update: function(dt){
  17470. this._inner.update(this._updateTime(dt));
  17471. },
  17472. clone: function(){
  17473. var action = new cc.EaseQuarticActionIn();
  17474. action.initWithAction(this._inner.clone());
  17475. return action;
  17476. },
  17477. reverse: function(){
  17478. return new cc.EaseQuarticActionIn(this._inner.reverse());
  17479. }
  17480. });
  17481. cc.EaseQuarticActionIn.create = function(action){
  17482. return new cc.EaseQuarticActionIn(action);
  17483. };
  17484. cc._easeQuarticActionIn = {
  17485. easing: cc.EaseQuarticActionIn.prototype._updateTime,
  17486. reverse: function(){
  17487. return cc._easeQuarticActionIn;
  17488. }
  17489. };
  17490. cc.easeQuarticActionIn = function(){
  17491. return cc._easeQuarticActionIn;
  17492. };
  17493. cc.EaseQuarticActionOut = cc.ActionEase.extend({
  17494. _updateTime: function(time){
  17495. time -= 1;
  17496. return -(time * time * time * time - 1);
  17497. },
  17498. update: function(dt){
  17499. this._inner.update(this._updateTime(dt));
  17500. },
  17501. clone: function(){
  17502. var action = new cc.EaseQuarticActionOut();
  17503. action.initWithAction(this._inner.clone());
  17504. return action;
  17505. },
  17506. reverse: function(){
  17507. return new cc.EaseQuarticActionOut(this._inner.reverse());
  17508. }
  17509. });
  17510. cc.EaseQuarticActionOut.create = function(action){
  17511. return new cc.EaseQuarticActionOut(action);
  17512. };
  17513. cc._easeQuarticActionOut = {
  17514. easing: cc.EaseQuarticActionOut.prototype._updateTime,
  17515. reverse: function(){
  17516. return cc._easeQuarticActionOut;
  17517. }
  17518. };
  17519. cc.easeQuarticActionOut = function(){
  17520. return cc._easeQuarticActionOut;
  17521. };
  17522. cc.EaseQuarticActionInOut = cc.ActionEase.extend({
  17523. _updateTime: function(time){
  17524. time = time*2;
  17525. if (time < 1)
  17526. return 0.5 * time * time * time * time;
  17527. time -= 2;
  17528. return -0.5 * (time * time * time * time - 2);
  17529. },
  17530. update: function(dt){
  17531. this._inner.update(this._updateTime(dt));
  17532. },
  17533. clone: function(){
  17534. var action = new cc.EaseQuarticActionInOut();
  17535. action.initWithAction(this._inner.clone());
  17536. return action;
  17537. },
  17538. reverse: function(){
  17539. return new cc.EaseQuarticActionInOut(this._inner.reverse());
  17540. }
  17541. });
  17542. cc.EaseQuarticActionInOut.create = function(action){
  17543. return new cc.EaseQuarticActionInOut(action);
  17544. };
  17545. cc._easeQuarticActionInOut = {
  17546. easing: cc.EaseQuarticActionInOut.prototype._updateTime,
  17547. reverse: function(){
  17548. return cc._easeQuarticActionInOut;
  17549. }
  17550. };
  17551. cc.easeQuarticActionInOut = function(){
  17552. return cc._easeQuarticActionInOut;
  17553. };
  17554. cc.EaseQuinticActionIn = cc.ActionEase.extend({
  17555. _updateTime: function(time){
  17556. return time * time * time * time * time;
  17557. },
  17558. update: function(dt){
  17559. this._inner.update(this._updateTime(dt));
  17560. },
  17561. clone: function(){
  17562. var action = new cc.EaseQuinticActionIn();
  17563. action.initWithAction(this._inner.clone());
  17564. return action;
  17565. },
  17566. reverse: function(){
  17567. return new cc.EaseQuinticActionIn(this._inner.reverse());
  17568. }
  17569. });
  17570. cc.EaseQuinticActionIn.create = function(action){
  17571. return new cc.EaseQuinticActionIn(action);
  17572. };
  17573. cc._easeQuinticActionIn = {
  17574. easing: cc.EaseQuinticActionIn.prototype._updateTime,
  17575. reverse: function(){
  17576. return cc._easeQuinticActionIn;
  17577. }
  17578. };
  17579. cc.easeQuinticActionIn = function(){
  17580. return cc._easeQuinticActionIn;
  17581. };
  17582. cc.EaseQuinticActionOut = cc.ActionEase.extend({
  17583. _updateTime: function(time){
  17584. time -=1;
  17585. return (time * time * time * time * time + 1);
  17586. },
  17587. update: function(dt){
  17588. this._inner.update(this._updateTime(dt));
  17589. },
  17590. clone: function(){
  17591. var action = new cc.EaseQuinticActionOut();
  17592. action.initWithAction(this._inner.clone());
  17593. return action;
  17594. },
  17595. reverse: function(){
  17596. return new cc.EaseQuinticActionOut(this._inner.reverse());
  17597. }
  17598. });
  17599. cc.EaseQuinticActionOut.create = function(action){
  17600. return new cc.EaseQuinticActionOut(action);
  17601. };
  17602. cc._easeQuinticActionOut = {
  17603. easing: cc.EaseQuinticActionOut.prototype._updateTime,
  17604. reverse: function(){
  17605. return cc._easeQuinticActionOut;
  17606. }
  17607. };
  17608. cc.easeQuinticActionOut = function(){
  17609. return cc._easeQuinticActionOut;
  17610. };
  17611. cc.EaseQuinticActionInOut = cc.ActionEase.extend({
  17612. _updateTime: function(time){
  17613. time = time*2;
  17614. if (time < 1)
  17615. return 0.5 * time * time * time * time * time;
  17616. time -= 2;
  17617. return 0.5 * (time * time * time * time * time + 2);
  17618. },
  17619. update: function(dt){
  17620. this._inner.update(this._updateTime(dt));
  17621. },
  17622. clone: function(){
  17623. var action = new cc.EaseQuinticActionInOut();
  17624. action.initWithAction(this._inner.clone());
  17625. return action;
  17626. },
  17627. reverse: function(){
  17628. return new cc.EaseQuinticActionInOut(this._inner.reverse());
  17629. }
  17630. });
  17631. cc.EaseQuinticActionInOut.create = function(action){
  17632. return new cc.EaseQuinticActionInOut(action);
  17633. };
  17634. cc._easeQuinticActionInOut = {
  17635. easing: cc.EaseQuinticActionInOut.prototype._updateTime,
  17636. reverse: function(){
  17637. return cc._easeQuinticActionInOut;
  17638. }
  17639. };
  17640. cc.easeQuinticActionInOut = function(){
  17641. return cc._easeQuinticActionInOut;
  17642. };
  17643. cc.EaseCircleActionIn = cc.ActionEase.extend({
  17644. _updateTime: function(time){
  17645. return -1 * (Math.sqrt(1 - time * time) - 1);
  17646. },
  17647. update: function(dt){
  17648. this._inner.update(this._updateTime(dt));
  17649. },
  17650. clone: function(){
  17651. var action = new cc.EaseCircleActionIn();
  17652. action.initWithAction(this._inner.clone());
  17653. return action;
  17654. },
  17655. reverse: function(){
  17656. return new cc.EaseCircleActionIn(this._inner.reverse());
  17657. }
  17658. });
  17659. cc.EaseCircleActionIn.create = function(action){
  17660. return new cc.EaseCircleActionIn(action);
  17661. };
  17662. cc._easeCircleActionIn = {
  17663. easing: cc.EaseCircleActionIn.prototype._updateTime,
  17664. reverse: function(){
  17665. return cc._easeCircleActionIn;
  17666. }
  17667. };
  17668. cc.easeCircleActionIn = function(){
  17669. return cc._easeCircleActionIn;
  17670. };
  17671. cc.EaseCircleActionOut = cc.ActionEase.extend({
  17672. _updateTime: function(time){
  17673. time = time - 1;
  17674. return Math.sqrt(1 - time * time);
  17675. },
  17676. update: function(dt){
  17677. this._inner.update(this._updateTime(dt));
  17678. },
  17679. clone: function(){
  17680. var action = new cc.EaseCircleActionOut();
  17681. action.initWithAction(this._inner.clone());
  17682. return action;
  17683. },
  17684. reverse: function(){
  17685. return new cc.EaseCircleActionOut(this._inner.reverse());
  17686. }
  17687. });
  17688. cc.EaseCircleActionOut.create = function(action){
  17689. return new cc.EaseCircleActionOut(action);
  17690. };
  17691. cc._easeCircleActionOut = {
  17692. easing: cc.EaseCircleActionOut.prototype._updateTime,
  17693. reverse: function(){
  17694. return cc._easeCircleActionOut;
  17695. }
  17696. };
  17697. cc.easeCircleActionOut = function(){
  17698. return cc._easeCircleActionOut;
  17699. };
  17700. cc.EaseCircleActionInOut = cc.ActionEase.extend({
  17701. _updateTime: function(time){
  17702. time = time * 2;
  17703. if (time < 1)
  17704. return -0.5 * (Math.sqrt(1 - time * time) - 1);
  17705. time -= 2;
  17706. return 0.5 * (Math.sqrt(1 - time * time) + 1);
  17707. },
  17708. update: function(dt){
  17709. this._inner.update(this._updateTime(dt));
  17710. },
  17711. clone: function(){
  17712. var action = new cc.EaseCircleActionInOut();
  17713. action.initWithAction(this._inner.clone());
  17714. return action;
  17715. },
  17716. reverse: function(){
  17717. return new cc.EaseCircleActionInOut(this._inner.reverse());
  17718. }
  17719. });
  17720. cc.EaseCircleActionInOut.create = function(action){
  17721. return new cc.EaseCircleActionInOut(action);
  17722. };
  17723. cc._easeCircleActionInOut = {
  17724. easing: cc.EaseCircleActionInOut.prototype._updateTime,
  17725. reverse: function(){
  17726. return cc._easeCircleActionInOut;
  17727. }
  17728. };
  17729. cc.easeCircleActionInOut = function(){
  17730. return cc._easeCircleActionInOut;
  17731. };
  17732. cc.EaseCubicActionIn = cc.ActionEase.extend({
  17733. _updateTime: function(time){
  17734. return time * time * time;
  17735. },
  17736. update: function(dt){
  17737. this._inner.update(this._updateTime(dt));
  17738. },
  17739. clone: function(){
  17740. var action = new cc.EaseCubicActionIn();
  17741. action.initWithAction(this._inner.clone());
  17742. return action;
  17743. },
  17744. reverse: function(){
  17745. return new cc.EaseCubicActionIn(this._inner.reverse());
  17746. }
  17747. });
  17748. cc.EaseCubicActionIn.create = function(action){
  17749. return new cc.EaseCubicActionIn(action);
  17750. };
  17751. cc._easeCubicActionIn = {
  17752. easing: cc.EaseCubicActionIn.prototype._updateTime,
  17753. reverse: function(){
  17754. return cc._easeCubicActionIn;
  17755. }
  17756. };
  17757. cc.easeCubicActionIn = function(){
  17758. return cc._easeCubicActionIn;
  17759. };
  17760. cc.EaseCubicActionOut = cc.ActionEase.extend({
  17761. _updateTime: function(time){
  17762. time -= 1;
  17763. return (time * time * time + 1);
  17764. },
  17765. update: function(dt){
  17766. this._inner.update(this._updateTime(dt));
  17767. },
  17768. clone: function(){
  17769. var action = new cc.EaseCubicActionOut();
  17770. action.initWithAction(this._inner.clone());
  17771. return action;
  17772. },
  17773. reverse: function(){
  17774. return new cc.EaseCubicActionOut(this._inner.reverse());
  17775. }
  17776. });
  17777. cc.EaseCubicActionOut.create = function(action){
  17778. return new cc.EaseCubicActionOut(action);
  17779. };
  17780. cc._easeCubicActionOut = {
  17781. easing: cc.EaseCubicActionOut.prototype._updateTime,
  17782. reverse: function(){
  17783. return cc._easeCubicActionOut;
  17784. }
  17785. };
  17786. cc.easeCubicActionOut = function(){
  17787. return cc._easeCubicActionOut;
  17788. };
  17789. cc.EaseCubicActionInOut = cc.ActionEase.extend({
  17790. _updateTime: function(time){
  17791. time = time*2;
  17792. if (time < 1)
  17793. return 0.5 * time * time * time;
  17794. time -= 2;
  17795. return 0.5 * (time * time * time + 2);
  17796. },
  17797. update: function(dt){
  17798. this._inner.update(this._updateTime(dt));
  17799. },
  17800. clone: function(){
  17801. var action = new cc.EaseCubicActionInOut();
  17802. action.initWithAction(this._inner.clone());
  17803. return action;
  17804. },
  17805. reverse: function(){
  17806. return new cc.EaseCubicActionInOut(this._inner.reverse());
  17807. }
  17808. });
  17809. cc.EaseCubicActionInOut.create = function(action){
  17810. return new cc.EaseCubicActionInOut(action);
  17811. };
  17812. cc._easeCubicActionInOut = {
  17813. easing: cc.EaseCubicActionInOut.prototype._updateTime,
  17814. reverse: function(){
  17815. return cc._easeCubicActionInOut;
  17816. }
  17817. };
  17818. cc.easeCubicActionInOut = function(){
  17819. return cc._easeCubicActionInOut;
  17820. };
  17821. cc.cardinalSplineAt = function (p0, p1, p2, p3, tension, t) {
  17822. var t2 = t * t;
  17823. var t3 = t2 * t;
  17824. var s = (1 - tension) / 2;
  17825. var b1 = s * ((-t3 + (2 * t2)) - t);
  17826. var b2 = s * (-t3 + t2) + (2 * t3 - 3 * t2 + 1);
  17827. var b3 = s * (t3 - 2 * t2 + t) + (-2 * t3 + 3 * t2);
  17828. var b4 = s * (t3 - t2);
  17829. var x = (p0.x * b1 + p1.x * b2 + p2.x * b3 + p3.x * b4);
  17830. var y = (p0.y * b1 + p1.y * b2 + p2.y * b3 + p3.y * b4);
  17831. return cc.p(x, y);
  17832. };
  17833. cc.reverseControlPoints = function (controlPoints) {
  17834. var newArray = [];
  17835. for (var i = controlPoints.length - 1; i >= 0; i--) {
  17836. newArray.push(cc.p(controlPoints[i].x, controlPoints[i].y));
  17837. }
  17838. return newArray;
  17839. };
  17840. cc.cloneControlPoints = function (controlPoints) {
  17841. var newArray = [];
  17842. for (var i = 0; i < controlPoints.length; i++)
  17843. newArray.push(cc.p(controlPoints[i].x, controlPoints[i].y));
  17844. return newArray;
  17845. };
  17846. cc.copyControlPoints = cc.cloneControlPoints;
  17847. cc.getControlPointAt = function (controlPoints, pos) {
  17848. var p = Math.min(controlPoints.length - 1, Math.max(pos, 0));
  17849. return controlPoints[p];
  17850. };
  17851. cc.reverseControlPointsInline = function (controlPoints) {
  17852. var len = controlPoints.length;
  17853. var mid = 0 | (len / 2);
  17854. for (var i = 0; i < mid; ++i) {
  17855. var temp = controlPoints[i];
  17856. controlPoints[i] = controlPoints[len - i - 1];
  17857. controlPoints[len - i - 1] = temp;
  17858. }
  17859. };
  17860. cc.CardinalSplineTo = cc.ActionInterval.extend({
  17861. _points:null,
  17862. _deltaT:0,
  17863. _tension:0,
  17864. _previousPosition:null,
  17865. _accumulatedDiff:null,
  17866. ctor: function (duration, points, tension) {
  17867. cc.ActionInterval.prototype.ctor.call(this);
  17868. this._points = [];
  17869. tension !== undefined && this.initWithDuration(duration, points, tension);
  17870. },
  17871. initWithDuration:function (duration, points, tension) {
  17872. if(!points || points.length === 0)
  17873. throw new Error("Invalid configuration. It must at least have one control point");
  17874. if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) {
  17875. this.setPoints(points);
  17876. this._tension = tension;
  17877. return true;
  17878. }
  17879. return false;
  17880. },
  17881. clone:function () {
  17882. var action = new cc.CardinalSplineTo();
  17883. action.initWithDuration(this._duration, cc.copyControlPoints(this._points), this._tension);
  17884. return action;
  17885. },
  17886. startWithTarget:function (target) {
  17887. cc.ActionInterval.prototype.startWithTarget.call(this, target);
  17888. this._deltaT = 1 / (this._points.length - 1);
  17889. this._previousPosition = cc.p(this.target.getPositionX(), this.target.getPositionY());
  17890. this._accumulatedDiff = cc.p(0, 0);
  17891. },
  17892. update:function (dt) {
  17893. dt = this._computeEaseTime(dt);
  17894. var p, lt;
  17895. var ps = this._points;
  17896. if (dt === 1) {
  17897. p = ps.length - 1;
  17898. lt = 1;
  17899. } else {
  17900. var locDT = this._deltaT;
  17901. p = 0 | (dt / locDT);
  17902. lt = (dt - locDT * p) / locDT;
  17903. }
  17904. var newPos = cc.cardinalSplineAt(
  17905. cc.getControlPointAt(ps, p - 1),
  17906. cc.getControlPointAt(ps, p - 0),
  17907. cc.getControlPointAt(ps, p + 1),
  17908. cc.getControlPointAt(ps, p + 2),
  17909. this._tension, lt);
  17910. if (cc.ENABLE_STACKABLE_ACTIONS) {
  17911. var tempX, tempY;
  17912. tempX = this.target.getPositionX() - this._previousPosition.x;
  17913. tempY = this.target.getPositionY() - this._previousPosition.y;
  17914. if (tempX !== 0 || tempY !== 0) {
  17915. var locAccDiff = this._accumulatedDiff;
  17916. tempX = locAccDiff.x + tempX;
  17917. tempY = locAccDiff.y + tempY;
  17918. locAccDiff.x = tempX;
  17919. locAccDiff.y = tempY;
  17920. newPos.x += tempX;
  17921. newPos.y += tempY;
  17922. }
  17923. }
  17924. this.updatePosition(newPos);
  17925. },
  17926. reverse:function () {
  17927. var reversePoints = cc.reverseControlPoints(this._points);
  17928. return cc.cardinalSplineTo(this._duration, reversePoints, this._tension);
  17929. },
  17930. updatePosition:function (newPos) {
  17931. this.target.setPosition(newPos);
  17932. this._previousPosition = newPos;
  17933. },
  17934. getPoints:function () {
  17935. return this._points;
  17936. },
  17937. setPoints:function (points) {
  17938. this._points = points;
  17939. }
  17940. });
  17941. cc.cardinalSplineTo = function (duration, points, tension) {
  17942. return new cc.CardinalSplineTo(duration, points, tension);
  17943. };
  17944. cc.CardinalSplineTo.create = cc.cardinalSplineTo;
  17945. cc.CardinalSplineBy = cc.CardinalSplineTo.extend({
  17946. _startPosition:null,
  17947. ctor:function (duration, points, tension) {
  17948. cc.CardinalSplineTo.prototype.ctor.call(this);
  17949. this._startPosition = cc.p(0, 0);
  17950. tension !== undefined && this.initWithDuration(duration, points, tension);
  17951. },
  17952. startWithTarget:function (target) {
  17953. cc.CardinalSplineTo.prototype.startWithTarget.call(this, target);
  17954. this._startPosition.x = target.getPositionX();
  17955. this._startPosition.y = target.getPositionY();
  17956. },
  17957. reverse:function () {
  17958. var copyConfig = this._points.slice();
  17959. var current;
  17960. var p = copyConfig[0];
  17961. for (var i = 1; i < copyConfig.length; ++i) {
  17962. current = copyConfig[i];
  17963. copyConfig[i] = cc.pSub(current, p);
  17964. p = current;
  17965. }
  17966. var reverseArray = cc.reverseControlPoints(copyConfig);
  17967. p = reverseArray[ reverseArray.length - 1 ];
  17968. reverseArray.pop();
  17969. p.x = -p.x;
  17970. p.y = -p.y;
  17971. reverseArray.unshift(p);
  17972. for (var i = 1; i < reverseArray.length; ++i) {
  17973. current = reverseArray[i];
  17974. current.x = -current.x;
  17975. current.y = -current.y;
  17976. current.x += p.x;
  17977. current.y += p.y;
  17978. reverseArray[i] = current;
  17979. p = current;
  17980. }
  17981. return cc.cardinalSplineBy(this._duration, reverseArray, this._tension);
  17982. },
  17983. updatePosition:function (newPos) {
  17984. var pos = this._startPosition;
  17985. var posX = newPos.x + pos.x;
  17986. var posY = newPos.y + pos.y;
  17987. this._previousPosition.x = posX;
  17988. this._previousPosition.y = posY;
  17989. this.target.setPosition(posX, posY);
  17990. },
  17991. clone:function () {
  17992. var a = new cc.CardinalSplineBy();
  17993. a.initWithDuration(this._duration, cc.copyControlPoints(this._points), this._tension);
  17994. return a;
  17995. }
  17996. });
  17997. cc.cardinalSplineBy = function (duration, points, tension) {
  17998. return new cc.CardinalSplineBy(duration, points, tension);
  17999. };
  18000. cc.CardinalSplineBy.create = cc.cardinalSplineBy;
  18001. cc.CatmullRomTo = cc.CardinalSplineTo.extend({
  18002. ctor: function(dt, points) {
  18003. points && this.initWithDuration(dt, points);
  18004. },
  18005. initWithDuration:function (dt, points) {
  18006. return cc.CardinalSplineTo.prototype.initWithDuration.call(this, dt, points, 0.5);
  18007. },
  18008. clone:function () {
  18009. var action = new cc.CatmullRomTo();
  18010. action.initWithDuration(this._duration, cc.copyControlPoints(this._points));
  18011. return action;
  18012. }
  18013. });
  18014. cc.catmullRomTo = function (dt, points) {
  18015. return new cc.CatmullRomTo(dt, points);
  18016. };
  18017. cc.CatmullRomTo.create = cc.catmullRomTo;
  18018. cc.CatmullRomBy = cc.CardinalSplineBy.extend({
  18019. ctor: function(dt, points) {
  18020. cc.CardinalSplineBy.prototype.ctor.call(this);
  18021. points && this.initWithDuration(dt, points);
  18022. },
  18023. initWithDuration:function (dt, points) {
  18024. return cc.CardinalSplineTo.prototype.initWithDuration.call(this, dt, points, 0.5);
  18025. },
  18026. clone:function () {
  18027. var action = new cc.CatmullRomBy();
  18028. action.initWithDuration(this._duration, cc.copyControlPoints(this._points));
  18029. return action;
  18030. }
  18031. });
  18032. cc.catmullRomBy = function (dt, points) {
  18033. return new cc.CatmullRomBy(dt, points);
  18034. };
  18035. cc.CatmullRomBy.create = cc.catmullRomBy;
  18036. cc.ActionTweenDelegate = cc.Class.extend({
  18037. updateTweenAction:function(value, key){}
  18038. });
  18039. cc.ActionTween = cc.ActionInterval.extend({
  18040. key:"",
  18041. from:0,
  18042. to:0,
  18043. delta:0,
  18044. ctor:function(duration, key, from, to){
  18045. cc.ActionInterval.prototype.ctor.call(this);
  18046. this.key = "";
  18047. to !== undefined && this.initWithDuration(duration, key, from, to);
  18048. },
  18049. initWithDuration:function (duration, key, from, to) {
  18050. if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) {
  18051. this.key = key;
  18052. this.to = to;
  18053. this.from = from;
  18054. return true;
  18055. }
  18056. return false;
  18057. },
  18058. startWithTarget:function (target) {
  18059. if(!target || !target.updateTweenAction)
  18060. throw new Error("cc.ActionTween.startWithTarget(): target must be non-null, and target must implement updateTweenAction function");
  18061. cc.ActionInterval.prototype.startWithTarget.call(this, target);
  18062. this.delta = this.to - this.from;
  18063. },
  18064. update:function (dt) {
  18065. this.target.updateTweenAction(this.to - this.delta * (1 - dt), this.key);
  18066. },
  18067. reverse:function () {
  18068. return new cc.ActionTween(this.duration, this.key, this.to, this.from);
  18069. },
  18070. clone:function(){
  18071. var action = new cc.ActionTween();
  18072. action.initWithDuration(this._duration, this.key, this.from, this.to);
  18073. return action;
  18074. }
  18075. });
  18076. cc.actionTween = function (duration, key, from, to) {
  18077. return new cc.ActionTween(duration, key, from, to);
  18078. };
  18079. cc.ActionTween.create = cc.actionTween;
  18080. (function(){
  18081. var DEBUG = false;
  18082. var sys = cc.sys;
  18083. var version = sys.browserVersion;
  18084. var supportWebAudio = !!(window.AudioContext || window.webkitAudioContext || window.mozAudioContext);
  18085. var support = {ONLY_ONE: false, WEB_AUDIO: supportWebAudio, DELAY_CREATE_CTX: false, ONE_SOURCE: false };
  18086. if (sys.browserType === sys.BROWSER_TYPE_FIREFOX) {
  18087. support.DELAY_CREATE_CTX = true;
  18088. support.USE_LOADER_EVENT = 'canplay';
  18089. }
  18090. if (sys.os === sys.OS_IOS) {
  18091. support.USE_LOADER_EVENT = 'loadedmetadata';
  18092. }
  18093. if (sys.os === sys.OS_ANDROID) {
  18094. if (sys.browserType === sys.BROWSER_TYPE_UC) {
  18095. support.ONE_SOURCE = true;
  18096. }
  18097. }
  18098. window.__audioSupport = support;
  18099. if(DEBUG){
  18100. setTimeout(function(){
  18101. cc.log("browse type: " + sys.browserType);
  18102. cc.log("browse version: " + version);
  18103. cc.log("MULTI_CHANNEL: " + window.__audioSupport.MULTI_CHANNEL);
  18104. cc.log("WEB_AUDIO: " + window.__audioSupport.WEB_AUDIO);
  18105. cc.log("AUTOPLAY: " + window.__audioSupport.AUTOPLAY);
  18106. }, 0);
  18107. }
  18108. })();
  18109. cc.Audio = cc.Class.extend({
  18110. src: null,
  18111. _element: null,
  18112. _AUDIO_TYPE: "AUDIO",
  18113. ctor: function(url){
  18114. this.src = url;
  18115. },
  18116. setBuffer: function (buffer) {
  18117. this._AUDIO_TYPE = "WEBAUDIO";
  18118. this._element = new cc.Audio.WebAudio(buffer);
  18119. },
  18120. setElement: function (element) {
  18121. this._AUDIO_TYPE = "AUDIO";
  18122. this._element = element;
  18123. element.addEventListener('ended', function () {
  18124. if (!element.loop) {
  18125. element.paused = true;
  18126. }
  18127. });
  18128. },
  18129. play: function (offset, loop) {
  18130. if (!this._element) return;
  18131. this._element.loop = loop;
  18132. this._element.play();
  18133. if (this._AUDIO_TYPE === 'AUDIO' && this._element.paused) {
  18134. this.stop();
  18135. cc.Audio.touchPlayList.push({ loop: loop, offset: offset, audio: this._element });
  18136. }
  18137. if (cc.Audio.bindTouch === false) {
  18138. cc.Audio.bindTouch = true;
  18139. cc.game.canvas.addEventListener('touchstart', cc.Audio.touchStart);
  18140. }
  18141. },
  18142. getPlaying: function () {
  18143. if (!this._element) return true;
  18144. return !this._element.paused;
  18145. },
  18146. stop: function () {
  18147. if (!this._element) return;
  18148. this._element.pause();
  18149. try{
  18150. this._element.currentTime = 0;
  18151. } catch (err) {}
  18152. },
  18153. pause: function () {
  18154. if (!this._element) return;
  18155. this._element.pause();
  18156. },
  18157. resume: function () {
  18158. if (!this._element) return;
  18159. this._element.play();
  18160. },
  18161. setVolume: function (volume) {
  18162. if (!this._element) return;
  18163. this._element.volume = volume;
  18164. },
  18165. getVolume: function () {
  18166. if (!this._element) return;
  18167. return this._element.volume;
  18168. },
  18169. cloneNode: function () {
  18170. var audio = new cc.Audio(this.src);
  18171. if (this._AUDIO_TYPE === "AUDIO") {
  18172. var elem = document.createElement("audio");
  18173. var sources = elem.getElementsByTagName('source');
  18174. for (var i=0; i<sources.length; i++) {
  18175. elem.appendChild(sources[i]);
  18176. }
  18177. elem.src = this.src;
  18178. audio.setElement(elem);
  18179. } else {
  18180. audio.setBuffer(this._element.buffer);
  18181. }
  18182. return audio;
  18183. }
  18184. });
  18185. cc.Audio.touchPlayList = [
  18186. ];
  18187. cc.Audio.bindTouch = false;
  18188. cc.Audio.touchStart = function () {
  18189. var list = cc.Audio.touchPlayList;
  18190. var item = null;
  18191. while (item = list.pop()) {
  18192. item.audio.loop = !!item.loop;
  18193. item.audio.play(item.offset);
  18194. }
  18195. };
  18196. cc.Audio.WebAudio = function (buffer) {
  18197. this.buffer = buffer;
  18198. this.context = cc.Audio._context;
  18199. var volume = this.context['createGain']();
  18200. volume['gain'].value = 1;
  18201. volume['connect'](this.context['destination']);
  18202. this._volume = volume;
  18203. this._loop = false;
  18204. this._startTime = -1;
  18205. this._currentSource = null;
  18206. this.playedLength = 0;
  18207. this._currextTimer = null;
  18208. };
  18209. cc.Audio.WebAudio.prototype = {
  18210. constructor: cc.Audio.WebAudio,
  18211. get paused () {
  18212. if (this._currentSource && this._currentSource.loop)
  18213. return false;
  18214. if (this._startTime === -1)
  18215. return true;
  18216. return this.context.currentTime - this._startTime > this.buffer.duration;
  18217. },
  18218. set paused (bool) {},
  18219. get loop () { return this._loop; },
  18220. set loop (bool) { return this._loop = bool; },
  18221. get volume () { return this._volume['gain'].value; },
  18222. set volume (num) { return this._volume['gain'].value = num; },
  18223. get currentTime () { return this.playedLength; },
  18224. set currentTime (num) { return this.playedLength = num; },
  18225. play: function (offset) {
  18226. if (this._currentSource && !this.paused) {
  18227. this._currentSource.stop(0);
  18228. this.playedLength = 0;
  18229. }
  18230. var audio = this.context["createBufferSource"]();
  18231. audio.buffer = this.buffer;
  18232. audio["connect"](this._volume);
  18233. audio.loop = this._loop;
  18234. this._startTime = this.context.currentTime;
  18235. offset = offset || this.playedLength;
  18236. var duration = this.buffer.duration;
  18237. if (!this._loop) {
  18238. if (audio.start)
  18239. audio.start(0, offset, duration - offset);
  18240. else if (audio["notoGrainOn"])
  18241. audio["noteGrainOn"](0, offset, duration - offset);
  18242. else
  18243. audio["noteOn"](0, offset, duration - offset);
  18244. } else {
  18245. if (audio.start)
  18246. audio.start(0);
  18247. else if (audio["notoGrainOn"])
  18248. audio["noteGrainOn"](0);
  18249. else
  18250. audio["noteOn"](0);
  18251. }
  18252. this._currentSource = audio;
  18253. if (this.context.currentTime === 0) {
  18254. var self = this;
  18255. clearTimeout(this._currextTimer);
  18256. this._currextTimer = setTimeout(function () {
  18257. if (self.context.currentTime === 0) {
  18258. cc.Audio.touchPlayList.push({
  18259. offset: offset,
  18260. audio: self
  18261. });
  18262. }
  18263. }, 10);
  18264. }
  18265. },
  18266. pause: function () {
  18267. this.playedLength = this.context.currentTime - this._startTime;
  18268. this.playedLength %= this.buffer.duration;
  18269. var audio = this._currentSource;
  18270. this._currentSource = null;
  18271. this._startTime = -1;
  18272. if (audio)
  18273. audio.stop(0);
  18274. }
  18275. };
  18276. (function(polyfill){
  18277. var SWA = polyfill.WEB_AUDIO, SWB = polyfill.ONLY_ONE;
  18278. var support = [];
  18279. (function(){
  18280. var audio = document.createElement("audio");
  18281. if(audio.canPlayType) {
  18282. var ogg = audio.canPlayType('audio/ogg; codecs="vorbis"');
  18283. if (ogg && ogg !== "") support.push(".ogg");
  18284. var mp3 = audio.canPlayType("audio/mpeg");
  18285. if (mp3 && mp3 !== "") support.push(".mp3");
  18286. var wav = audio.canPlayType('audio/wav; codecs="1"');
  18287. if (wav && wav !== "") support.push(".wav");
  18288. var mp4 = audio.canPlayType("audio/mp4");
  18289. if (mp4 && mp4 !== "") support.push(".mp4");
  18290. var m4a = audio.canPlayType("audio/x-m4a");
  18291. if (m4a && m4a !== "") support.push(".m4a");
  18292. }
  18293. })();
  18294. try{
  18295. if(SWA){
  18296. var context = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)();
  18297. cc.Audio._context = context;
  18298. if(polyfill.DELAY_CREATE_CTX)
  18299. setTimeout(function(){
  18300. context = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)();
  18301. cc.Audio._context = context;
  18302. }, 0);
  18303. }
  18304. }catch(error){
  18305. SWA = false;
  18306. cc.log("browser don't support web audio");
  18307. }
  18308. var loader = {
  18309. cache: {},
  18310. useWebAudio: false,
  18311. loadBuffer: function (url, cb) {
  18312. if (!SWA) return;
  18313. var request = new XMLHttpRequest();
  18314. request.open("GET", url, true);
  18315. request.responseType = "arraybuffer";
  18316. request.onload = function () {
  18317. context["decodeAudioData"](request.response, function(buffer){
  18318. cb(null, buffer);
  18319. }, function(){
  18320. cb('decode error - ' + url);
  18321. });
  18322. };
  18323. request.onerror = function(){
  18324. cb('request error - ' + url);
  18325. };
  18326. request.send();
  18327. },
  18328. load: function(realUrl, url, res, cb){
  18329. if(support.length === 0)
  18330. return cb("can not support audio!");
  18331. var audio = cc.loader.getRes(url);
  18332. if (audio)
  18333. return cb(null, audio);
  18334. var i;
  18335. if(cc.loader.audioPath)
  18336. realUrl = cc.path.join(cc.loader.audioPath, realUrl);
  18337. var extname = cc.path.extname(realUrl);
  18338. var typeList = [extname];
  18339. for(i=0; i<support.length; i++){
  18340. if(extname !== support[i]){
  18341. typeList.push(support[i]);
  18342. }
  18343. }
  18344. audio = new cc.Audio(realUrl);
  18345. cc.loader.cache[url] = audio;
  18346. this.loadAudioFromExtList(realUrl, typeList, audio, cb);
  18347. return audio;
  18348. },
  18349. loadAudioFromExtList: function(realUrl, typeList, audio, cb){
  18350. if(typeList.length === 0){
  18351. var ERRSTR = "can not found the resource of audio! Last match url is : ";
  18352. ERRSTR += realUrl.replace(/\.(.*)?$/, "(");
  18353. support.forEach(function(ext){
  18354. ERRSTR += ext + "|";
  18355. });
  18356. ERRSTR = ERRSTR.replace(/\|$/, ")");
  18357. return cb({status:520, errorMessage:ERRSTR}, null);
  18358. }
  18359. if (SWA && this.useWebAudio) {
  18360. this.loadBuffer(realUrl, function (error, buffer) {
  18361. if (error)
  18362. cc.log(error);
  18363. if (buffer)
  18364. audio.setBuffer(buffer);
  18365. cb(null, audio);
  18366. });
  18367. return;
  18368. }
  18369. var num = polyfill.ONE_SOURCE ? 1 : typeList.length;
  18370. var dom = document.createElement('audio');
  18371. for (var i=0; i<num; i++) {
  18372. var source = document.createElement('source');
  18373. source.src = cc.path.changeExtname(realUrl, typeList[i]);
  18374. dom.appendChild(source);
  18375. }
  18376. audio.setElement(dom);
  18377. var timer = setTimeout(function(){
  18378. if (dom.readyState === 0) {
  18379. failure();
  18380. } else {
  18381. success();
  18382. }
  18383. }, 8000);
  18384. var success = function () {
  18385. dom.removeEventListener("canplaythrough", success, false);
  18386. dom.removeEventListener("error", failure, false);
  18387. dom.removeEventListener("emptied", success, false);
  18388. if (polyfill.USE_LOADER_EVENT)
  18389. dom.removeEventListener(polyfill.USE_LOADER_EVENT, success, false);
  18390. clearTimeout(timer);
  18391. cb(null, audio);
  18392. };
  18393. var failure = function () {
  18394. cc.log('load audio failure - ' + realUrl);
  18395. success();
  18396. };
  18397. dom.addEventListener("canplaythrough", success, false);
  18398. dom.addEventListener("error", failure, false);
  18399. if(polyfill.USE_LOADER_EVENT)
  18400. dom.addEventListener(polyfill.USE_LOADER_EVENT, success, false);
  18401. }
  18402. };
  18403. cc.loader.register(["mp3", "ogg", "wav", "mp4", "m4a"], loader);
  18404. cc.audioEngine = {
  18405. _currMusic: null,
  18406. _musicVolume: 1,
  18407. features: polyfill,
  18408. willPlayMusic: function(){return false;},
  18409. playMusic: function(url, loop){
  18410. var bgMusic = this._currMusic;
  18411. if (bgMusic && bgMusic.getPlaying()) {
  18412. bgMusic.stop();
  18413. }
  18414. var audio = cc.loader.getRes(url);
  18415. if (!audio) {
  18416. cc.loader.load(url);
  18417. audio = cc.loader.getRes(url);
  18418. }
  18419. audio.setVolume(this._musicVolume);
  18420. audio.play(0, loop || false);
  18421. this._currMusic = audio;
  18422. },
  18423. stopMusic: function(releaseData){
  18424. var audio = this._currMusic;
  18425. if (audio) {
  18426. audio.stop();
  18427. this._currMusic = null;
  18428. if (releaseData)
  18429. cc.loader.release(audio.src);
  18430. }
  18431. },
  18432. pauseMusic: function(){
  18433. var audio = this._currMusic;
  18434. if (audio)
  18435. audio.pause();
  18436. },
  18437. resumeMusic: function(){
  18438. var audio = this._currMusic;
  18439. if (audio)
  18440. audio.resume();
  18441. },
  18442. rewindMusic: function(){
  18443. var audio = this._currMusic;
  18444. if (audio){
  18445. audio.stop();
  18446. audio.play();
  18447. }
  18448. },
  18449. getMusicVolume: function(){
  18450. return this._musicVolume;
  18451. },
  18452. setMusicVolume: function(volume){
  18453. volume = volume - 0;
  18454. if (isNaN(volume)) volume = 1;
  18455. if (volume > 1) volume = 1;
  18456. if (volume < 0) volume = 0;
  18457. this._musicVolume = volume;
  18458. var audio = this._currMusic;
  18459. if (audio) {
  18460. audio.setVolume(volume);
  18461. }
  18462. },
  18463. isMusicPlaying: function(){
  18464. var audio = this._currMusic;
  18465. if (audio) {
  18466. return audio.getPlaying();
  18467. } else {
  18468. return false;
  18469. }
  18470. },
  18471. _audioPool: {},
  18472. _maxAudioInstance: 10,
  18473. _effectVolume: 1,
  18474. playEffect: function(url, loop){
  18475. if (SWB && this._currMusic && this._currMusic.getPlaying()) {
  18476. cc.log('Browser is only allowed to play one audio');
  18477. return null;
  18478. }
  18479. var effectList = this._audioPool[url];
  18480. if (!effectList) {
  18481. effectList = this._audioPool[url] = [];
  18482. }
  18483. var i;
  18484. for (i = 0; i < effectList.length; i++) {
  18485. if (!effectList[i].getPlaying()) {
  18486. break;
  18487. }
  18488. }
  18489. if (!SWA && i > this._maxAudioInstance) {
  18490. var first = effectList.shift();
  18491. first.stop();
  18492. effectList.push(first);
  18493. i = effectList.length - 1;
  18494. }
  18495. var audio;
  18496. if (effectList[i]) {
  18497. audio = effectList[i];
  18498. audio.setVolume(this._effectVolume);
  18499. audio.play(0, loop || false);
  18500. return audio;
  18501. }
  18502. audio = cc.loader.getRes(url);
  18503. if (audio && SWA && audio._AUDIO_TYPE === 'AUDIO') {
  18504. cc.loader.release(url);
  18505. audio = null;
  18506. }
  18507. if (audio) {
  18508. if (SWA && audio._AUDIO_TYPE === 'AUDIO') {
  18509. loader.loadBuffer(url, function (error, buffer) {
  18510. audio.setBuffer(buffer);
  18511. audio.setVolume(cc.audioEngine._effectVolume);
  18512. if (!audio.getPlaying())
  18513. audio.play(0, loop || false);
  18514. });
  18515. } else {
  18516. audio = audio.cloneNode();
  18517. audio.setVolume(this._effectVolume);
  18518. audio.play(0, loop || false);
  18519. effectList.push(audio);
  18520. return audio;
  18521. }
  18522. }
  18523. loader.useWebAudio = true;
  18524. cc.loader.load(url, function (audio) {
  18525. audio = cc.loader.getRes(url);
  18526. audio = audio.cloneNode();
  18527. audio.setVolume(cc.audioEngine._effectVolume);
  18528. audio.play(0, loop || false);
  18529. effectList.push(audio);
  18530. });
  18531. loader.useWebAudio = false;
  18532. return audio;
  18533. },
  18534. setEffectsVolume: function(volume){
  18535. volume = volume - 0;
  18536. if(isNaN(volume)) volume = 1;
  18537. if(volume > 1) volume = 1;
  18538. if(volume < 0) volume = 0;
  18539. this._effectVolume = volume;
  18540. var audioPool = this._audioPool;
  18541. for(var p in audioPool){
  18542. var audioList = audioPool[p];
  18543. if(Array.isArray(audioList))
  18544. for(var i=0; i<audioList.length; i++){
  18545. audioList[i].setVolume(volume);
  18546. }
  18547. }
  18548. },
  18549. getEffectsVolume: function(){
  18550. return this._effectVolume;
  18551. },
  18552. pauseEffect: function(audio){
  18553. if(audio){
  18554. audio.pause();
  18555. }
  18556. },
  18557. pauseAllEffects: function(){
  18558. var ap = this._audioPool;
  18559. for(var p in ap){
  18560. var list = ap[p];
  18561. for(var i=0; i<ap[p].length; i++){
  18562. if(list[i].getPlaying()){
  18563. list[i].pause();
  18564. }
  18565. }
  18566. }
  18567. },
  18568. resumeEffect: function(audio){
  18569. if(audio)
  18570. audio.resume();
  18571. },
  18572. resumeAllEffects: function(){
  18573. var ap = this._audioPool;
  18574. for(var p in ap){
  18575. var list = ap[p];
  18576. for(var i=0; i<ap[p].length; i++){
  18577. list[i].resume();
  18578. }
  18579. }
  18580. },
  18581. stopEffect: function(audio){
  18582. if(audio) {
  18583. audio.stop();
  18584. }
  18585. },
  18586. stopAllEffects: function(){
  18587. var ap = this._audioPool;
  18588. for(var p in ap){
  18589. var list = ap[p];
  18590. for(var i=0; i<list.length; i++){
  18591. list[i].stop();
  18592. }
  18593. list.length = 0;
  18594. }
  18595. },
  18596. unloadEffect: function(url){
  18597. if(!url){
  18598. return;
  18599. }
  18600. cc.loader.release(url);
  18601. var pool = this._audioPool[url];
  18602. if(pool) pool.length = 0;
  18603. delete this._audioPool[url];
  18604. },
  18605. end: function(){
  18606. this.stopMusic();
  18607. this.stopAllEffects();
  18608. },
  18609. _pauseCache: [],
  18610. _pausePlaying: function(){
  18611. var bgMusic = this._currMusic;
  18612. if(bgMusic && bgMusic.getPlaying()){
  18613. bgMusic.pause();
  18614. this._pauseCache.push(bgMusic);
  18615. }
  18616. var ap = this._audioPool;
  18617. for(var p in ap){
  18618. var list = ap[p];
  18619. for(var i=0; i<ap[p].length; i++){
  18620. if(list[i].getPlaying()){
  18621. list[i].pause();
  18622. this._pauseCache.push(list[i]);
  18623. }
  18624. }
  18625. }
  18626. },
  18627. _resumePlaying: function(){
  18628. var list = this._pauseCache;
  18629. for(var i=0; i<list.length; i++){
  18630. list[i].resume();
  18631. }
  18632. list.length = 0;
  18633. }
  18634. };
  18635. })(window.__audioSupport);
  18636. cc._globalFontSize = cc.ITEM_SIZE;
  18637. cc._globalFontName = "Arial";
  18638. cc._globalFontNameRelease = false;
  18639. cc.MenuItem = cc.Node.extend({
  18640. _enabled: false,
  18641. _target: null,
  18642. _callback: null,
  18643. _isSelected: false,
  18644. _className: "MenuItem",
  18645. ctor: function (callback, target) {
  18646. var nodeP = cc.Node.prototype;
  18647. nodeP.ctor.call(this);
  18648. this._target = null;
  18649. this._callback = null;
  18650. this._isSelected = false;
  18651. this._enabled = false;
  18652. nodeP.setAnchorPoint.call(this, 0.5, 0.5);
  18653. this._target = target || null;
  18654. this._callback = callback || null;
  18655. if (this._callback) {
  18656. this._enabled = true;
  18657. }
  18658. },
  18659. isSelected: function () {
  18660. return this._isSelected;
  18661. },
  18662. setOpacityModifyRGB: function (value) {
  18663. },
  18664. isOpacityModifyRGB: function () {
  18665. return false;
  18666. },
  18667. setTarget: function (selector, rec) {
  18668. this._target = rec;
  18669. this._callback = selector;
  18670. },
  18671. isEnabled: function () {
  18672. return this._enabled;
  18673. },
  18674. setEnabled: function (enable) {
  18675. this._enabled = enable;
  18676. },
  18677. initWithCallback: function (callback, target) {
  18678. this.anchorX = 0.5;
  18679. this.anchorY = 0.5;
  18680. this._target = target;
  18681. this._callback = callback;
  18682. this._enabled = true;
  18683. this._isSelected = false;
  18684. return true;
  18685. },
  18686. rect: function () {
  18687. var locPosition = this._position, locContentSize = this._contentSize, locAnchorPoint = this._anchorPoint;
  18688. return cc.rect(locPosition.x - locContentSize.width * locAnchorPoint.x,
  18689. locPosition.y - locContentSize.height * locAnchorPoint.y,
  18690. locContentSize.width, locContentSize.height);
  18691. },
  18692. selected: function () {
  18693. this._isSelected = true;
  18694. },
  18695. unselected: function () {
  18696. this._isSelected = false;
  18697. },
  18698. setCallback: function (callback, target) {
  18699. this._target = target;
  18700. this._callback = callback;
  18701. },
  18702. activate: function () {
  18703. if (this._enabled) {
  18704. var locTarget = this._target, locCallback = this._callback;
  18705. if (!locCallback)
  18706. return;
  18707. if (locTarget && cc.isString(locCallback)) {
  18708. locTarget[locCallback](this);
  18709. } else if (locTarget && cc.isFunction(locCallback)) {
  18710. locCallback.call(locTarget, this);
  18711. } else
  18712. locCallback(this);
  18713. }
  18714. }
  18715. });
  18716. var _p = cc.MenuItem.prototype;
  18717. _p.enabled;
  18718. cc.defineGetterSetter(_p, "enabled", _p.isEnabled, _p.setEnabled);
  18719. cc.MenuItem.create = function (callback, target) {
  18720. return new cc.MenuItem(callback, target);
  18721. };
  18722. cc.MenuItemLabel = cc.MenuItem.extend({
  18723. _disabledColor: null,
  18724. _label: null,
  18725. _originalScale: 0,
  18726. _colorBackup: null,
  18727. ctor: function (label, selector, target) {
  18728. cc.MenuItem.prototype.ctor.call(this, selector, target);
  18729. this._disabledColor = null;
  18730. this._label = null;
  18731. this._colorBackup = null;
  18732. if (label) {
  18733. this._originalScale = 1.0;
  18734. this._colorBackup = cc.color.WHITE;
  18735. this._disabledColor = cc.color(126, 126, 126);
  18736. this.setLabel(label);
  18737. if (label.textureLoaded && !label.textureLoaded()) {
  18738. label.addEventListener("load", function (sender) {
  18739. this.width = sender.width;
  18740. this.height = sender.height;
  18741. if (this.parent instanceof cc.Menu) {
  18742. this.parent.updateAlign();
  18743. }
  18744. }, this);
  18745. }
  18746. this.setCascadeColorEnabled(true);
  18747. this.setCascadeOpacityEnabled(true);
  18748. }
  18749. },
  18750. getDisabledColor: function () {
  18751. return this._disabledColor;
  18752. },
  18753. setDisabledColor: function (color) {
  18754. this._disabledColor = color;
  18755. },
  18756. getLabel: function () {
  18757. return this._label;
  18758. },
  18759. setLabel: function (label) {
  18760. if (label) {
  18761. this.addChild(label);
  18762. label.anchorX = 0;
  18763. label.anchorY = 0;
  18764. this.width = label.width;
  18765. this.height = label.height;
  18766. label.setCascadeColorEnabled(true);
  18767. }
  18768. if (this._label) {
  18769. this.removeChild(this._label, true);
  18770. }
  18771. this._label = label;
  18772. },
  18773. setEnabled: function (enabled) {
  18774. if (this._enabled !== enabled) {
  18775. if (!enabled) {
  18776. this._colorBackup = this.color;
  18777. this.setColor(this._disabledColor);
  18778. } else {
  18779. this.setColor(this._colorBackup);
  18780. }
  18781. }
  18782. cc.MenuItem.prototype.setEnabled.call(this, enabled);
  18783. },
  18784. initWithLabel: function (label, selector, target) {
  18785. this.initWithCallback(selector, target);
  18786. this._originalScale = 1.0;
  18787. this._colorBackup = cc.color.WHITE;
  18788. this._disabledColor = cc.color(126, 126, 126);
  18789. this.setLabel(label);
  18790. this.setCascadeColorEnabled(true);
  18791. this.setCascadeOpacityEnabled(true);
  18792. return true;
  18793. },
  18794. setString: function (label) {
  18795. this._label.string = label;
  18796. this.width = this._label.width;
  18797. this.height = this._label.height;
  18798. },
  18799. getString: function () {
  18800. return this._label.string;
  18801. },
  18802. activate: function () {
  18803. if (this._enabled) {
  18804. this.stopAllActions();
  18805. this.scale = this._originalScale;
  18806. cc.MenuItem.prototype.activate.call(this);
  18807. }
  18808. },
  18809. selected: function () {
  18810. if (this._enabled) {
  18811. cc.MenuItem.prototype.selected.call(this);
  18812. var action = this.getActionByTag(cc.ZOOM_ACTION_TAG);
  18813. if (action)
  18814. this.stopAction(action);
  18815. else
  18816. this._originalScale = this.scale;
  18817. var zoomAction = cc.scaleTo(0.1, this._originalScale * 1.2);
  18818. zoomAction.setTag(cc.ZOOM_ACTION_TAG);
  18819. this.runAction(zoomAction);
  18820. }
  18821. },
  18822. unselected: function () {
  18823. if (this._enabled) {
  18824. cc.MenuItem.prototype.unselected.call(this);
  18825. this.stopActionByTag(cc.ZOOM_ACTION_TAG);
  18826. var zoomAction = cc.scaleTo(0.1, this._originalScale);
  18827. zoomAction.setTag(cc.ZOOM_ACTION_TAG);
  18828. this.runAction(zoomAction);
  18829. }
  18830. }
  18831. });
  18832. var _p = cc.MenuItemLabel.prototype;
  18833. _p.string;
  18834. cc.defineGetterSetter(_p, "string", _p.getString, _p.setString);
  18835. _p.disabledColor;
  18836. cc.defineGetterSetter(_p, "disabledColor", _p.getDisabledColor, _p.setDisabledColor);
  18837. _p.label;
  18838. cc.defineGetterSetter(_p, "label", _p.getLabel, _p.setLabel);
  18839. cc.MenuItemLabel.create = function (label, selector, target) {
  18840. return new cc.MenuItemLabel(label, selector, target);
  18841. };
  18842. cc.MenuItemAtlasFont = cc.MenuItemLabel.extend({
  18843. ctor: function (value, charMapFile, itemWidth, itemHeight, startCharMap, callback, target) {
  18844. var label;
  18845. if (value && value.length > 0) {
  18846. label = new cc.LabelAtlas(value, charMapFile, itemWidth, itemHeight, startCharMap);
  18847. }
  18848. cc.MenuItemLabel.prototype.ctor.call(this, label, callback, target);
  18849. },
  18850. initWithString: function (value, charMapFile, itemWidth, itemHeight, startCharMap, callback, target) {
  18851. if (!value || value.length === 0)
  18852. throw new Error("cc.MenuItemAtlasFont.initWithString(): value should be non-null and its length should be greater than 0");
  18853. var label = new cc.LabelAtlas();
  18854. label.initWithString(value, charMapFile, itemWidth, itemHeight, startCharMap);
  18855. if (this.initWithLabel(label, callback, target)) {
  18856. }
  18857. return true;
  18858. }
  18859. });
  18860. cc.MenuItemAtlasFont.create = function (value, charMapFile, itemWidth, itemHeight, startCharMap, callback, target) {
  18861. return new cc.MenuItemAtlasFont(value, charMapFile, itemWidth, itemHeight, startCharMap, callback, target);
  18862. };
  18863. cc.MenuItemFont = cc.MenuItemLabel.extend({
  18864. _fontSize: null,
  18865. _fontName: null,
  18866. ctor: function (value, callback, target) {
  18867. var label;
  18868. if (value && value.length > 0) {
  18869. this._fontName = cc._globalFontName;
  18870. this._fontSize = cc._globalFontSize;
  18871. label = new cc.LabelTTF(value, this._fontName, this._fontSize);
  18872. }
  18873. else {
  18874. this._fontSize = 0;
  18875. this._fontName = "";
  18876. }
  18877. cc.MenuItemLabel.prototype.ctor.call(this, label, callback, target);
  18878. },
  18879. initWithString: function (value, callback, target) {
  18880. if (!value || value.length === 0)
  18881. throw new Error("Value should be non-null and its length should be greater than 0");
  18882. this._fontName = cc._globalFontName;
  18883. this._fontSize = cc._globalFontSize;
  18884. var label = new cc.LabelTTF(value, this._fontName, this._fontSize);
  18885. if (this.initWithLabel(label, callback, target)) {
  18886. }
  18887. return true;
  18888. },
  18889. setFontSize: function (s) {
  18890. this._fontSize = s;
  18891. this._recreateLabel();
  18892. },
  18893. getFontSize: function () {
  18894. return this._fontSize;
  18895. },
  18896. setFontName: function (name) {
  18897. this._fontName = name;
  18898. this._recreateLabel();
  18899. },
  18900. getFontName: function () {
  18901. return this._fontName;
  18902. },
  18903. _recreateLabel: function () {
  18904. var label = new cc.LabelTTF(this._label.string, this._fontName, this._fontSize);
  18905. this.setLabel(label);
  18906. }
  18907. });
  18908. cc.MenuItemFont.setFontSize = function (fontSize) {
  18909. cc._globalFontSize = fontSize;
  18910. };
  18911. cc.MenuItemFont.fontSize = function () {
  18912. return cc._globalFontSize;
  18913. };
  18914. cc.MenuItemFont.setFontName = function (name) {
  18915. if (cc._globalFontNameRelease) {
  18916. cc._globalFontName = '';
  18917. }
  18918. cc._globalFontName = name;
  18919. cc._globalFontNameRelease = true;
  18920. };
  18921. var _p = cc.MenuItemFont.prototype;
  18922. _p.fontSize;
  18923. cc.defineGetterSetter(_p, "fontSize", _p.getFontSize, _p.setFontSize);
  18924. _p.fontName;
  18925. cc.defineGetterSetter(_p, "fontName", _p.getFontName, _p.setFontName);
  18926. cc.MenuItemFont.fontName = function () {
  18927. return cc._globalFontName;
  18928. };
  18929. cc.MenuItemFont.create = function (value, callback, target) {
  18930. return new cc.MenuItemFont(value, callback, target);
  18931. };
  18932. cc.MenuItemSprite = cc.MenuItem.extend({
  18933. _normalImage: null,
  18934. _selectedImage: null,
  18935. _disabledImage: null,
  18936. ctor: function (normalSprite, selectedSprite, three, four, five) {
  18937. cc.MenuItem.prototype.ctor.call(this);
  18938. this._normalImage = null;
  18939. this._selectedImage = null;
  18940. this._disabledImage = null;
  18941. this._loader = new cc.Sprite.LoadManager();
  18942. if (normalSprite !== undefined) {
  18943. selectedSprite = selectedSprite || null;
  18944. var disabledImage, target, callback;
  18945. if (five !== undefined) {
  18946. disabledImage = three;
  18947. callback = four;
  18948. target = five;
  18949. } else if (four !== undefined && cc.isFunction(four)) {
  18950. disabledImage = three;
  18951. callback = four;
  18952. } else if (four !== undefined && cc.isFunction(three)) {
  18953. target = four;
  18954. callback = three;
  18955. disabledImage = null;
  18956. } else if (three === undefined) {
  18957. disabledImage = null;
  18958. }
  18959. this._loader.clear();
  18960. if (normalSprite.textureLoaded && !normalSprite.textureLoaded()) {
  18961. this._loader.once(normalSprite, function () {
  18962. this.initWithNormalSprite(normalSprite, selectedSprite, disabledImage, callback, target);
  18963. }, this);
  18964. return false;
  18965. }
  18966. this.initWithNormalSprite(normalSprite, selectedSprite, disabledImage, callback, target);
  18967. return true;
  18968. }
  18969. },
  18970. getNormalImage: function () {
  18971. return this._normalImage;
  18972. },
  18973. setNormalImage: function (normalImage) {
  18974. if (this._normalImage === normalImage) {
  18975. return;
  18976. }
  18977. if (normalImage) {
  18978. this.addChild(normalImage, 0, cc.NORMAL_TAG);
  18979. normalImage.anchorX = 0;
  18980. normalImage.anchorY = 0;
  18981. }
  18982. if (this._normalImage) {
  18983. this.removeChild(this._normalImage, true);
  18984. }
  18985. this._normalImage = normalImage;
  18986. if(!this._normalImage)
  18987. return;
  18988. this.width = this._normalImage.width;
  18989. this.height = this._normalImage.height;
  18990. this._updateImagesVisibility();
  18991. if (normalImage.textureLoaded && !normalImage.textureLoaded()) {
  18992. normalImage.addEventListener("load", function (sender) {
  18993. this.width = sender.width;
  18994. this.height = sender.height;
  18995. if (this.parent instanceof cc.Menu) {
  18996. this.parent.updateAlign();
  18997. }
  18998. }, this);
  18999. }
  19000. },
  19001. getSelectedImage: function () {
  19002. return this._selectedImage;
  19003. },
  19004. setSelectedImage: function (selectedImage) {
  19005. if (this._selectedImage === selectedImage)
  19006. return;
  19007. if (selectedImage) {
  19008. this.addChild(selectedImage, 0, cc.SELECTED_TAG);
  19009. selectedImage.anchorX = 0;
  19010. selectedImage.anchorY = 0;
  19011. }
  19012. if (this._selectedImage) {
  19013. this.removeChild(this._selectedImage, true);
  19014. }
  19015. this._selectedImage = selectedImage;
  19016. this._updateImagesVisibility();
  19017. },
  19018. getDisabledImage: function () {
  19019. return this._disabledImage;
  19020. },
  19021. setDisabledImage: function (disabledImage) {
  19022. if (this._disabledImage === disabledImage)
  19023. return;
  19024. if (disabledImage) {
  19025. this.addChild(disabledImage, 0, cc.DISABLE_TAG);
  19026. disabledImage.anchorX = 0;
  19027. disabledImage.anchorY = 0;
  19028. }
  19029. if (this._disabledImage)
  19030. this.removeChild(this._disabledImage, true);
  19031. this._disabledImage = disabledImage;
  19032. this._updateImagesVisibility();
  19033. },
  19034. initWithNormalSprite: function (normalSprite, selectedSprite, disabledSprite, callback, target) {
  19035. this._loader.clear();
  19036. if (normalSprite.textureLoaded && !normalSprite.textureLoaded()) {
  19037. this._loader.once(normalSprite, function () {
  19038. this.initWithNormalSprite(normalSprite, selectedSprite, disabledSprite, callback, target);
  19039. }, this);
  19040. return false;
  19041. }
  19042. this.initWithCallback(callback, target);
  19043. this.setNormalImage(normalSprite);
  19044. this.setSelectedImage(selectedSprite);
  19045. this.setDisabledImage(disabledSprite);
  19046. var locNormalImage = this._normalImage;
  19047. if (locNormalImage) {
  19048. this.width = locNormalImage.width;
  19049. this.height = locNormalImage.height;
  19050. }
  19051. this.setCascadeColorEnabled(true);
  19052. this.setCascadeOpacityEnabled(true);
  19053. return true;
  19054. },
  19055. selected: function () {
  19056. cc.MenuItem.prototype.selected.call(this);
  19057. if (this._normalImage) {
  19058. if (this._disabledImage)
  19059. this._disabledImage.visible = false;
  19060. if (this._selectedImage) {
  19061. this._normalImage.visible = false;
  19062. this._selectedImage.visible = true;
  19063. } else
  19064. this._normalImage.visible = true;
  19065. }
  19066. },
  19067. unselected: function () {
  19068. cc.MenuItem.prototype.unselected.call(this);
  19069. if (this._normalImage) {
  19070. this._normalImage.visible = true;
  19071. if (this._selectedImage)
  19072. this._selectedImage.visible = false;
  19073. if (this._disabledImage)
  19074. this._disabledImage.visible = false;
  19075. }
  19076. },
  19077. setEnabled: function (bEnabled) {
  19078. if (this._enabled !== bEnabled) {
  19079. cc.MenuItem.prototype.setEnabled.call(this, bEnabled);
  19080. this._updateImagesVisibility();
  19081. }
  19082. },
  19083. _updateImagesVisibility: function () {
  19084. var locNormalImage = this._normalImage, locSelImage = this._selectedImage, locDisImage = this._disabledImage;
  19085. if (this._enabled) {
  19086. if (locNormalImage)
  19087. locNormalImage.visible = true;
  19088. if (locSelImage)
  19089. locSelImage.visible = false;
  19090. if (locDisImage)
  19091. locDisImage.visible = false;
  19092. } else {
  19093. if (locDisImage) {
  19094. if (locNormalImage)
  19095. locNormalImage.visible = false;
  19096. if (locSelImage)
  19097. locSelImage.visible = false;
  19098. if (locDisImage)
  19099. locDisImage.visible = true;
  19100. } else {
  19101. if (locNormalImage)
  19102. locNormalImage.visible = true;
  19103. if (locSelImage)
  19104. locSelImage.visible = false;
  19105. }
  19106. }
  19107. }
  19108. });
  19109. var _p = cc.MenuItemSprite.prototype;
  19110. _p.normalImage;
  19111. cc.defineGetterSetter(_p, "normalImage", _p.getNormalImage, _p.setNormalImage);
  19112. _p.selectedImage;
  19113. cc.defineGetterSetter(_p, "selectedImage", _p.getSelectedImage, _p.setSelectedImage);
  19114. _p.disabledImage;
  19115. cc.defineGetterSetter(_p, "disabledImage", _p.getDisabledImage, _p.setDisabledImage);
  19116. cc.MenuItemSprite.create = function (normalSprite, selectedSprite, three, four, five) {
  19117. return new cc.MenuItemSprite(normalSprite, selectedSprite, three, four, five || undefined);
  19118. };
  19119. cc.MenuItemImage = cc.MenuItemSprite.extend({
  19120. ctor: function (normalImage, selectedImage, three, four, five) {
  19121. var normalSprite = null,
  19122. selectedSprite = null,
  19123. disabledSprite = null,
  19124. callback = null,
  19125. target = null;
  19126. if (normalImage === undefined || normalImage === null) {
  19127. cc.MenuItemSprite.prototype.ctor.call(this);
  19128. }
  19129. else {
  19130. normalSprite = new cc.Sprite(normalImage);
  19131. selectedImage &&
  19132. (selectedSprite = new cc.Sprite(selectedImage));
  19133. if (four === undefined) {
  19134. callback = three;
  19135. }
  19136. else if (five === undefined) {
  19137. callback = three;
  19138. target = four;
  19139. }
  19140. else if (five) {
  19141. disabledSprite = new cc.Sprite(three);
  19142. callback = four;
  19143. target = five;
  19144. }
  19145. cc.MenuItemSprite.prototype.ctor.call(this, normalSprite, selectedSprite, disabledSprite, callback, target);
  19146. }
  19147. },
  19148. setNormalSpriteFrame: function (frame) {
  19149. this.setNormalImage(new cc.Sprite(frame));
  19150. },
  19151. setSelectedSpriteFrame: function (frame) {
  19152. this.setSelectedImage(new cc.Sprite(frame));
  19153. },
  19154. setDisabledSpriteFrame: function (frame) {
  19155. this.setDisabledImage(new cc.Sprite(frame));
  19156. },
  19157. initWithNormalImage: function (normalImage, selectedImage, disabledImage, callback, target) {
  19158. var normalSprite = null;
  19159. var selectedSprite = null;
  19160. var disabledSprite = null;
  19161. if (normalImage) {
  19162. normalSprite = new cc.Sprite(normalImage);
  19163. }
  19164. if (selectedImage) {
  19165. selectedSprite = new cc.Sprite(selectedImage);
  19166. }
  19167. if (disabledImage) {
  19168. disabledSprite = new cc.Sprite(disabledImage);
  19169. }
  19170. return this.initWithNormalSprite(normalSprite, selectedSprite, disabledSprite, callback, target);
  19171. }
  19172. });
  19173. cc.MenuItemImage.create = function (normalImage, selectedImage, three, four, five) {
  19174. return new cc.MenuItemImage(normalImage, selectedImage, three, four, five);
  19175. };
  19176. cc.MenuItemToggle = cc.MenuItem.extend({
  19177. subItems: null,
  19178. _selectedIndex: 0,
  19179. _opacity: null,
  19180. _color: null,
  19181. ctor: function () {
  19182. cc.MenuItem.prototype.ctor.call(this);
  19183. this._selectedIndex = 0;
  19184. this.subItems = [];
  19185. this._opacity = 0;
  19186. this._color = cc.color.WHITE;
  19187. if(arguments.length > 0)
  19188. this.initWithItems(Array.prototype.slice.apply(arguments));
  19189. },
  19190. getOpacity: function () {
  19191. return this._opacity;
  19192. },
  19193. setOpacity: function (opacity) {
  19194. this._opacity = opacity;
  19195. if (this.subItems && this.subItems.length > 0) {
  19196. for (var it = 0; it < this.subItems.length; it++) {
  19197. this.subItems[it].opacity = opacity;
  19198. }
  19199. }
  19200. this._color.a = opacity;
  19201. },
  19202. getColor: function () {
  19203. var locColor = this._color;
  19204. return cc.color(locColor.r, locColor.g, locColor.b, locColor.a);
  19205. },
  19206. setColor: function (color) {
  19207. var locColor = this._color;
  19208. locColor.r = color.r;
  19209. locColor.g = color.g;
  19210. locColor.b = color.b;
  19211. if (this.subItems && this.subItems.length > 0) {
  19212. for (var it = 0; it < this.subItems.length; it++) {
  19213. this.subItems[it].setColor(color);
  19214. }
  19215. }
  19216. if (color.a !== undefined && !color.a_undefined) {
  19217. this.setOpacity(color.a);
  19218. }
  19219. },
  19220. getSelectedIndex: function () {
  19221. return this._selectedIndex;
  19222. },
  19223. setSelectedIndex: function (SelectedIndex) {
  19224. if (SelectedIndex !== this._selectedIndex) {
  19225. this._selectedIndex = SelectedIndex;
  19226. var currItem = this.getChildByTag(cc.CURRENT_ITEM);
  19227. if (currItem)
  19228. currItem.removeFromParent(false);
  19229. var item = this.subItems[this._selectedIndex];
  19230. this.addChild(item, 0, cc.CURRENT_ITEM);
  19231. var w = item.width, h = item.height;
  19232. this.width = w;
  19233. this.height = h;
  19234. item.setPosition(w / 2, h / 2);
  19235. }
  19236. },
  19237. getSubItems: function () {
  19238. return this.subItems;
  19239. },
  19240. setSubItems: function (subItems) {
  19241. this.subItems = subItems;
  19242. },
  19243. initWithItems: function (args) {
  19244. var l = args.length;
  19245. if (cc.isFunction(args[args.length - 2])) {
  19246. this.initWithCallback(args[args.length - 2], args[args.length - 1]);
  19247. l = l - 2;
  19248. } else if (cc.isFunction(args[args.length - 1])) {
  19249. this.initWithCallback(args[args.length - 1], null);
  19250. l = l - 1;
  19251. } else {
  19252. this.initWithCallback(null, null);
  19253. }
  19254. var locSubItems = this.subItems;
  19255. locSubItems.length = 0;
  19256. for (var i = 0; i < l; i++) {
  19257. if (args[i])
  19258. locSubItems.push(args[i]);
  19259. }
  19260. this._selectedIndex = cc.UINT_MAX;
  19261. this.setSelectedIndex(0);
  19262. this.setCascadeColorEnabled(true);
  19263. this.setCascadeOpacityEnabled(true);
  19264. return true;
  19265. },
  19266. addSubItem: function (item) {
  19267. this.subItems.push(item);
  19268. },
  19269. activate: function () {
  19270. if (this._enabled) {
  19271. var newIndex = (this._selectedIndex + 1) % this.subItems.length;
  19272. this.setSelectedIndex(newIndex);
  19273. }
  19274. cc.MenuItem.prototype.activate.call(this);
  19275. },
  19276. selected: function () {
  19277. cc.MenuItem.prototype.selected.call(this);
  19278. this.subItems[this._selectedIndex].selected();
  19279. },
  19280. unselected: function () {
  19281. cc.MenuItem.prototype.unselected.call(this);
  19282. this.subItems[this._selectedIndex].unselected();
  19283. },
  19284. setEnabled: function (enabled) {
  19285. if (this._enabled !== enabled) {
  19286. cc.MenuItem.prototype.setEnabled.call(this, enabled);
  19287. var locItems = this.subItems;
  19288. if (locItems && locItems.length > 0) {
  19289. for (var it = 0; it < locItems.length; it++)
  19290. locItems[it].enabled = enabled;
  19291. }
  19292. }
  19293. },
  19294. selectedItem: function () {
  19295. return this.subItems[this._selectedIndex];
  19296. },
  19297. getSelectedItem: function() {
  19298. return this.subItems[this._selectedIndex];
  19299. },
  19300. onEnter: function () {
  19301. cc.Node.prototype.onEnter.call(this);
  19302. this.setSelectedIndex(this._selectedIndex);
  19303. }
  19304. });
  19305. var _p = cc.MenuItemToggle.prototype;
  19306. _p.selectedIndex;
  19307. cc.defineGetterSetter(_p, "selectedIndex", _p.getSelectedIndex, _p.setSelectedIndex);
  19308. cc.MenuItemToggle.create = function () {
  19309. if ((arguments.length > 0) && (arguments[arguments.length - 1] == null))
  19310. cc.log("parameters should not be ending with null in Javascript");
  19311. var ret = new cc.MenuItemToggle();
  19312. ret.initWithItems(Array.prototype.slice.apply(arguments));
  19313. return ret;
  19314. };
  19315. cc.MENU_STATE_WAITING = 0;
  19316. cc.MENU_STATE_TRACKING_TOUCH = 1;
  19317. cc.MENU_HANDLER_PRIORITY = -128;
  19318. cc.DEFAULT_PADDING = 5;
  19319. cc.Menu = cc.Layer.extend({
  19320. enabled: false,
  19321. _selectedItem: null,
  19322. _state: -1,
  19323. _touchListener: null,
  19324. _className: "Menu",
  19325. ctor: function (menuItems) {
  19326. cc.Layer.prototype.ctor.call(this);
  19327. this._color = cc.color.WHITE;
  19328. this.enabled = false;
  19329. this._opacity = 255;
  19330. this._selectedItem = null;
  19331. this._state = -1;
  19332. this._touchListener = cc.EventListener.create({
  19333. event: cc.EventListener.TOUCH_ONE_BY_ONE,
  19334. swallowTouches: true,
  19335. onTouchBegan: this._onTouchBegan,
  19336. onTouchMoved: this._onTouchMoved,
  19337. onTouchEnded: this._onTouchEnded,
  19338. onTouchCancelled: this._onTouchCancelled
  19339. });
  19340. if ((arguments.length > 0) && (arguments[arguments.length - 1] == null))
  19341. cc.log("parameters should not be ending with null in Javascript");
  19342. var argc = arguments.length, items;
  19343. if (argc === 0) {
  19344. items = [];
  19345. } else if (argc === 1) {
  19346. if (menuItems instanceof Array) {
  19347. items = menuItems;
  19348. }
  19349. else items = [menuItems];
  19350. }
  19351. else if (argc > 1) {
  19352. items = [];
  19353. for (var i = 0; i < argc; i++) {
  19354. if (arguments[i])
  19355. items.push(arguments[i]);
  19356. }
  19357. }
  19358. this.initWithArray(items);
  19359. },
  19360. onEnter: function () {
  19361. var locListener = this._touchListener;
  19362. if (!locListener._isRegistered())
  19363. cc.eventManager.addListener(locListener, this);
  19364. cc.Node.prototype.onEnter.call(this);
  19365. },
  19366. isEnabled: function () {
  19367. return this.enabled;
  19368. },
  19369. setEnabled: function (enabled) {
  19370. this.enabled = enabled;
  19371. },
  19372. initWithItems: function (args) {
  19373. var pArray = [];
  19374. if (args) {
  19375. for (var i = 0; i < args.length; i++) {
  19376. if (args[i])
  19377. pArray.push(args[i]);
  19378. }
  19379. }
  19380. return this.initWithArray(pArray);
  19381. },
  19382. initWithArray: function (arrayOfItems) {
  19383. if (cc.Layer.prototype.init.call(this)) {
  19384. this.enabled = true;
  19385. var winSize = cc.winSize;
  19386. this.setPosition(winSize.width / 2, winSize.height / 2);
  19387. this.setContentSize(winSize);
  19388. this.setAnchorPoint(0.5, 0.5);
  19389. this.ignoreAnchorPointForPosition(true);
  19390. if (arrayOfItems) {
  19391. for (var i = 0; i < arrayOfItems.length; i++)
  19392. this.addChild(arrayOfItems[i], i);
  19393. }
  19394. this._selectedItem = null;
  19395. this._state = cc.MENU_STATE_WAITING;
  19396. this.cascadeColor = true;
  19397. this.cascadeOpacity = true;
  19398. return true;
  19399. }
  19400. return false;
  19401. },
  19402. addChild: function (child, zOrder, tag) {
  19403. if (!(child instanceof cc.MenuItem))
  19404. throw new Error("cc.Menu.addChild() : Menu only supports MenuItem objects as children");
  19405. cc.Layer.prototype.addChild.call(this, child, zOrder, tag);
  19406. },
  19407. updateAlign: function () {
  19408. switch (this._align) {
  19409. case 'vertically':
  19410. this.alignItemsVertically();
  19411. break;
  19412. case 'horizontally':
  19413. this.alignItemsHorizontally();
  19414. break;
  19415. }
  19416. },
  19417. alignItemsVertically: function () {
  19418. this.alignItemsVerticallyWithPadding(cc.DEFAULT_PADDING);
  19419. },
  19420. alignItemsVerticallyWithPadding: function (padding) {
  19421. this._align = 'vertically';
  19422. var height = -padding, locChildren = this._children, len, i, locScaleY, locHeight, locChild;
  19423. if (locChildren && locChildren.length > 0) {
  19424. for (i = 0, len = locChildren.length; i < len; i++)
  19425. height += locChildren[i].height * locChildren[i].scaleY + padding;
  19426. var y = height / 2.0;
  19427. for (i = 0, len = locChildren.length; i < len; i++) {
  19428. locChild = locChildren[i];
  19429. locHeight = locChild.height;
  19430. locScaleY = locChild.scaleY;
  19431. locChild.setPosition(0, y - locHeight * locScaleY / 2);
  19432. y -= locHeight * locScaleY + padding;
  19433. }
  19434. }
  19435. },
  19436. alignItemsHorizontally: function () {
  19437. this.alignItemsHorizontallyWithPadding(cc.DEFAULT_PADDING);
  19438. },
  19439. alignItemsHorizontallyWithPadding: function (padding) {
  19440. this._align = 'horizontally';
  19441. var width = -padding, locChildren = this._children, i, len, locScaleX, locWidth, locChild;
  19442. if (locChildren && locChildren.length > 0) {
  19443. for (i = 0, len = locChildren.length; i < len; i++)
  19444. width += locChildren[i].width * locChildren[i].scaleX + padding;
  19445. var x = -width / 2.0;
  19446. for (i = 0, len = locChildren.length; i < len; i++) {
  19447. locChild = locChildren[i];
  19448. locScaleX = locChild.scaleX;
  19449. locWidth = locChildren[i].width;
  19450. locChild.setPosition(x + locWidth * locScaleX / 2, 0);
  19451. x += locWidth * locScaleX + padding;
  19452. }
  19453. }
  19454. },
  19455. alignItemsInColumns: function () {
  19456. if ((arguments.length > 0) && (arguments[arguments.length - 1] == null))
  19457. cc.log("parameters should not be ending with null in Javascript");
  19458. var rows = [];
  19459. for (var i = 0; i < arguments.length; i++) {
  19460. rows.push(arguments[i]);
  19461. }
  19462. var height = -5;
  19463. var row = 0;
  19464. var rowHeight = 0;
  19465. var columnsOccupied = 0;
  19466. var rowColumns, tmp, len;
  19467. var locChildren = this._children;
  19468. if (locChildren && locChildren.length > 0) {
  19469. for (i = 0, len = locChildren.length; i < len; i++) {
  19470. if (row >= rows.length)
  19471. continue;
  19472. rowColumns = rows[row];
  19473. if (!rowColumns)
  19474. continue;
  19475. tmp = locChildren[i].height;
  19476. rowHeight = ((rowHeight >= tmp || isNaN(tmp)) ? rowHeight : tmp);
  19477. ++columnsOccupied;
  19478. if (columnsOccupied >= rowColumns) {
  19479. height += rowHeight + 5;
  19480. columnsOccupied = 0;
  19481. rowHeight = 0;
  19482. ++row;
  19483. }
  19484. }
  19485. }
  19486. var winSize = cc.director.getWinSize();
  19487. row = 0;
  19488. rowHeight = 0;
  19489. rowColumns = 0;
  19490. var w = 0.0;
  19491. var x = 0.0;
  19492. var y = (height / 2);
  19493. if (locChildren && locChildren.length > 0) {
  19494. for (i = 0, len = locChildren.length; i < len; i++) {
  19495. var child = locChildren[i];
  19496. if (rowColumns === 0) {
  19497. rowColumns = rows[row];
  19498. w = winSize.width / (1 + rowColumns);
  19499. x = w;
  19500. }
  19501. tmp = child._getHeight();
  19502. rowHeight = ((rowHeight >= tmp || isNaN(tmp)) ? rowHeight : tmp);
  19503. child.setPosition(x - winSize.width / 2, y - tmp / 2);
  19504. x += w;
  19505. ++columnsOccupied;
  19506. if (columnsOccupied >= rowColumns) {
  19507. y -= rowHeight + 5;
  19508. columnsOccupied = 0;
  19509. rowColumns = 0;
  19510. rowHeight = 0;
  19511. ++row;
  19512. }
  19513. }
  19514. }
  19515. },
  19516. alignItemsInRows: function () {
  19517. if ((arguments.length > 0) && (arguments[arguments.length - 1] == null))
  19518. cc.log("parameters should not be ending with null in Javascript");
  19519. var columns = [], i;
  19520. for (i = 0; i < arguments.length; i++) {
  19521. columns.push(arguments[i]);
  19522. }
  19523. var columnWidths = [];
  19524. var columnHeights = [];
  19525. var width = -10;
  19526. var columnHeight = -5;
  19527. var column = 0;
  19528. var columnWidth = 0;
  19529. var rowsOccupied = 0;
  19530. var columnRows, child, len, tmp;
  19531. var locChildren = this._children;
  19532. if (locChildren && locChildren.length > 0) {
  19533. for (i = 0, len = locChildren.length; i < len; i++) {
  19534. child = locChildren[i];
  19535. if (column >= columns.length)
  19536. continue;
  19537. columnRows = columns[column];
  19538. if (!columnRows)
  19539. continue;
  19540. tmp = child.width;
  19541. columnWidth = ((columnWidth >= tmp || isNaN(tmp)) ? columnWidth : tmp);
  19542. columnHeight += (child.height + 5);
  19543. ++rowsOccupied;
  19544. if (rowsOccupied >= columnRows) {
  19545. columnWidths.push(columnWidth);
  19546. columnHeights.push(columnHeight);
  19547. width += columnWidth + 10;
  19548. rowsOccupied = 0;
  19549. columnWidth = 0;
  19550. columnHeight = -5;
  19551. ++column;
  19552. }
  19553. }
  19554. }
  19555. var winSize = cc.director.getWinSize();
  19556. column = 0;
  19557. columnWidth = 0;
  19558. columnRows = 0;
  19559. var x = -width / 2;
  19560. var y = 0.0;
  19561. if (locChildren && locChildren.length > 0) {
  19562. for (i = 0, len = locChildren.length; i < len; i++) {
  19563. child = locChildren[i];
  19564. if (columnRows === 0) {
  19565. columnRows = columns[column];
  19566. y = columnHeights[column];
  19567. }
  19568. tmp = child._getWidth();
  19569. columnWidth = ((columnWidth >= tmp || isNaN(tmp)) ? columnWidth : tmp);
  19570. child.setPosition(x + columnWidths[column] / 2, y - winSize.height / 2);
  19571. y -= child.height + 10;
  19572. ++rowsOccupied;
  19573. if (rowsOccupied >= columnRows) {
  19574. x += columnWidth + 5;
  19575. rowsOccupied = 0;
  19576. columnRows = 0;
  19577. columnWidth = 0;
  19578. ++column;
  19579. }
  19580. }
  19581. }
  19582. },
  19583. removeChild: function (child, cleanup) {
  19584. if (child == null)
  19585. return;
  19586. if (!(child instanceof cc.MenuItem)) {
  19587. cc.log("cc.Menu.removeChild():Menu only supports MenuItem objects as children");
  19588. return;
  19589. }
  19590. if (this._selectedItem === child)
  19591. this._selectedItem = null;
  19592. cc.Node.prototype.removeChild.call(this, child, cleanup);
  19593. },
  19594. _onTouchBegan: function (touch, event) {
  19595. var target = event.getCurrentTarget();
  19596. if (target._state !== cc.MENU_STATE_WAITING || !target._visible || !target.enabled)
  19597. return false;
  19598. for (var c = target.parent; c != null; c = c.parent) {
  19599. if (!c.isVisible())
  19600. return false;
  19601. }
  19602. target._selectedItem = target._itemForTouch(touch);
  19603. if (target._selectedItem) {
  19604. target._state = cc.MENU_STATE_TRACKING_TOUCH;
  19605. target._selectedItem.selected();
  19606. target._selectedItem.setNodeDirty();
  19607. return true;
  19608. }
  19609. return false;
  19610. },
  19611. _onTouchEnded: function (touch, event) {
  19612. var target = event.getCurrentTarget();
  19613. if (target._state !== cc.MENU_STATE_TRACKING_TOUCH) {
  19614. cc.log("cc.Menu.onTouchEnded(): invalid state");
  19615. return;
  19616. }
  19617. if (target._selectedItem) {
  19618. target._selectedItem.unselected();
  19619. target._selectedItem.setNodeDirty();
  19620. target._selectedItem.activate();
  19621. }
  19622. target._state = cc.MENU_STATE_WAITING;
  19623. },
  19624. _onTouchCancelled: function (touch, event) {
  19625. var target = event.getCurrentTarget();
  19626. if (target._state !== cc.MENU_STATE_TRACKING_TOUCH) {
  19627. cc.log("cc.Menu.onTouchCancelled(): invalid state");
  19628. return;
  19629. }
  19630. if (target._selectedItem) {
  19631. target._selectedItem.unselected();
  19632. target._selectedItem.setNodeDirty();
  19633. }
  19634. target._state = cc.MENU_STATE_WAITING;
  19635. },
  19636. _onTouchMoved: function (touch, event) {
  19637. var target = event.getCurrentTarget();
  19638. if (target._state !== cc.MENU_STATE_TRACKING_TOUCH) {
  19639. cc.log("cc.Menu.onTouchMoved(): invalid state");
  19640. return;
  19641. }
  19642. var currentItem = target._itemForTouch(touch);
  19643. if (currentItem !== target._selectedItem) {
  19644. if (target._selectedItem) {
  19645. target._selectedItem.unselected();
  19646. target._selectedItem.setNodeDirty();
  19647. }
  19648. target._selectedItem = currentItem;
  19649. if (target._selectedItem) {
  19650. target._selectedItem.selected();
  19651. target._selectedItem.setNodeDirty();
  19652. }
  19653. }
  19654. },
  19655. onExit: function () {
  19656. if (this._state === cc.MENU_STATE_TRACKING_TOUCH) {
  19657. if (this._selectedItem) {
  19658. this._selectedItem.unselected();
  19659. this._selectedItem = null;
  19660. }
  19661. this._state = cc.MENU_STATE_WAITING;
  19662. }
  19663. cc.Node.prototype.onExit.call(this);
  19664. },
  19665. setOpacityModifyRGB: function (value) {
  19666. },
  19667. isOpacityModifyRGB: function () {
  19668. return false;
  19669. },
  19670. _itemForTouch: function (touch) {
  19671. var touchLocation = touch.getLocation();
  19672. var itemChildren = this._children, locItemChild;
  19673. if (itemChildren && itemChildren.length > 0) {
  19674. for (var i = itemChildren.length - 1; i >= 0; i--) {
  19675. locItemChild = itemChildren[i];
  19676. if (locItemChild.isVisible() && locItemChild.isEnabled()) {
  19677. var local = locItemChild.convertToNodeSpace(touchLocation);
  19678. var r = locItemChild.rect();
  19679. r.x = 0;
  19680. r.y = 0;
  19681. if (cc.rectContainsPoint(r, local))
  19682. return locItemChild;
  19683. }
  19684. }
  19685. }
  19686. return null;
  19687. }
  19688. });
  19689. var _p = cc.Menu.prototype;
  19690. _p.enabled;
  19691. cc.Menu.create = function (menuItems) {
  19692. var argc = arguments.length;
  19693. if ((argc > 0) && (arguments[argc - 1] == null))
  19694. cc.log("parameters should not be ending with null in Javascript");
  19695. var ret;
  19696. if (argc === 0)
  19697. ret = new cc.Menu();
  19698. else if (argc === 1)
  19699. ret = new cc.Menu(menuItems);
  19700. else
  19701. ret = new cc.Menu(Array.prototype.slice.call(arguments, 0));
  19702. return ret;
  19703. };