123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711 |
- // Generated by Construct 2, the HTML5 game and app creator :: http://www.scirra.com
- var cr = {};
- cr.plugins_ = {};
- cr.behaviors = {};
- if (typeof Object.getPrototypeOf !== "function")
- {
- if (typeof "test".__proto__ === "object")
- {
- Object.getPrototypeOf = function(object) {
- return object.__proto__;
- };
- }
- else
- {
- Object.getPrototypeOf = function(object) {
- return object.constructor.prototype;
- };
- }
- }
- (function(){
- cr.logexport = function (msg)
- {
- if (window.console && window.console.log)
- window.console.log(msg);
- };
- cr.logerror = function (msg)
- {
- if (window.console && window.console.error)
- window.console.error(msg);
- };
- cr.seal = function(x)
- {
- return x;
- };
- cr.freeze = function(x)
- {
- return x;
- };
- cr.is_undefined = function (x)
- {
- return typeof x === "undefined";
- };
- cr.is_number = function (x)
- {
- return typeof x === "number";
- };
- cr.is_string = function (x)
- {
- return typeof x === "string";
- };
- cr.isPOT = function (x)
- {
- return x > 0 && ((x - 1) & x) === 0;
- };
- cr.nextHighestPowerOfTwo = function(x) {
- --x;
- for (var i = 1; i < 32; i <<= 1) {
- x = x | x >> i;
- }
- return x + 1;
- }
- cr.abs = function (x)
- {
- return (x < 0 ? -x : x);
- };
- cr.max = function (a, b)
- {
- return (a > b ? a : b);
- };
- cr.min = function (a, b)
- {
- return (a < b ? a : b);
- };
- cr.PI = Math.PI;
- cr.round = function (x)
- {
- return (x + 0.5) | 0;
- };
- cr.floor = function (x)
- {
- if (x >= 0)
- return x | 0;
- else
- return (x | 0) - 1; // correctly round down when negative
- };
- cr.ceil = function (x)
- {
- var f = x | 0;
- return (f === x ? f : f + 1);
- };
- function Vector2(x, y)
- {
- this.x = x;
- this.y = y;
- cr.seal(this);
- };
- Vector2.prototype.offset = function (px, py)
- {
- this.x += px;
- this.y += py;
- return this;
- };
- Vector2.prototype.mul = function (px, py)
- {
- this.x *= px;
- this.y *= py;
- return this;
- };
- cr.vector2 = Vector2;
- cr.segments_intersect = function(a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y)
- {
- var max_ax, min_ax, max_ay, min_ay, max_bx, min_bx, max_by, min_by;
- if (a1x < a2x)
- {
- min_ax = a1x;
- max_ax = a2x;
- }
- else
- {
- min_ax = a2x;
- max_ax = a1x;
- }
- if (b1x < b2x)
- {
- min_bx = b1x;
- max_bx = b2x;
- }
- else
- {
- min_bx = b2x;
- max_bx = b1x;
- }
- if (max_ax < min_bx || min_ax > max_bx)
- return false;
- if (a1y < a2y)
- {
- min_ay = a1y;
- max_ay = a2y;
- }
- else
- {
- min_ay = a2y;
- max_ay = a1y;
- }
- if (b1y < b2y)
- {
- min_by = b1y;
- max_by = b2y;
- }
- else
- {
- min_by = b2y;
- max_by = b1y;
- }
- if (max_ay < min_by || min_ay > max_by)
- return false;
- var dpx = b1x - a1x + b2x - a2x;
- var dpy = b1y - a1y + b2y - a2y;
- var qax = a2x - a1x;
- var qay = a2y - a1y;
- var qbx = b2x - b1x;
- var qby = b2y - b1y;
- var d = cr.abs(qay * qbx - qby * qax);
- var la = qbx * dpy - qby * dpx;
- if (cr.abs(la) > d)
- return false;
- var lb = qax * dpy - qay * dpx;
- return cr.abs(lb) <= d;
- };
- function Rect(left, top, right, bottom)
- {
- this.set(left, top, right, bottom);
- cr.seal(this);
- };
- Rect.prototype.set = function (left, top, right, bottom)
- {
- this.left = left;
- this.top = top;
- this.right = right;
- this.bottom = bottom;
- };
- Rect.prototype.copy = function (r)
- {
- this.left = r.left;
- this.top = r.top;
- this.right = r.right;
- this.bottom = r.bottom;
- };
- Rect.prototype.width = function ()
- {
- return this.right - this.left;
- };
- Rect.prototype.height = function ()
- {
- return this.bottom - this.top;
- };
- Rect.prototype.offset = function (px, py)
- {
- this.left += px;
- this.top += py;
- this.right += px;
- this.bottom += py;
- return this;
- };
- Rect.prototype.normalize = function ()
- {
- var temp = 0;
- if (this.left > this.right)
- {
- temp = this.left;
- this.left = this.right;
- this.right = temp;
- }
- if (this.top > this.bottom)
- {
- temp = this.top;
- this.top = this.bottom;
- this.bottom = temp;
- }
- };
- Rect.prototype.intersects_rect = function (rc)
- {
- return !(rc.right < this.left || rc.bottom < this.top || rc.left > this.right || rc.top > this.bottom);
- };
- Rect.prototype.intersects_rect_off = function (rc, ox, oy)
- {
- return !(rc.right + ox < this.left || rc.bottom + oy < this.top || rc.left + ox > this.right || rc.top + oy > this.bottom);
- };
- Rect.prototype.contains_pt = function (x, y)
- {
- return (x >= this.left && x <= this.right) && (y >= this.top && y <= this.bottom);
- };
- Rect.prototype.equals = function (r)
- {
- return this.left === r.left && this.top === r.top && this.right === r.right && this.bottom === r.bottom;
- };
- cr.rect = Rect;
- function Quad()
- {
- this.tlx = 0;
- this.tly = 0;
- this.trx = 0;
- this.try_ = 0; // is a keyword otherwise!
- this.brx = 0;
- this.bry = 0;
- this.blx = 0;
- this.bly = 0;
- cr.seal(this);
- };
- Quad.prototype.set_from_rect = function (rc)
- {
- this.tlx = rc.left;
- this.tly = rc.top;
- this.trx = rc.right;
- this.try_ = rc.top;
- this.brx = rc.right;
- this.bry = rc.bottom;
- this.blx = rc.left;
- this.bly = rc.bottom;
- };
- Quad.prototype.set_from_rotated_rect = function (rc, a)
- {
- if (a === 0)
- {
- this.set_from_rect(rc);
- }
- else
- {
- var sin_a = Math.sin(a);
- var cos_a = Math.cos(a);
- var left_sin_a = rc.left * sin_a;
- var top_sin_a = rc.top * sin_a;
- var right_sin_a = rc.right * sin_a;
- var bottom_sin_a = rc.bottom * sin_a;
- var left_cos_a = rc.left * cos_a;
- var top_cos_a = rc.top * cos_a;
- var right_cos_a = rc.right * cos_a;
- var bottom_cos_a = rc.bottom * cos_a;
- this.tlx = left_cos_a - top_sin_a;
- this.tly = top_cos_a + left_sin_a;
- this.trx = right_cos_a - top_sin_a;
- this.try_ = top_cos_a + right_sin_a;
- this.brx = right_cos_a - bottom_sin_a;
- this.bry = bottom_cos_a + right_sin_a;
- this.blx = left_cos_a - bottom_sin_a;
- this.bly = bottom_cos_a + left_sin_a;
- }
- };
- Quad.prototype.offset = function (px, py)
- {
- this.tlx += px;
- this.tly += py;
- this.trx += px;
- this.try_ += py;
- this.brx += px;
- this.bry += py;
- this.blx += px;
- this.bly += py;
- return this;
- };
- var minresult = 0;
- var maxresult = 0;
- function minmax4(a, b, c, d)
- {
- if (a < b)
- {
- if (c < d)
- {
- if (a < c)
- minresult = a;
- else
- minresult = c;
- if (b > d)
- maxresult = b;
- else
- maxresult = d;
- }
- else
- {
- if (a < d)
- minresult = a;
- else
- minresult = d;
- if (b > c)
- maxresult = b;
- else
- maxresult = c;
- }
- }
- else
- {
- if (c < d)
- {
- if (b < c)
- minresult = b;
- else
- minresult = c;
- if (a > d)
- maxresult = a;
- else
- maxresult = d;
- }
- else
- {
- if (b < d)
- minresult = b;
- else
- minresult = d;
- if (a > c)
- maxresult = a;
- else
- maxresult = c;
- }
- }
- };
- Quad.prototype.bounding_box = function (rc)
- {
- minmax4(this.tlx, this.trx, this.brx, this.blx);
- rc.left = minresult;
- rc.right = maxresult;
- minmax4(this.tly, this.try_, this.bry, this.bly);
- rc.top = minresult;
- rc.bottom = maxresult;
- };
- Quad.prototype.contains_pt = function (x, y)
- {
- var tlx = this.tlx;
- var tly = this.tly;
- var v0x = this.trx - tlx;
- var v0y = this.try_ - tly;
- var v1x = this.brx - tlx;
- var v1y = this.bry - tly;
- var v2x = x - tlx;
- var v2y = y - tly;
- var dot00 = v0x * v0x + v0y * v0y
- var dot01 = v0x * v1x + v0y * v1y
- var dot02 = v0x * v2x + v0y * v2y
- var dot11 = v1x * v1x + v1y * v1y
- var dot12 = v1x * v2x + v1y * v2y
- var invDenom = 1.0 / (dot00 * dot11 - dot01 * dot01);
- var u = (dot11 * dot02 - dot01 * dot12) * invDenom;
- var v = (dot00 * dot12 - dot01 * dot02) * invDenom;
- if ((u >= 0.0) && (v > 0.0) && (u + v < 1))
- return true;
- v0x = this.blx - tlx;
- v0y = this.bly - tly;
- var dot00 = v0x * v0x + v0y * v0y
- var dot01 = v0x * v1x + v0y * v1y
- var dot02 = v0x * v2x + v0y * v2y
- invDenom = 1.0 / (dot00 * dot11 - dot01 * dot01);
- u = (dot11 * dot02 - dot01 * dot12) * invDenom;
- v = (dot00 * dot12 - dot01 * dot02) * invDenom;
- return (u >= 0.0) && (v > 0.0) && (u + v < 1);
- };
- Quad.prototype.at = function (i, xory)
- {
- if (xory)
- {
- switch (i)
- {
- case 0: return this.tlx;
- case 1: return this.trx;
- case 2: return this.brx;
- case 3: return this.blx;
- case 4: return this.tlx;
- default: return this.tlx;
- }
- }
- else
- {
- switch (i)
- {
- case 0: return this.tly;
- case 1: return this.try_;
- case 2: return this.bry;
- case 3: return this.bly;
- case 4: return this.tly;
- default: return this.tly;
- }
- }
- };
- Quad.prototype.midX = function ()
- {
- return (this.tlx + this.trx + this.brx + this.blx) / 4;
- };
- Quad.prototype.midY = function ()
- {
- return (this.tly + this.try_ + this.bry + this.bly) / 4;
- };
- Quad.prototype.intersects_segment = function (x1, y1, x2, y2)
- {
- if (this.contains_pt(x1, y1) || this.contains_pt(x2, y2))
- return true;
- var a1x, a1y, a2x, a2y;
- var i;
- for (i = 0; i < 4; i++)
- {
- a1x = this.at(i, true);
- a1y = this.at(i, false);
- a2x = this.at(i + 1, true);
- a2y = this.at(i + 1, false);
- if (cr.segments_intersect(x1, y1, x2, y2, a1x, a1y, a2x, a2y))
- return true;
- }
- return false;
- };
- Quad.prototype.intersects_quad = function (rhs)
- {
- var midx = rhs.midX();
- var midy = rhs.midY();
- if (this.contains_pt(midx, midy))
- return true;
- midx = this.midX();
- midy = this.midY();
- if (rhs.contains_pt(midx, midy))
- return true;
- var a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y;
- var i, j;
- for (i = 0; i < 4; i++)
- {
- for (j = 0; j < 4; j++)
- {
- a1x = this.at(i, true);
- a1y = this.at(i, false);
- a2x = this.at(i + 1, true);
- a2y = this.at(i + 1, false);
- b1x = rhs.at(j, true);
- b1y = rhs.at(j, false);
- b2x = rhs.at(j + 1, true);
- b2y = rhs.at(j + 1, false);
- if (cr.segments_intersect(a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y))
- return true;
- }
- }
- return false;
- };
- cr.quad = Quad;
- cr.RGB = function (red, green, blue)
- {
- return Math.max(Math.min(red, 255), 0)
- | (Math.max(Math.min(green, 255), 0) << 8)
- | (Math.max(Math.min(blue, 255), 0) << 16);
- };
- cr.GetRValue = function (rgb)
- {
- return rgb & 0xFF;
- };
- cr.GetGValue = function (rgb)
- {
- return (rgb & 0xFF00) >> 8;
- };
- cr.GetBValue = function (rgb)
- {
- return (rgb & 0xFF0000) >> 16;
- };
- cr.shallowCopy = function (a, b, allowOverwrite)
- {
- var attr;
- for (attr in b)
- {
- if (b.hasOwnProperty(attr))
- {
- ;
- a[attr] = b[attr];
- }
- }
- return a;
- };
- cr.arrayRemove = function (arr, index)
- {
- var i, len;
- index = cr.floor(index);
- if (index < 0 || index >= arr.length)
- return; // index out of bounds
- for (i = index, len = arr.length - 1; i < len; i++)
- arr[i] = arr[i + 1];
- cr.truncateArray(arr, len);
- };
- cr.truncateArray = function (arr, index)
- {
- arr.length = index;
- };
- cr.clearArray = function (arr)
- {
- cr.truncateArray(arr, 0);
- };
- cr.shallowAssignArray = function (dest, src)
- {
- cr.clearArray(dest);
- var i, len;
- for (i = 0, len = src.length; i < len; ++i)
- dest[i] = src[i];
- };
- cr.appendArray = function (a, b)
- {
- a.push.apply(a, b);
- };
- cr.fastIndexOf = function (arr, item)
- {
- var i, len;
- for (i = 0, len = arr.length; i < len; ++i)
- {
- if (arr[i] === item)
- return i;
- }
- return -1;
- };
- cr.arrayFindRemove = function (arr, item)
- {
- var index = cr.fastIndexOf(arr, item);
- if (index !== -1)
- cr.arrayRemove(arr, index);
- };
- cr.clamp = function(x, a, b)
- {
- if (x < a)
- return a;
- else if (x > b)
- return b;
- else
- return x;
- };
- cr.to_radians = function(x)
- {
- return x / (180.0 / cr.PI);
- };
- cr.to_degrees = function(x)
- {
- return x * (180.0 / cr.PI);
- };
- cr.clamp_angle_degrees = function (a)
- {
- a %= 360; // now in (-360, 360) range
- if (a < 0)
- a += 360; // now in [0, 360) range
- return a;
- };
- cr.clamp_angle = function (a)
- {
- a %= 2 * cr.PI; // now in (-2pi, 2pi) range
- if (a < 0)
- a += 2 * cr.PI; // now in [0, 2pi) range
- return a;
- };
- cr.to_clamped_degrees = function (x)
- {
- return cr.clamp_angle_degrees(cr.to_degrees(x));
- };
- cr.to_clamped_radians = function (x)
- {
- return cr.clamp_angle(cr.to_radians(x));
- };
- cr.angleTo = function(x1, y1, x2, y2)
- {
- var dx = x2 - x1;
- var dy = y2 - y1;
- return Math.atan2(dy, dx);
- };
- cr.angleDiff = function (a1, a2)
- {
- if (a1 === a2)
- return 0;
- var s1 = Math.sin(a1);
- var c1 = Math.cos(a1);
- var s2 = Math.sin(a2);
- var c2 = Math.cos(a2);
- var n = s1 * s2 + c1 * c2;
- if (n >= 1)
- return 0;
- if (n <= -1)
- return cr.PI;
- return Math.acos(n);
- };
- cr.angleRotate = function (start, end, step)
- {
- var ss = Math.sin(start);
- var cs = Math.cos(start);
- var se = Math.sin(end);
- var ce = Math.cos(end);
- if (Math.acos(ss * se + cs * ce) > step)
- {
- if (cs * se - ss * ce > 0)
- return cr.clamp_angle(start + step);
- else
- return cr.clamp_angle(start - step);
- }
- else
- return cr.clamp_angle(end);
- };
- cr.angleClockwise = function (a1, a2)
- {
- var s1 = Math.sin(a1);
- var c1 = Math.cos(a1);
- var s2 = Math.sin(a2);
- var c2 = Math.cos(a2);
- return c1 * s2 - s1 * c2 <= 0;
- };
- cr.rotatePtAround = function (px, py, a, ox, oy, getx)
- {
- if (a === 0)
- return getx ? px : py;
- var sin_a = Math.sin(a);
- var cos_a = Math.cos(a);
- px -= ox;
- py -= oy;
- var left_sin_a = px * sin_a;
- var top_sin_a = py * sin_a;
- var left_cos_a = px * cos_a;
- var top_cos_a = py * cos_a;
- px = left_cos_a - top_sin_a;
- py = top_cos_a + left_sin_a;
- px += ox;
- py += oy;
- return getx ? px : py;
- }
- cr.distanceTo = function(x1, y1, x2, y2)
- {
- var dx = x2 - x1;
- var dy = y2 - y1;
- return Math.sqrt(dx*dx + dy*dy);
- };
- cr.xor = function (x, y)
- {
- return !x !== !y;
- };
- cr.lerp = function (a, b, x)
- {
- return a + (b - a) * x;
- };
- cr.unlerp = function (a, b, c)
- {
- if (a === b)
- return 0; // avoid divide by 0
- return (c - a) / (b - a);
- };
- cr.anglelerp = function (a, b, x)
- {
- var diff = cr.angleDiff(a, b);
- if (cr.angleClockwise(b, a))
- {
- return a + diff * x;
- }
- else
- {
- return a - diff * x;
- }
- };
- cr.qarp = function (a, b, c, x)
- {
- return cr.lerp(cr.lerp(a, b, x), cr.lerp(b, c, x), x);
- };
- cr.cubic = function (a, b, c, d, x)
- {
- return cr.lerp(cr.qarp(a, b, c, x), cr.qarp(b, c, d, x), x);
- };
- cr.cosp = function (a, b, x)
- {
- return (a + b + (a - b) * Math.cos(x * Math.PI)) / 2;
- };
- cr.hasAnyOwnProperty = function (o)
- {
- var p;
- for (p in o)
- {
- if (o.hasOwnProperty(p))
- return true;
- }
- return false;
- };
- cr.wipe = function (obj)
- {
- var p;
- for (p in obj)
- {
- if (obj.hasOwnProperty(p))
- delete obj[p];
- }
- };
- var startup_time = +(new Date());
- cr.performance_now = function()
- {
- if (typeof window["performance"] !== "undefined")
- {
- var winperf = window["performance"];
- if (typeof winperf.now !== "undefined")
- return winperf.now();
- else if (typeof winperf["webkitNow"] !== "undefined")
- return winperf["webkitNow"]();
- else if (typeof winperf["mozNow"] !== "undefined")
- return winperf["mozNow"]();
- else if (typeof winperf["msNow"] !== "undefined")
- return winperf["msNow"]();
- }
- return Date.now() - startup_time;
- };
- var isChrome = false;
- var isSafari = false;
- var isiOS = false;
- var isEjecta = false;
- if (typeof window !== "undefined") // not c2 editor
- {
- isChrome = /chrome/i.test(navigator.userAgent) || /chromium/i.test(navigator.userAgent);
- isSafari = !isChrome && /safari/i.test(navigator.userAgent);
- isiOS = /(iphone|ipod|ipad)/i.test(navigator.userAgent);
- isEjecta = window["c2ejecta"];
- }
- var supports_set = ((!isSafari && !isEjecta && !isiOS) && (typeof Set !== "undefined" && typeof Set.prototype["forEach"] !== "undefined"));
- function ObjectSet_()
- {
- this.s = null;
- this.items = null; // lazy allocated (hopefully results in better GC performance)
- this.item_count = 0;
- if (supports_set)
- {
- this.s = new Set();
- }
- this.values_cache = [];
- this.cache_valid = true;
- cr.seal(this);
- };
- ObjectSet_.prototype.contains = function (x)
- {
- if (this.isEmpty())
- return false;
- if (supports_set)
- return this.s["has"](x);
- else
- return (this.items && this.items.hasOwnProperty(x));
- };
- ObjectSet_.prototype.add = function (x)
- {
- if (supports_set)
- {
- if (!this.s["has"](x))
- {
- this.s["add"](x);
- this.cache_valid = false;
- }
- }
- else
- {
- var str = x.toString();
- var items = this.items;
- if (!items)
- {
- this.items = {};
- this.items[str] = x;
- this.item_count = 1;
- this.cache_valid = false;
- }
- else if (!items.hasOwnProperty(str))
- {
- items[str] = x;
- this.item_count++;
- this.cache_valid = false;
- }
- }
- };
- ObjectSet_.prototype.remove = function (x)
- {
- if (this.isEmpty())
- return;
- if (supports_set)
- {
- if (this.s["has"](x))
- {
- this.s["delete"](x);
- this.cache_valid = false;
- }
- }
- else if (this.items)
- {
- var str = x.toString();
- var items = this.items;
- if (items.hasOwnProperty(str))
- {
- delete items[str];
- this.item_count--;
- this.cache_valid = false;
- }
- }
- };
- ObjectSet_.prototype.clear = function (/*wipe_*/)
- {
- if (this.isEmpty())
- return;
- if (supports_set)
- {
- this.s["clear"](); // best!
- }
- else
- {
- this.items = null; // creates garbage; will lazy allocate on next add()
- this.item_count = 0;
- }
- cr.clearArray(this.values_cache);
- this.cache_valid = true;
- };
- ObjectSet_.prototype.isEmpty = function ()
- {
- return this.count() === 0;
- };
- ObjectSet_.prototype.count = function ()
- {
- if (supports_set)
- return this.s["size"];
- else
- return this.item_count;
- };
- var current_arr = null;
- var current_index = 0;
- function set_append_to_arr(x)
- {
- current_arr[current_index++] = x;
- };
- ObjectSet_.prototype.update_cache = function ()
- {
- if (this.cache_valid)
- return;
- if (supports_set)
- {
- cr.clearArray(this.values_cache);
- current_arr = this.values_cache;
- current_index = 0;
- this.s["forEach"](set_append_to_arr);
- ;
- current_arr = null;
- current_index = 0;
- }
- else
- {
- var values_cache = this.values_cache;
- cr.clearArray(values_cache);
- var p, n = 0, items = this.items;
- if (items)
- {
- for (p in items)
- {
- if (items.hasOwnProperty(p))
- values_cache[n++] = items[p];
- }
- }
- ;
- }
- this.cache_valid = true;
- };
- ObjectSet_.prototype.valuesRef = function ()
- {
- this.update_cache();
- return this.values_cache;
- };
- cr.ObjectSet = ObjectSet_;
- var tmpSet = new cr.ObjectSet();
- cr.removeArrayDuplicates = function (arr)
- {
- var i, len;
- for (i = 0, len = arr.length; i < len; ++i)
- {
- tmpSet.add(arr[i]);
- }
- cr.shallowAssignArray(arr, tmpSet.valuesRef());
- tmpSet.clear();
- };
- cr.arrayRemoveAllFromObjectSet = function (arr, remset)
- {
- if (supports_set)
- cr.arrayRemoveAll_set(arr, remset.s);
- else
- cr.arrayRemoveAll_arr(arr, remset.valuesRef());
- };
- cr.arrayRemoveAll_set = function (arr, s)
- {
- var i, j, len, item;
- for (i = 0, j = 0, len = arr.length; i < len; ++i)
- {
- item = arr[i];
- if (!s["has"](item)) // not an item to remove
- arr[j++] = item; // keep it
- }
- cr.truncateArray(arr, j);
- };
- cr.arrayRemoveAll_arr = function (arr, rem)
- {
- var i, j, len, item;
- for (i = 0, j = 0, len = arr.length; i < len; ++i)
- {
- item = arr[i];
- if (cr.fastIndexOf(rem, item) === -1) // not an item to remove
- arr[j++] = item; // keep it
- }
- cr.truncateArray(arr, j);
- };
- function KahanAdder_()
- {
- this.c = 0;
- this.y = 0;
- this.t = 0;
- this.sum = 0;
- cr.seal(this);
- };
- KahanAdder_.prototype.add = function (v)
- {
- this.y = v - this.c;
- this.t = this.sum + this.y;
- this.c = (this.t - this.sum) - this.y;
- this.sum = this.t;
- };
- KahanAdder_.prototype.reset = function ()
- {
- this.c = 0;
- this.y = 0;
- this.t = 0;
- this.sum = 0;
- };
- cr.KahanAdder = KahanAdder_;
- cr.regexp_escape = function(text)
- {
- return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
- };
- function CollisionPoly_(pts_array_)
- {
- this.pts_cache = [];
- this.bboxLeft = 0;
- this.bboxTop = 0;
- this.bboxRight = 0;
- this.bboxBottom = 0;
- this.convexpolys = null; // for physics behavior to cache separated polys
- this.set_pts(pts_array_);
- cr.seal(this);
- };
- CollisionPoly_.prototype.set_pts = function(pts_array_)
- {
- this.pts_array = pts_array_;
- this.pts_count = pts_array_.length / 2; // x, y, x, y... in array
- this.pts_cache.length = pts_array_.length;
- this.cache_width = -1;
- this.cache_height = -1;
- this.cache_angle = 0;
- };
- CollisionPoly_.prototype.is_empty = function()
- {
- return !this.pts_array.length;
- };
- CollisionPoly_.prototype.update_bbox = function ()
- {
- var myptscache = this.pts_cache;
- var bboxLeft_ = myptscache[0];
- var bboxRight_ = bboxLeft_;
- var bboxTop_ = myptscache[1];
- var bboxBottom_ = bboxTop_;
- var x, y, i = 1, i2, len = this.pts_count;
- for ( ; i < len; ++i)
- {
- i2 = i*2;
- x = myptscache[i2];
- y = myptscache[i2+1];
- if (x < bboxLeft_)
- bboxLeft_ = x;
- if (x > bboxRight_)
- bboxRight_ = x;
- if (y < bboxTop_)
- bboxTop_ = y;
- if (y > bboxBottom_)
- bboxBottom_ = y;
- }
- this.bboxLeft = bboxLeft_;
- this.bboxRight = bboxRight_;
- this.bboxTop = bboxTop_;
- this.bboxBottom = bboxBottom_;
- };
- CollisionPoly_.prototype.set_from_rect = function(rc, offx, offy)
- {
- this.pts_cache.length = 8;
- this.pts_count = 4;
- var myptscache = this.pts_cache;
- myptscache[0] = rc.left - offx;
- myptscache[1] = rc.top - offy;
- myptscache[2] = rc.right - offx;
- myptscache[3] = rc.top - offy;
- myptscache[4] = rc.right - offx;
- myptscache[5] = rc.bottom - offy;
- myptscache[6] = rc.left - offx;
- myptscache[7] = rc.bottom - offy;
- this.cache_width = rc.right - rc.left;
- this.cache_height = rc.bottom - rc.top;
- this.update_bbox();
- };
- CollisionPoly_.prototype.set_from_quad = function(q, offx, offy, w, h)
- {
- this.pts_cache.length = 8;
- this.pts_count = 4;
- var myptscache = this.pts_cache;
- myptscache[0] = q.tlx - offx;
- myptscache[1] = q.tly - offy;
- myptscache[2] = q.trx - offx;
- myptscache[3] = q.try_ - offy;
- myptscache[4] = q.brx - offx;
- myptscache[5] = q.bry - offy;
- myptscache[6] = q.blx - offx;
- myptscache[7] = q.bly - offy;
- this.cache_width = w;
- this.cache_height = h;
- this.update_bbox();
- };
- CollisionPoly_.prototype.set_from_poly = function (r)
- {
- this.pts_count = r.pts_count;
- cr.shallowAssignArray(this.pts_cache, r.pts_cache);
- this.bboxLeft = r.bboxLeft;
- this.bboxTop - r.bboxTop;
- this.bboxRight = r.bboxRight;
- this.bboxBottom = r.bboxBottom;
- };
- CollisionPoly_.prototype.cache_poly = function(w, h, a)
- {
- if (this.cache_width === w && this.cache_height === h && this.cache_angle === a)
- return; // cache up-to-date
- this.cache_width = w;
- this.cache_height = h;
- this.cache_angle = a;
- var i, i2, i21, len, x, y;
- var sina = 0;
- var cosa = 1;
- var myptsarray = this.pts_array;
- var myptscache = this.pts_cache;
- if (a !== 0)
- {
- sina = Math.sin(a);
- cosa = Math.cos(a);
- }
- for (i = 0, len = this.pts_count; i < len; i++)
- {
- i2 = i*2;
- i21 = i2+1;
- x = myptsarray[i2] * w;
- y = myptsarray[i21] * h;
- myptscache[i2] = (x * cosa) - (y * sina);
- myptscache[i21] = (y * cosa) + (x * sina);
- }
- this.update_bbox();
- };
- CollisionPoly_.prototype.contains_pt = function (a2x, a2y)
- {
- var myptscache = this.pts_cache;
- if (a2x === myptscache[0] && a2y === myptscache[1])
- return true;
- var i, i2, imod, len = this.pts_count;
- var a1x = this.bboxLeft - 110;
- var a1y = this.bboxTop - 101;
- var a3x = this.bboxRight + 131
- var a3y = this.bboxBottom + 120;
- var b1x, b1y, b2x, b2y;
- var count1 = 0, count2 = 0;
- for (i = 0; i < len; i++)
- {
- i2 = i*2;
- imod = ((i+1)%len)*2;
- b1x = myptscache[i2];
- b1y = myptscache[i2+1];
- b2x = myptscache[imod];
- b2y = myptscache[imod+1];
- if (cr.segments_intersect(a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y))
- count1++;
- if (cr.segments_intersect(a3x, a3y, a2x, a2y, b1x, b1y, b2x, b2y))
- count2++;
- }
- return (count1 % 2 === 1) || (count2 % 2 === 1);
- };
- CollisionPoly_.prototype.intersects_poly = function (rhs, offx, offy)
- {
- var rhspts = rhs.pts_cache;
- var mypts = this.pts_cache;
- if (this.contains_pt(rhspts[0] + offx, rhspts[1] + offy))
- return true;
- if (rhs.contains_pt(mypts[0] - offx, mypts[1] - offy))
- return true;
- var i, i2, imod, leni, j, j2, jmod, lenj;
- var a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y;
- for (i = 0, leni = this.pts_count; i < leni; i++)
- {
- i2 = i*2;
- imod = ((i+1)%leni)*2;
- a1x = mypts[i2];
- a1y = mypts[i2+1];
- a2x = mypts[imod];
- a2y = mypts[imod+1];
- for (j = 0, lenj = rhs.pts_count; j < lenj; j++)
- {
- j2 = j*2;
- jmod = ((j+1)%lenj)*2;
- b1x = rhspts[j2] + offx;
- b1y = rhspts[j2+1] + offy;
- b2x = rhspts[jmod] + offx;
- b2y = rhspts[jmod+1] + offy;
- if (cr.segments_intersect(a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y))
- return true;
- }
- }
- return false;
- };
- CollisionPoly_.prototype.intersects_segment = function (offx, offy, x1, y1, x2, y2)
- {
- var mypts = this.pts_cache;
- if (this.contains_pt(x1 - offx, y1 - offy))
- return true;
- var i, leni, i2, imod;
- var a1x, a1y, a2x, a2y;
- for (i = 0, leni = this.pts_count; i < leni; i++)
- {
- i2 = i*2;
- imod = ((i+1)%leni)*2;
- a1x = mypts[i2] + offx;
- a1y = mypts[i2+1] + offy;
- a2x = mypts[imod] + offx;
- a2y = mypts[imod+1] + offy;
- if (cr.segments_intersect(x1, y1, x2, y2, a1x, a1y, a2x, a2y))
- return true;
- }
- return false;
- };
- CollisionPoly_.prototype.mirror = function (px)
- {
- var i, leni, i2;
- for (i = 0, leni = this.pts_count; i < leni; ++i)
- {
- i2 = i*2;
- this.pts_cache[i2] = px * 2 - this.pts_cache[i2];
- }
- };
- CollisionPoly_.prototype.flip = function (py)
- {
- var i, leni, i21;
- for (i = 0, leni = this.pts_count; i < leni; ++i)
- {
- i21 = i*2+1;
- this.pts_cache[i21] = py * 2 - this.pts_cache[i21];
- }
- };
- CollisionPoly_.prototype.diag = function ()
- {
- var i, leni, i2, i21, temp;
- for (i = 0, leni = this.pts_count; i < leni; ++i)
- {
- i2 = i*2;
- i21 = i2+1;
- temp = this.pts_cache[i2];
- this.pts_cache[i2] = this.pts_cache[i21];
- this.pts_cache[i21] = temp;
- }
- };
- cr.CollisionPoly = CollisionPoly_;
- function SparseGrid_(cellwidth_, cellheight_)
- {
- this.cellwidth = cellwidth_;
- this.cellheight = cellheight_;
- this.cells = {};
- };
- SparseGrid_.prototype.totalCellCount = 0;
- SparseGrid_.prototype.getCell = function (x_, y_, create_if_missing)
- {
- var ret;
- var col = this.cells[x_];
- if (!col)
- {
- if (create_if_missing)
- {
- ret = allocGridCell(this, x_, y_);
- this.cells[x_] = {};
- this.cells[x_][y_] = ret;
- return ret;
- }
- else
- return null;
- }
- ret = col[y_];
- if (ret)
- return ret;
- else if (create_if_missing)
- {
- ret = allocGridCell(this, x_, y_);
- this.cells[x_][y_] = ret;
- return ret;
- }
- else
- return null;
- };
- SparseGrid_.prototype.XToCell = function (x_)
- {
- return cr.floor(x_ / this.cellwidth);
- };
- SparseGrid_.prototype.YToCell = function (y_)
- {
- return cr.floor(y_ / this.cellheight);
- };
- SparseGrid_.prototype.update = function (inst, oldrange, newrange)
- {
- var x, lenx, y, leny, cell;
- if (oldrange)
- {
- for (x = oldrange.left, lenx = oldrange.right; x <= lenx; ++x)
- {
- for (y = oldrange.top, leny = oldrange.bottom; y <= leny; ++y)
- {
- if (newrange && newrange.contains_pt(x, y))
- continue; // is still in this cell
- cell = this.getCell(x, y, false); // don't create if missing
- if (!cell)
- continue; // cell does not exist yet
- cell.remove(inst);
- if (cell.isEmpty())
- {
- freeGridCell(cell);
- this.cells[x][y] = null;
- }
- }
- }
- }
- if (newrange)
- {
- for (x = newrange.left, lenx = newrange.right; x <= lenx; ++x)
- {
- for (y = newrange.top, leny = newrange.bottom; y <= leny; ++y)
- {
- if (oldrange && oldrange.contains_pt(x, y))
- continue; // is still in this cell
- this.getCell(x, y, true).insert(inst);
- }
- }
- }
- };
- SparseGrid_.prototype.queryRange = function (rc, result)
- {
- var x, lenx, ystart, y, leny, cell;
- x = this.XToCell(rc.left);
- ystart = this.YToCell(rc.top);
- lenx = this.XToCell(rc.right);
- leny = this.YToCell(rc.bottom);
- for ( ; x <= lenx; ++x)
- {
- for (y = ystart; y <= leny; ++y)
- {
- cell = this.getCell(x, y, false);
- if (!cell)
- continue;
- cell.dump(result);
- }
- }
- };
- cr.SparseGrid = SparseGrid_;
- function RenderGrid_(cellwidth_, cellheight_)
- {
- this.cellwidth = cellwidth_;
- this.cellheight = cellheight_;
- this.cells = {};
- };
- RenderGrid_.prototype.totalCellCount = 0;
- RenderGrid_.prototype.getCell = function (x_, y_, create_if_missing)
- {
- var ret;
- var col = this.cells[x_];
- if (!col)
- {
- if (create_if_missing)
- {
- ret = allocRenderCell(this, x_, y_);
- this.cells[x_] = {};
- this.cells[x_][y_] = ret;
- return ret;
- }
- else
- return null;
- }
- ret = col[y_];
- if (ret)
- return ret;
- else if (create_if_missing)
- {
- ret = allocRenderCell(this, x_, y_);
- this.cells[x_][y_] = ret;
- return ret;
- }
- else
- return null;
- };
- RenderGrid_.prototype.XToCell = function (x_)
- {
- return cr.floor(x_ / this.cellwidth);
- };
- RenderGrid_.prototype.YToCell = function (y_)
- {
- return cr.floor(y_ / this.cellheight);
- };
- RenderGrid_.prototype.update = function (inst, oldrange, newrange)
- {
- var x, lenx, y, leny, cell;
- if (oldrange)
- {
- for (x = oldrange.left, lenx = oldrange.right; x <= lenx; ++x)
- {
- for (y = oldrange.top, leny = oldrange.bottom; y <= leny; ++y)
- {
- if (newrange && newrange.contains_pt(x, y))
- continue; // is still in this cell
- cell = this.getCell(x, y, false); // don't create if missing
- if (!cell)
- continue; // cell does not exist yet
- cell.remove(inst);
- if (cell.isEmpty())
- {
- freeRenderCell(cell);
- this.cells[x][y] = null;
- }
- }
- }
- }
- if (newrange)
- {
- for (x = newrange.left, lenx = newrange.right; x <= lenx; ++x)
- {
- for (y = newrange.top, leny = newrange.bottom; y <= leny; ++y)
- {
- if (oldrange && oldrange.contains_pt(x, y))
- continue; // is still in this cell
- this.getCell(x, y, true).insert(inst);
- }
- }
- }
- };
- RenderGrid_.prototype.queryRange = function (left, top, right, bottom, result)
- {
- var x, lenx, ystart, y, leny, cell;
- x = this.XToCell(left);
- ystart = this.YToCell(top);
- lenx = this.XToCell(right);
- leny = this.YToCell(bottom);
- for ( ; x <= lenx; ++x)
- {
- for (y = ystart; y <= leny; ++y)
- {
- cell = this.getCell(x, y, false);
- if (!cell)
- continue;
- cell.dump(result);
- }
- }
- };
- RenderGrid_.prototype.markRangeChanged = function (rc)
- {
- var x, lenx, ystart, y, leny, cell;
- x = rc.left;
- ystart = rc.top;
- lenx = rc.right;
- leny = rc.bottom;
- for ( ; x <= lenx; ++x)
- {
- for (y = ystart; y <= leny; ++y)
- {
- cell = this.getCell(x, y, false);
- if (!cell)
- continue;
- cell.is_sorted = false;
- }
- }
- };
- cr.RenderGrid = RenderGrid_;
- var gridcellcache = [];
- function allocGridCell(grid_, x_, y_)
- {
- var ret;
- SparseGrid_.prototype.totalCellCount++;
- if (gridcellcache.length)
- {
- ret = gridcellcache.pop();
- ret.grid = grid_;
- ret.x = x_;
- ret.y = y_;
- return ret;
- }
- else
- return new cr.GridCell(grid_, x_, y_);
- };
- function freeGridCell(c)
- {
- SparseGrid_.prototype.totalCellCount--;
- c.objects.clear();
- if (gridcellcache.length < 1000)
- gridcellcache.push(c);
- };
- function GridCell_(grid_, x_, y_)
- {
- this.grid = grid_;
- this.x = x_;
- this.y = y_;
- this.objects = new cr.ObjectSet();
- };
- GridCell_.prototype.isEmpty = function ()
- {
- return this.objects.isEmpty();
- };
- GridCell_.prototype.insert = function (inst)
- {
- this.objects.add(inst);
- };
- GridCell_.prototype.remove = function (inst)
- {
- this.objects.remove(inst);
- };
- GridCell_.prototype.dump = function (result)
- {
- cr.appendArray(result, this.objects.valuesRef());
- };
- cr.GridCell = GridCell_;
- var rendercellcache = [];
- function allocRenderCell(grid_, x_, y_)
- {
- var ret;
- RenderGrid_.prototype.totalCellCount++;
- if (rendercellcache.length)
- {
- ret = rendercellcache.pop();
- ret.grid = grid_;
- ret.x = x_;
- ret.y = y_;
- return ret;
- }
- else
- return new cr.RenderCell(grid_, x_, y_);
- };
- function freeRenderCell(c)
- {
- RenderGrid_.prototype.totalCellCount--;
- c.reset();
- if (rendercellcache.length < 1000)
- rendercellcache.push(c);
- };
- function RenderCell_(grid_, x_, y_)
- {
- this.grid = grid_;
- this.x = x_;
- this.y = y_;
- this.objects = []; // array which needs to be sorted by Z order
- this.is_sorted = true; // whether array is in correct sort order or not
- this.pending_removal = new cr.ObjectSet();
- this.any_pending_removal = false;
- };
- RenderCell_.prototype.isEmpty = function ()
- {
- if (!this.objects.length)
- {
- ;
- ;
- return true;
- }
- if (this.objects.length > this.pending_removal.count())
- return false;
- ;
- this.flush_pending(); // takes fast path and just resets state
- return true;
- };
- RenderCell_.prototype.insert = function (inst)
- {
- if (this.pending_removal.contains(inst))
- {
- this.pending_removal.remove(inst);
- if (this.pending_removal.isEmpty())
- this.any_pending_removal = false;
- return;
- }
- if (this.objects.length)
- {
- var top = this.objects[this.objects.length - 1];
- if (top.get_zindex() > inst.get_zindex())
- this.is_sorted = false; // 'inst' should be somewhere beneath 'top'
- this.objects.push(inst);
- }
- else
- {
- this.objects.push(inst);
- this.is_sorted = true;
- }
- ;
- };
- RenderCell_.prototype.remove = function (inst)
- {
- this.pending_removal.add(inst);
- this.any_pending_removal = true;
- if (this.pending_removal.count() >= 30)
- this.flush_pending();
- };
- RenderCell_.prototype.flush_pending = function ()
- {
- ;
- if (!this.any_pending_removal)
- return; // not changed
- if (this.pending_removal.count() === this.objects.length)
- {
- this.reset();
- return;
- }
- cr.arrayRemoveAllFromObjectSet(this.objects, this.pending_removal);
- this.pending_removal.clear();
- this.any_pending_removal = false;
- };
- function sortByInstanceZIndex(a, b)
- {
- return a.zindex - b.zindex;
- };
- RenderCell_.prototype.ensure_sorted = function ()
- {
- if (this.is_sorted)
- return; // already sorted
- this.objects.sort(sortByInstanceZIndex);
- this.is_sorted = true;
- };
- RenderCell_.prototype.reset = function ()
- {
- cr.clearArray(this.objects);
- this.is_sorted = true;
- this.pending_removal.clear();
- this.any_pending_removal = false;
- };
- RenderCell_.prototype.dump = function (result)
- {
- this.flush_pending();
- this.ensure_sorted();
- if (this.objects.length)
- result.push(this.objects);
- };
- cr.RenderCell = RenderCell_;
- var fxNames = [ "lighter",
- "xor",
- "copy",
- "destination-over",
- "source-in",
- "destination-in",
- "source-out",
- "destination-out",
- "source-atop",
- "destination-atop"];
- cr.effectToCompositeOp = function(effect)
- {
- if (effect <= 0 || effect >= 11)
- return "source-over";
- return fxNames[effect - 1]; // not including "none" so offset by 1
- };
- cr.setGLBlend = function(this_, effect, gl)
- {
- if (!gl)
- return;
- this_.srcBlend = gl.ONE;
- this_.destBlend = gl.ONE_MINUS_SRC_ALPHA;
- switch (effect) {
- case 1: // lighter (additive)
- this_.srcBlend = gl.ONE;
- this_.destBlend = gl.ONE;
- break;
- case 2: // xor
- break; // todo
- case 3: // copy
- this_.srcBlend = gl.ONE;
- this_.destBlend = gl.ZERO;
- break;
- case 4: // destination-over
- this_.srcBlend = gl.ONE_MINUS_DST_ALPHA;
- this_.destBlend = gl.ONE;
- break;
- case 5: // source-in
- this_.srcBlend = gl.DST_ALPHA;
- this_.destBlend = gl.ZERO;
- break;
- case 6: // destination-in
- this_.srcBlend = gl.ZERO;
- this_.destBlend = gl.SRC_ALPHA;
- break;
- case 7: // source-out
- this_.srcBlend = gl.ONE_MINUS_DST_ALPHA;
- this_.destBlend = gl.ZERO;
- break;
- case 8: // destination-out
- this_.srcBlend = gl.ZERO;
- this_.destBlend = gl.ONE_MINUS_SRC_ALPHA;
- break;
- case 9: // source-atop
- this_.srcBlend = gl.DST_ALPHA;
- this_.destBlend = gl.ONE_MINUS_SRC_ALPHA;
- break;
- case 10: // destination-atop
- this_.srcBlend = gl.ONE_MINUS_DST_ALPHA;
- this_.destBlend = gl.SRC_ALPHA;
- break;
- }
- };
- cr.round6dp = function (x)
- {
- return Math.round(x * 1000000) / 1000000;
- };
- /*
- var localeCompare_options = {
- "usage": "search",
- "sensitivity": "accent"
- };
- var has_localeCompare = !!"a".localeCompare;
- var localeCompare_works1 = (has_localeCompare && "a".localeCompare("A", undefined, localeCompare_options) === 0);
- var localeCompare_works2 = (has_localeCompare && "a".localeCompare("á", undefined, localeCompare_options) !== 0);
- var supports_localeCompare = (has_localeCompare && localeCompare_works1 && localeCompare_works2);
- */
- cr.equals_nocase = function (a, b)
- {
- if (typeof a !== "string" || typeof b !== "string")
- return false;
- if (a.length !== b.length)
- return false;
- if (a === b)
- return true;
- /*
- if (supports_localeCompare)
- {
- return (a.localeCompare(b, undefined, localeCompare_options) === 0);
- }
- else
- {
- */
- return a.toLowerCase() === b.toLowerCase();
- };
- cr.isCanvasInputEvent = function (e)
- {
- var target = e.target;
- if (!target)
- return true;
- if (target === document || target === window)
- return true;
- if (document && document.body && target === document.body)
- return true;
- if (cr.equals_nocase(target.tagName, "canvas"))
- return true;
- return false;
- };
- }());
- var MatrixArray=typeof Float32Array!=="undefined"?Float32Array:Array,glMatrixArrayType=MatrixArray,vec3={},mat3={},mat4={},quat4={};vec3.create=function(a){var b=new MatrixArray(3);a&&(b[0]=a[0],b[1]=a[1],b[2]=a[2]);return b};vec3.set=function(a,b){b[0]=a[0];b[1]=a[1];b[2]=a[2];return b};vec3.add=function(a,b,c){if(!c||a===c)return a[0]+=b[0],a[1]+=b[1],a[2]+=b[2],a;c[0]=a[0]+b[0];c[1]=a[1]+b[1];c[2]=a[2]+b[2];return c};
- vec3.subtract=function(a,b,c){if(!c||a===c)return a[0]-=b[0],a[1]-=b[1],a[2]-=b[2],a;c[0]=a[0]-b[0];c[1]=a[1]-b[1];c[2]=a[2]-b[2];return c};vec3.negate=function(a,b){b||(b=a);b[0]=-a[0];b[1]=-a[1];b[2]=-a[2];return b};vec3.scale=function(a,b,c){if(!c||a===c)return a[0]*=b,a[1]*=b,a[2]*=b,a;c[0]=a[0]*b;c[1]=a[1]*b;c[2]=a[2]*b;return c};
- vec3.normalize=function(a,b){b||(b=a);var c=a[0],d=a[1],e=a[2],g=Math.sqrt(c*c+d*d+e*e);if(g){if(g===1)return b[0]=c,b[1]=d,b[2]=e,b}else return b[0]=0,b[1]=0,b[2]=0,b;g=1/g;b[0]=c*g;b[1]=d*g;b[2]=e*g;return b};vec3.cross=function(a,b,c){c||(c=a);var d=a[0],e=a[1],a=a[2],g=b[0],f=b[1],b=b[2];c[0]=e*b-a*f;c[1]=a*g-d*b;c[2]=d*f-e*g;return c};vec3.length=function(a){var b=a[0],c=a[1],a=a[2];return Math.sqrt(b*b+c*c+a*a)};vec3.dot=function(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]};
- vec3.direction=function(a,b,c){c||(c=a);var d=a[0]-b[0],e=a[1]-b[1],a=a[2]-b[2],b=Math.sqrt(d*d+e*e+a*a);if(!b)return c[0]=0,c[1]=0,c[2]=0,c;b=1/b;c[0]=d*b;c[1]=e*b;c[2]=a*b;return c};vec3.lerp=function(a,b,c,d){d||(d=a);d[0]=a[0]+c*(b[0]-a[0]);d[1]=a[1]+c*(b[1]-a[1]);d[2]=a[2]+c*(b[2]-a[2]);return d};vec3.str=function(a){return"["+a[0]+", "+a[1]+", "+a[2]+"]"};
- mat3.create=function(a){var b=new MatrixArray(9);a&&(b[0]=a[0],b[1]=a[1],b[2]=a[2],b[3]=a[3],b[4]=a[4],b[5]=a[5],b[6]=a[6],b[7]=a[7],b[8]=a[8]);return b};mat3.set=function(a,b){b[0]=a[0];b[1]=a[1];b[2]=a[2];b[3]=a[3];b[4]=a[4];b[5]=a[5];b[6]=a[6];b[7]=a[7];b[8]=a[8];return b};mat3.identity=function(a){a[0]=1;a[1]=0;a[2]=0;a[3]=0;a[4]=1;a[5]=0;a[6]=0;a[7]=0;a[8]=1;return a};
- mat3.transpose=function(a,b){if(!b||a===b){var c=a[1],d=a[2],e=a[5];a[1]=a[3];a[2]=a[6];a[3]=c;a[5]=a[7];a[6]=d;a[7]=e;return a}b[0]=a[0];b[1]=a[3];b[2]=a[6];b[3]=a[1];b[4]=a[4];b[5]=a[7];b[6]=a[2];b[7]=a[5];b[8]=a[8];return b};mat3.toMat4=function(a,b){b||(b=mat4.create());b[15]=1;b[14]=0;b[13]=0;b[12]=0;b[11]=0;b[10]=a[8];b[9]=a[7];b[8]=a[6];b[7]=0;b[6]=a[5];b[5]=a[4];b[4]=a[3];b[3]=0;b[2]=a[2];b[1]=a[1];b[0]=a[0];return b};
- mat3.str=function(a){return"["+a[0]+", "+a[1]+", "+a[2]+", "+a[3]+", "+a[4]+", "+a[5]+", "+a[6]+", "+a[7]+", "+a[8]+"]"};mat4.create=function(a){var b=new MatrixArray(16);a&&(b[0]=a[0],b[1]=a[1],b[2]=a[2],b[3]=a[3],b[4]=a[4],b[5]=a[5],b[6]=a[6],b[7]=a[7],b[8]=a[8],b[9]=a[9],b[10]=a[10],b[11]=a[11],b[12]=a[12],b[13]=a[13],b[14]=a[14],b[15]=a[15]);return b};
- mat4.set=function(a,b){b[0]=a[0];b[1]=a[1];b[2]=a[2];b[3]=a[3];b[4]=a[4];b[5]=a[5];b[6]=a[6];b[7]=a[7];b[8]=a[8];b[9]=a[9];b[10]=a[10];b[11]=a[11];b[12]=a[12];b[13]=a[13];b[14]=a[14];b[15]=a[15];return b};mat4.identity=function(a){a[0]=1;a[1]=0;a[2]=0;a[3]=0;a[4]=0;a[5]=1;a[6]=0;a[7]=0;a[8]=0;a[9]=0;a[10]=1;a[11]=0;a[12]=0;a[13]=0;a[14]=0;a[15]=1;return a};
- mat4.transpose=function(a,b){if(!b||a===b){var c=a[1],d=a[2],e=a[3],g=a[6],f=a[7],h=a[11];a[1]=a[4];a[2]=a[8];a[3]=a[12];a[4]=c;a[6]=a[9];a[7]=a[13];a[8]=d;a[9]=g;a[11]=a[14];a[12]=e;a[13]=f;a[14]=h;return a}b[0]=a[0];b[1]=a[4];b[2]=a[8];b[3]=a[12];b[4]=a[1];b[5]=a[5];b[6]=a[9];b[7]=a[13];b[8]=a[2];b[9]=a[6];b[10]=a[10];b[11]=a[14];b[12]=a[3];b[13]=a[7];b[14]=a[11];b[15]=a[15];return b};
- mat4.determinant=function(a){var b=a[0],c=a[1],d=a[2],e=a[3],g=a[4],f=a[5],h=a[6],i=a[7],j=a[8],k=a[9],l=a[10],n=a[11],o=a[12],m=a[13],p=a[14],a=a[15];return o*k*h*e-j*m*h*e-o*f*l*e+g*m*l*e+j*f*p*e-g*k*p*e-o*k*d*i+j*m*d*i+o*c*l*i-b*m*l*i-j*c*p*i+b*k*p*i+o*f*d*n-g*m*d*n-o*c*h*n+b*m*h*n+g*c*p*n-b*f*p*n-j*f*d*a+g*k*d*a+j*c*h*a-b*k*h*a-g*c*l*a+b*f*l*a};
- mat4.inverse=function(a,b){b||(b=a);var c=a[0],d=a[1],e=a[2],g=a[3],f=a[4],h=a[5],i=a[6],j=a[7],k=a[8],l=a[9],n=a[10],o=a[11],m=a[12],p=a[13],r=a[14],s=a[15],A=c*h-d*f,B=c*i-e*f,t=c*j-g*f,u=d*i-e*h,v=d*j-g*h,w=e*j-g*i,x=k*p-l*m,y=k*r-n*m,z=k*s-o*m,C=l*r-n*p,D=l*s-o*p,E=n*s-o*r,q=1/(A*E-B*D+t*C+u*z-v*y+w*x);b[0]=(h*E-i*D+j*C)*q;b[1]=(-d*E+e*D-g*C)*q;b[2]=(p*w-r*v+s*u)*q;b[3]=(-l*w+n*v-o*u)*q;b[4]=(-f*E+i*z-j*y)*q;b[5]=(c*E-e*z+g*y)*q;b[6]=(-m*w+r*t-s*B)*q;b[7]=(k*w-n*t+o*B)*q;b[8]=(f*D-h*z+j*x)*q;
- b[9]=(-c*D+d*z-g*x)*q;b[10]=(m*v-p*t+s*A)*q;b[11]=(-k*v+l*t-o*A)*q;b[12]=(-f*C+h*y-i*x)*q;b[13]=(c*C-d*y+e*x)*q;b[14]=(-m*u+p*B-r*A)*q;b[15]=(k*u-l*B+n*A)*q;return b};mat4.toRotationMat=function(a,b){b||(b=mat4.create());b[0]=a[0];b[1]=a[1];b[2]=a[2];b[3]=a[3];b[4]=a[4];b[5]=a[5];b[6]=a[6];b[7]=a[7];b[8]=a[8];b[9]=a[9];b[10]=a[10];b[11]=a[11];b[12]=0;b[13]=0;b[14]=0;b[15]=1;return b};
- mat4.toMat3=function(a,b){b||(b=mat3.create());b[0]=a[0];b[1]=a[1];b[2]=a[2];b[3]=a[4];b[4]=a[5];b[5]=a[6];b[6]=a[8];b[7]=a[9];b[8]=a[10];return b};mat4.toInverseMat3=function(a,b){var c=a[0],d=a[1],e=a[2],g=a[4],f=a[5],h=a[6],i=a[8],j=a[9],k=a[10],l=k*f-h*j,n=-k*g+h*i,o=j*g-f*i,m=c*l+d*n+e*o;if(!m)return null;m=1/m;b||(b=mat3.create());b[0]=l*m;b[1]=(-k*d+e*j)*m;b[2]=(h*d-e*f)*m;b[3]=n*m;b[4]=(k*c-e*i)*m;b[5]=(-h*c+e*g)*m;b[6]=o*m;b[7]=(-j*c+d*i)*m;b[8]=(f*c-d*g)*m;return b};
- mat4.multiply=function(a,b,c){c||(c=a);var d=a[0],e=a[1],g=a[2],f=a[3],h=a[4],i=a[5],j=a[6],k=a[7],l=a[8],n=a[9],o=a[10],m=a[11],p=a[12],r=a[13],s=a[14],a=a[15],A=b[0],B=b[1],t=b[2],u=b[3],v=b[4],w=b[5],x=b[6],y=b[7],z=b[8],C=b[9],D=b[10],E=b[11],q=b[12],F=b[13],G=b[14],b=b[15];c[0]=A*d+B*h+t*l+u*p;c[1]=A*e+B*i+t*n+u*r;c[2]=A*g+B*j+t*o+u*s;c[3]=A*f+B*k+t*m+u*a;c[4]=v*d+w*h+x*l+y*p;c[5]=v*e+w*i+x*n+y*r;c[6]=v*g+w*j+x*o+y*s;c[7]=v*f+w*k+x*m+y*a;c[8]=z*d+C*h+D*l+E*p;c[9]=z*e+C*i+D*n+E*r;c[10]=z*g+C*
- j+D*o+E*s;c[11]=z*f+C*k+D*m+E*a;c[12]=q*d+F*h+G*l+b*p;c[13]=q*e+F*i+G*n+b*r;c[14]=q*g+F*j+G*o+b*s;c[15]=q*f+F*k+G*m+b*a;return c};mat4.multiplyVec3=function(a,b,c){c||(c=b);var d=b[0],e=b[1],b=b[2];c[0]=a[0]*d+a[4]*e+a[8]*b+a[12];c[1]=a[1]*d+a[5]*e+a[9]*b+a[13];c[2]=a[2]*d+a[6]*e+a[10]*b+a[14];return c};
- mat4.multiplyVec4=function(a,b,c){c||(c=b);var d=b[0],e=b[1],g=b[2],b=b[3];c[0]=a[0]*d+a[4]*e+a[8]*g+a[12]*b;c[1]=a[1]*d+a[5]*e+a[9]*g+a[13]*b;c[2]=a[2]*d+a[6]*e+a[10]*g+a[14]*b;c[3]=a[3]*d+a[7]*e+a[11]*g+a[15]*b;return c};
- mat4.translate=function(a,b,c){var d=b[0],e=b[1],b=b[2],g,f,h,i,j,k,l,n,o,m,p,r;if(!c||a===c)return a[12]=a[0]*d+a[4]*e+a[8]*b+a[12],a[13]=a[1]*d+a[5]*e+a[9]*b+a[13],a[14]=a[2]*d+a[6]*e+a[10]*b+a[14],a[15]=a[3]*d+a[7]*e+a[11]*b+a[15],a;g=a[0];f=a[1];h=a[2];i=a[3];j=a[4];k=a[5];l=a[6];n=a[7];o=a[8];m=a[9];p=a[10];r=a[11];c[0]=g;c[1]=f;c[2]=h;c[3]=i;c[4]=j;c[5]=k;c[6]=l;c[7]=n;c[8]=o;c[9]=m;c[10]=p;c[11]=r;c[12]=g*d+j*e+o*b+a[12];c[13]=f*d+k*e+m*b+a[13];c[14]=h*d+l*e+p*b+a[14];c[15]=i*d+n*e+r*b+a[15];
- return c};mat4.scale=function(a,b,c){var d=b[0],e=b[1],b=b[2];if(!c||a===c)return a[0]*=d,a[1]*=d,a[2]*=d,a[3]*=d,a[4]*=e,a[5]*=e,a[6]*=e,a[7]*=e,a[8]*=b,a[9]*=b,a[10]*=b,a[11]*=b,a;c[0]=a[0]*d;c[1]=a[1]*d;c[2]=a[2]*d;c[3]=a[3]*d;c[4]=a[4]*e;c[5]=a[5]*e;c[6]=a[6]*e;c[7]=a[7]*e;c[8]=a[8]*b;c[9]=a[9]*b;c[10]=a[10]*b;c[11]=a[11]*b;c[12]=a[12];c[13]=a[13];c[14]=a[14];c[15]=a[15];return c};
- mat4.rotate=function(a,b,c,d){var e=c[0],g=c[1],c=c[2],f=Math.sqrt(e*e+g*g+c*c),h,i,j,k,l,n,o,m,p,r,s,A,B,t,u,v,w,x,y,z;if(!f)return null;f!==1&&(f=1/f,e*=f,g*=f,c*=f);h=Math.sin(b);i=Math.cos(b);j=1-i;b=a[0];f=a[1];k=a[2];l=a[3];n=a[4];o=a[5];m=a[6];p=a[7];r=a[8];s=a[9];A=a[10];B=a[11];t=e*e*j+i;u=g*e*j+c*h;v=c*e*j-g*h;w=e*g*j-c*h;x=g*g*j+i;y=c*g*j+e*h;z=e*c*j+g*h;e=g*c*j-e*h;g=c*c*j+i;d?a!==d&&(d[12]=a[12],d[13]=a[13],d[14]=a[14],d[15]=a[15]):d=a;d[0]=b*t+n*u+r*v;d[1]=f*t+o*u+s*v;d[2]=k*t+m*u+A*
- v;d[3]=l*t+p*u+B*v;d[4]=b*w+n*x+r*y;d[5]=f*w+o*x+s*y;d[6]=k*w+m*x+A*y;d[7]=l*w+p*x+B*y;d[8]=b*z+n*e+r*g;d[9]=f*z+o*e+s*g;d[10]=k*z+m*e+A*g;d[11]=l*z+p*e+B*g;return d};mat4.rotateX=function(a,b,c){var d=Math.sin(b),b=Math.cos(b),e=a[4],g=a[5],f=a[6],h=a[7],i=a[8],j=a[9],k=a[10],l=a[11];c?a!==c&&(c[0]=a[0],c[1]=a[1],c[2]=a[2],c[3]=a[3],c[12]=a[12],c[13]=a[13],c[14]=a[14],c[15]=a[15]):c=a;c[4]=e*b+i*d;c[5]=g*b+j*d;c[6]=f*b+k*d;c[7]=h*b+l*d;c[8]=e*-d+i*b;c[9]=g*-d+j*b;c[10]=f*-d+k*b;c[11]=h*-d+l*b;return c};
- mat4.rotateY=function(a,b,c){var d=Math.sin(b),b=Math.cos(b),e=a[0],g=a[1],f=a[2],h=a[3],i=a[8],j=a[9],k=a[10],l=a[11];c?a!==c&&(c[4]=a[4],c[5]=a[5],c[6]=a[6],c[7]=a[7],c[12]=a[12],c[13]=a[13],c[14]=a[14],c[15]=a[15]):c=a;c[0]=e*b+i*-d;c[1]=g*b+j*-d;c[2]=f*b+k*-d;c[3]=h*b+l*-d;c[8]=e*d+i*b;c[9]=g*d+j*b;c[10]=f*d+k*b;c[11]=h*d+l*b;return c};
- mat4.rotateZ=function(a,b,c){var d=Math.sin(b),b=Math.cos(b),e=a[0],g=a[1],f=a[2],h=a[3],i=a[4],j=a[5],k=a[6],l=a[7];c?a!==c&&(c[8]=a[8],c[9]=a[9],c[10]=a[10],c[11]=a[11],c[12]=a[12],c[13]=a[13],c[14]=a[14],c[15]=a[15]):c=a;c[0]=e*b+i*d;c[1]=g*b+j*d;c[2]=f*b+k*d;c[3]=h*b+l*d;c[4]=e*-d+i*b;c[5]=g*-d+j*b;c[6]=f*-d+k*b;c[7]=h*-d+l*b;return c};
- mat4.frustum=function(a,b,c,d,e,g,f){f||(f=mat4.create());var h=b-a,i=d-c,j=g-e;f[0]=e*2/h;f[1]=0;f[2]=0;f[3]=0;f[4]=0;f[5]=e*2/i;f[6]=0;f[7]=0;f[8]=(b+a)/h;f[9]=(d+c)/i;f[10]=-(g+e)/j;f[11]=-1;f[12]=0;f[13]=0;f[14]=-(g*e*2)/j;f[15]=0;return f};mat4.perspective=function(a,b,c,d,e){a=c*Math.tan(a*Math.PI/360);b*=a;return mat4.frustum(-b,b,-a,a,c,d,e)};
- mat4.ortho=function(a,b,c,d,e,g,f){f||(f=mat4.create());var h=b-a,i=d-c,j=g-e;f[0]=2/h;f[1]=0;f[2]=0;f[3]=0;f[4]=0;f[5]=2/i;f[6]=0;f[7]=0;f[8]=0;f[9]=0;f[10]=-2/j;f[11]=0;f[12]=-(a+b)/h;f[13]=-(d+c)/i;f[14]=-(g+e)/j;f[15]=1;return f};
- mat4.lookAt=function(a,b,c,d){d||(d=mat4.create());var e,g,f,h,i,j,k,l,n=a[0],o=a[1],a=a[2];g=c[0];f=c[1];e=c[2];c=b[1];j=b[2];if(n===b[0]&&o===c&&a===j)return mat4.identity(d);c=n-b[0];j=o-b[1];k=a-b[2];l=1/Math.sqrt(c*c+j*j+k*k);c*=l;j*=l;k*=l;b=f*k-e*j;e=e*c-g*k;g=g*j-f*c;(l=Math.sqrt(b*b+e*e+g*g))?(l=1/l,b*=l,e*=l,g*=l):g=e=b=0;f=j*g-k*e;h=k*b-c*g;i=c*e-j*b;(l=Math.sqrt(f*f+h*h+i*i))?(l=1/l,f*=l,h*=l,i*=l):i=h=f=0;d[0]=b;d[1]=f;d[2]=c;d[3]=0;d[4]=e;d[5]=h;d[6]=j;d[7]=0;d[8]=g;d[9]=i;d[10]=k;d[11]=
- 0;d[12]=-(b*n+e*o+g*a);d[13]=-(f*n+h*o+i*a);d[14]=-(c*n+j*o+k*a);d[15]=1;return d};mat4.fromRotationTranslation=function(a,b,c){c||(c=mat4.create());var d=a[0],e=a[1],g=a[2],f=a[3],h=d+d,i=e+e,j=g+g,a=d*h,k=d*i;d*=j;var l=e*i;e*=j;g*=j;h*=f;i*=f;f*=j;c[0]=1-(l+g);c[1]=k+f;c[2]=d-i;c[3]=0;c[4]=k-f;c[5]=1-(a+g);c[6]=e+h;c[7]=0;c[8]=d+i;c[9]=e-h;c[10]=1-(a+l);c[11]=0;c[12]=b[0];c[13]=b[1];c[14]=b[2];c[15]=1;return c};
- mat4.str=function(a){return"["+a[0]+", "+a[1]+", "+a[2]+", "+a[3]+", "+a[4]+", "+a[5]+", "+a[6]+", "+a[7]+", "+a[8]+", "+a[9]+", "+a[10]+", "+a[11]+", "+a[12]+", "+a[13]+", "+a[14]+", "+a[15]+"]"};quat4.create=function(a){var b=new MatrixArray(4);a&&(b[0]=a[0],b[1]=a[1],b[2]=a[2],b[3]=a[3]);return b};quat4.set=function(a,b){b[0]=a[0];b[1]=a[1];b[2]=a[2];b[3]=a[3];return b};
- quat4.calculateW=function(a,b){var c=a[0],d=a[1],e=a[2];if(!b||a===b)return a[3]=-Math.sqrt(Math.abs(1-c*c-d*d-e*e)),a;b[0]=c;b[1]=d;b[2]=e;b[3]=-Math.sqrt(Math.abs(1-c*c-d*d-e*e));return b};quat4.inverse=function(a,b){if(!b||a===b)return a[0]*=-1,a[1]*=-1,a[2]*=-1,a;b[0]=-a[0];b[1]=-a[1];b[2]=-a[2];b[3]=a[3];return b};quat4.length=function(a){var b=a[0],c=a[1],d=a[2],a=a[3];return Math.sqrt(b*b+c*c+d*d+a*a)};
- quat4.normalize=function(a,b){b||(b=a);var c=a[0],d=a[1],e=a[2],g=a[3],f=Math.sqrt(c*c+d*d+e*e+g*g);if(f===0)return b[0]=0,b[1]=0,b[2]=0,b[3]=0,b;f=1/f;b[0]=c*f;b[1]=d*f;b[2]=e*f;b[3]=g*f;return b};quat4.multiply=function(a,b,c){c||(c=a);var d=a[0],e=a[1],g=a[2],a=a[3],f=b[0],h=b[1],i=b[2],b=b[3];c[0]=d*b+a*f+e*i-g*h;c[1]=e*b+a*h+g*f-d*i;c[2]=g*b+a*i+d*h-e*f;c[3]=a*b-d*f-e*h-g*i;return c};
- quat4.multiplyVec3=function(a,b,c){c||(c=b);var d=b[0],e=b[1],g=b[2],b=a[0],f=a[1],h=a[2],a=a[3],i=a*d+f*g-h*e,j=a*e+h*d-b*g,k=a*g+b*e-f*d,d=-b*d-f*e-h*g;c[0]=i*a+d*-b+j*-h-k*-f;c[1]=j*a+d*-f+k*-b-i*-h;c[2]=k*a+d*-h+i*-f-j*-b;return c};quat4.toMat3=function(a,b){b||(b=mat3.create());var c=a[0],d=a[1],e=a[2],g=a[3],f=c+c,h=d+d,i=e+e,j=c*f,k=c*h;c*=i;var l=d*h;d*=i;e*=i;f*=g;h*=g;g*=i;b[0]=1-(l+e);b[1]=k+g;b[2]=c-h;b[3]=k-g;b[4]=1-(j+e);b[5]=d+f;b[6]=c+h;b[7]=d-f;b[8]=1-(j+l);return b};
- quat4.toMat4=function(a,b){b||(b=mat4.create());var c=a[0],d=a[1],e=a[2],g=a[3],f=c+c,h=d+d,i=e+e,j=c*f,k=c*h;c*=i;var l=d*h;d*=i;e*=i;f*=g;h*=g;g*=i;b[0]=1-(l+e);b[1]=k+g;b[2]=c-h;b[3]=0;b[4]=k-g;b[5]=1-(j+e);b[6]=d+f;b[7]=0;b[8]=c+h;b[9]=d-f;b[10]=1-(j+l);b[11]=0;b[12]=0;b[13]=0;b[14]=0;b[15]=1;return b};
- quat4.slerp=function(a,b,c,d){d||(d=a);var e=a[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],g,f;if(Math.abs(e)>=1)return d!==a&&(d[0]=a[0],d[1]=a[1],d[2]=a[2],d[3]=a[3]),d;g=Math.acos(e);f=Math.sqrt(1-e*e);if(Math.abs(f)<0.001)return d[0]=a[0]*0.5+b[0]*0.5,d[1]=a[1]*0.5+b[1]*0.5,d[2]=a[2]*0.5+b[2]*0.5,d[3]=a[3]*0.5+b[3]*0.5,d;e=Math.sin((1-c)*g)/f;c=Math.sin(c*g)/f;d[0]=a[0]*e+b[0]*c;d[1]=a[1]*e+b[1]*c;d[2]=a[2]*e+b[2]*c;d[3]=a[3]*e+b[3]*c;return d};
- quat4.str=function(a){return"["+a[0]+", "+a[1]+", "+a[2]+", "+a[3]+"]"};
- (function()
- {
- var MAX_VERTICES = 8000; // equates to 2500 objects being drawn
- var MAX_INDICES = (MAX_VERTICES / 2) * 3; // 6 indices for every 4 vertices
- var MAX_POINTS = 8000;
- var MULTI_BUFFERS = 4; // cycle 4 buffers to try and avoid blocking
- var BATCH_NULL = 0;
- var BATCH_QUAD = 1;
- var BATCH_SETTEXTURE = 2;
- var BATCH_SETOPACITY = 3;
- var BATCH_SETBLEND = 4;
- var BATCH_UPDATEMODELVIEW = 5;
- var BATCH_RENDERTOTEXTURE = 6;
- var BATCH_CLEAR = 7;
- var BATCH_POINTS = 8;
- var BATCH_SETPROGRAM = 9;
- var BATCH_SETPROGRAMPARAMETERS = 10;
- var BATCH_SETTEXTURE1 = 11;
- /*
- var lose_ext = null;
- window.lose_context = function ()
- {
- if (!lose_ext)
- {
- console.log("WEBGL_lose_context not supported");
- return;
- }
- lose_ext.loseContext();
- };
- window.restore_context = function ()
- {
- if (!lose_ext)
- {
- console.log("WEBGL_lose_context not supported");
- return;
- }
- lose_ext.restoreContext();
- };
- */
- function GLWrap_(gl, isMobile)
- {
- this.isIE = /msie/i.test(navigator.userAgent) || /trident/i.test(navigator.userAgent);
- this.width = 0; // not yet known, wait for call to setSize()
- this.height = 0;
- this.cam = vec3.create([0, 0, 100]); // camera position
- this.look = vec3.create([0, 0, 0]); // lookat position
- this.up = vec3.create([0, 1, 0]); // up vector
- this.worldScale = vec3.create([1, 1, 1]); // world scaling factor
- this.enable_mipmaps = true;
- this.matP = mat4.create(); // perspective matrix
- this.matMV = mat4.create(); // model view matrix
- this.lastMV = mat4.create();
- this.currentMV = mat4.create();
- this.gl = gl;
- this.initState();
- };
- GLWrap_.prototype.initState = function ()
- {
- var gl = this.gl;
- var i, len;
- this.lastOpacity = 1;
- this.lastTexture0 = null; // last bound to TEXTURE0
- this.lastTexture1 = null; // last bound to TEXTURE1
- this.currentOpacity = 1;
- gl.clearColor(0, 0, 0, 0);
- gl.clear(gl.COLOR_BUFFER_BIT);
- gl.enable(gl.BLEND);
- gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
- gl.disable(gl.CULL_FACE);
- gl.disable(gl.DEPTH_TEST);
- this.maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
- this.lastSrcBlend = gl.ONE;
- this.lastDestBlend = gl.ONE_MINUS_SRC_ALPHA;
- this.vertexData = new Float32Array(MAX_VERTICES * 2);
- this.texcoordData = new Float32Array(MAX_VERTICES * 2);
- this.pointData = new Float32Array(MAX_POINTS * 4);
- this.pointBuffer = gl.createBuffer();
- gl.bindBuffer(gl.ARRAY_BUFFER, this.pointBuffer);
- gl.bufferData(gl.ARRAY_BUFFER, this.pointData.byteLength, gl.DYNAMIC_DRAW);
- this.vertexBuffers = new Array(MULTI_BUFFERS);
- this.texcoordBuffers = new Array(MULTI_BUFFERS);
- for (i = 0; i < MULTI_BUFFERS; i++)
- {
- this.vertexBuffers[i] = gl.createBuffer();
- gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffers[i]);
- gl.bufferData(gl.ARRAY_BUFFER, this.vertexData.byteLength, gl.DYNAMIC_DRAW);
- this.texcoordBuffers[i] = gl.createBuffer();
- gl.bindBuffer(gl.ARRAY_BUFFER, this.texcoordBuffers[i]);
- gl.bufferData(gl.ARRAY_BUFFER, this.texcoordData.byteLength, gl.DYNAMIC_DRAW);
- }
- this.curBuffer = 0;
- this.indexBuffer = gl.createBuffer();
- gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
- var indexData = new Uint16Array(MAX_INDICES);
- i = 0, len = MAX_INDICES;
- var fv = 0;
- while (i < len)
- {
- indexData[i++] = fv; // top left
- indexData[i++] = fv + 1; // top right
- indexData[i++] = fv + 2; // bottom right (first tri)
- indexData[i++] = fv; // top left
- indexData[i++] = fv + 2; // bottom right
- indexData[i++] = fv + 3; // bottom left
- fv += 4;
- }
- gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indexData, gl.STATIC_DRAW);
- this.vertexPtr = 0;
- this.pointPtr = 0;
- var fsSource, vsSource;
- this.shaderPrograms = [];
- fsSource = [
- "varying mediump vec2 vTex;",
- "uniform lowp float opacity;",
- "uniform lowp sampler2D samplerFront;",
- "void main(void) {",
- " gl_FragColor = texture2D(samplerFront, vTex);",
- " gl_FragColor *= opacity;",
- "}"
- ].join("\n");
- vsSource = [
- "attribute highp vec2 aPos;",
- "attribute mediump vec2 aTex;",
- "varying mediump vec2 vTex;",
- "uniform highp mat4 matP;",
- "uniform highp mat4 matMV;",
- "void main(void) {",
- " gl_Position = matP * matMV * vec4(aPos.x, aPos.y, 0.0, 1.0);",
- " vTex = aTex;",
- "}"
- ].join("\n");
- var shaderProg = this.createShaderProgram({src: fsSource}, vsSource, "<default>");
- ;
- this.shaderPrograms.push(shaderProg); // Default shader is always shader 0
- fsSource = [
- "uniform mediump sampler2D samplerFront;",
- "varying lowp float opacity;",
- "void main(void) {",
- " gl_FragColor = texture2D(samplerFront, gl_PointCoord);",
- " gl_FragColor *= opacity;",
- "}"
- ].join("\n");
- var pointVsSource = [
- "attribute vec4 aPos;",
- "varying float opacity;",
- "uniform mat4 matP;",
- "uniform mat4 matMV;",
- "void main(void) {",
- " gl_Position = matP * matMV * vec4(aPos.x, aPos.y, 0.0, 1.0);",
- " gl_PointSize = aPos.z;",
- " opacity = aPos.w;",
- "}"
- ].join("\n");
- shaderProg = this.createShaderProgram({src: fsSource}, pointVsSource, "<point>");
- ;
- this.shaderPrograms.push(shaderProg); // Point shader is always shader 1
- for (var shader_name in cr.shaders)
- {
- if (cr.shaders.hasOwnProperty(shader_name))
- this.shaderPrograms.push(this.createShaderProgram(cr.shaders[shader_name], vsSource, shader_name));
- }
- gl.activeTexture(gl.TEXTURE0);
- gl.bindTexture(gl.TEXTURE_2D, null);
- this.batch = [];
- this.batchPtr = 0;
- this.hasQuadBatchTop = false;
- this.hasPointBatchTop = false;
- this.lastProgram = -1; // start -1 so first switchProgram can do work
- this.currentProgram = -1; // current program during batch execution
- this.currentShader = null;
- this.fbo = gl.createFramebuffer();
- this.renderToTex = null;
- this.tmpVec3 = vec3.create([0, 0, 0]);
- ;
- var pointsizes = gl.getParameter(gl.ALIASED_POINT_SIZE_RANGE);
- this.minPointSize = pointsizes[0];
- this.maxPointSize = pointsizes[1];
- if (this.maxPointSize > 2048)
- this.maxPointSize = 2048;
- ;
- this.switchProgram(0);
- cr.seal(this);
- };
- function GLShaderProgram(gl, shaderProgram, name)
- {
- this.gl = gl;
- this.shaderProgram = shaderProgram;
- this.name = name;
- this.locAPos = gl.getAttribLocation(shaderProgram, "aPos");
- this.locATex = gl.getAttribLocation(shaderProgram, "aTex");
- this.locMatP = gl.getUniformLocation(shaderProgram, "matP");
- this.locMatMV = gl.getUniformLocation(shaderProgram, "matMV");
- this.locOpacity = gl.getUniformLocation(shaderProgram, "opacity");
- this.locSamplerFront = gl.getUniformLocation(shaderProgram, "samplerFront");
- this.locSamplerBack = gl.getUniformLocation(shaderProgram, "samplerBack");
- this.locDestStart = gl.getUniformLocation(shaderProgram, "destStart");
- this.locDestEnd = gl.getUniformLocation(shaderProgram, "destEnd");
- this.locSeconds = gl.getUniformLocation(shaderProgram, "seconds");
- this.locPixelWidth = gl.getUniformLocation(shaderProgram, "pixelWidth");
- this.locPixelHeight = gl.getUniformLocation(shaderProgram, "pixelHeight");
- this.locLayerScale = gl.getUniformLocation(shaderProgram, "layerScale");
- this.locLayerAngle = gl.getUniformLocation(shaderProgram, "layerAngle");
- this.locViewOrigin = gl.getUniformLocation(shaderProgram, "viewOrigin");
- this.locScrollPos = gl.getUniformLocation(shaderProgram, "scrollPos");
- this.hasAnyOptionalUniforms = !!(this.locPixelWidth || this.locPixelHeight || this.locSeconds || this.locSamplerBack || this.locDestStart || this.locDestEnd || this.locLayerScale || this.locLayerAngle || this.locViewOrigin || this.locScrollPos);
- this.lpPixelWidth = -999; // set to something unlikely so never counts as cached on first set
- this.lpPixelHeight = -999;
- this.lpOpacity = 1;
- this.lpDestStartX = 0.0;
- this.lpDestStartY = 0.0;
- this.lpDestEndX = 1.0;
- this.lpDestEndY = 1.0;
- this.lpLayerScale = 1.0;
- this.lpLayerAngle = 0.0;
- this.lpViewOriginX = 0.0;
- this.lpViewOriginY = 0.0;
- this.lpScrollPosX = 0.0;
- this.lpScrollPosY = 0.0;
- this.lastCustomParams = [];
- this.lpMatMV = mat4.create();
- if (this.locOpacity)
- gl.uniform1f(this.locOpacity, 1);
- if (this.locSamplerFront)
- gl.uniform1i(this.locSamplerFront, 0);
- if (this.locSamplerBack)
- gl.uniform1i(this.locSamplerBack, 1);
- if (this.locDestStart)
- gl.uniform2f(this.locDestStart, 0.0, 0.0);
- if (this.locDestEnd)
- gl.uniform2f(this.locDestEnd, 1.0, 1.0);
- if (this.locLayerScale)
- gl.uniform1f(this.locLayerScale, 1.0);
- if (this.locLayerAngle)
- gl.uniform1f(this.locLayerAngle, 0.0);
- if (this.locViewOrigin)
- gl.uniform2f(this.locViewOrigin, 0.0, 0.0);
- if (this.locScrollPos)
- gl.uniform2f(this.locScrollPos, 0.0, 0.0);
- this.hasCurrentMatMV = false; // matMV needs updating
- };
- function areMat4sEqual(a, b)
- {
- return a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&
- a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&
- a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&
- a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15];
- };
- GLShaderProgram.prototype.updateMatMV = function (mv)
- {
- if (areMat4sEqual(this.lpMatMV, mv))
- return; // no change, save the expensive GL call
- mat4.set(mv, this.lpMatMV);
- this.gl.uniformMatrix4fv(this.locMatMV, false, mv);
- };
- GLWrap_.prototype.createShaderProgram = function(shaderEntry, vsSource, name)
- {
- var gl = this.gl;
- var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
- gl.shaderSource(fragmentShader, shaderEntry.src);
- gl.compileShader(fragmentShader);
- if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS))
- {
- ;
- gl.deleteShader(fragmentShader);
- return null;
- }
- var vertexShader = gl.createShader(gl.VERTEX_SHADER);
- gl.shaderSource(vertexShader, vsSource);
- gl.compileShader(vertexShader);
- if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS))
- {
- ;
- gl.deleteShader(fragmentShader);
- gl.deleteShader(vertexShader);
- return null;
- }
- var shaderProgram = gl.createProgram();
- gl.attachShader(shaderProgram, fragmentShader);
- gl.attachShader(shaderProgram, vertexShader);
- gl.linkProgram(shaderProgram);
- if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS))
- {
- ;
- gl.deleteShader(fragmentShader);
- gl.deleteShader(vertexShader);
- gl.deleteProgram(shaderProgram);
- return null;
- }
- gl.useProgram(shaderProgram);
- gl.deleteShader(fragmentShader);
- gl.deleteShader(vertexShader);
- var ret = new GLShaderProgram(gl, shaderProgram, name);
- ret.extendBoxHorizontal = shaderEntry.extendBoxHorizontal || 0;
- ret.extendBoxVertical = shaderEntry.extendBoxVertical || 0;
- ret.crossSampling = !!shaderEntry.crossSampling;
- ret.animated = !!shaderEntry.animated;
- ret.parameters = shaderEntry.parameters || [];
- var i, len;
- for (i = 0, len = ret.parameters.length; i < len; i++)
- {
- ret.parameters[i][1] = gl.getUniformLocation(shaderProgram, ret.parameters[i][0]);
- ret.lastCustomParams.push(0);
- gl.uniform1f(ret.parameters[i][1], 0);
- }
- cr.seal(ret);
- return ret;
- };
- GLWrap_.prototype.getShaderIndex = function(name_)
- {
- var i, len;
- for (i = 0, len = this.shaderPrograms.length; i < len; i++)
- {
- if (this.shaderPrograms[i].name === name_)
- return i;
- }
- return -1;
- };
- GLWrap_.prototype.project = function (x, y, out)
- {
- var mv = this.matMV;
- var proj = this.matP;
- var fTempo = [0, 0, 0, 0, 0, 0, 0, 0];
- fTempo[0] = mv[0]*x+mv[4]*y+mv[12];
- fTempo[1] = mv[1]*x+mv[5]*y+mv[13];
- fTempo[2] = mv[2]*x+mv[6]*y+mv[14];
- fTempo[3] = mv[3]*x+mv[7]*y+mv[15];
- fTempo[4] = proj[0]*fTempo[0]+proj[4]*fTempo[1]+proj[8]*fTempo[2]+proj[12]*fTempo[3];
- fTempo[5] = proj[1]*fTempo[0]+proj[5]*fTempo[1]+proj[9]*fTempo[2]+proj[13]*fTempo[3];
- fTempo[6] = proj[2]*fTempo[0]+proj[6]*fTempo[1]+proj[10]*fTempo[2]+proj[14]*fTempo[3];
- fTempo[7] = -fTempo[2];
- if(fTempo[7]===0.0) //The w value
- return;
- fTempo[7]=1.0/fTempo[7];
- fTempo[4]*=fTempo[7];
- fTempo[5]*=fTempo[7];
- fTempo[6]*=fTempo[7];
- out[0]=(fTempo[4]*0.5+0.5)*this.width;
- out[1]=(fTempo[5]*0.5+0.5)*this.height;
- };
- GLWrap_.prototype.setSize = function(w, h, force)
- {
- if (this.width === w && this.height === h && !force)
- return;
- this.endBatch();
- this.width = w;
- this.height = h;
- this.gl.viewport(0, 0, w, h);
- mat4.perspective(45, w / h, 1, 1000, this.matP);
- mat4.lookAt(this.cam, this.look, this.up, this.matMV);
- var tl = [0, 0];
- var br = [0, 0];
- this.project(0, 0, tl);
- this.project(1, 1, br);
- this.worldScale[0] = 1 / (br[0] - tl[0]);
- this.worldScale[1] = -1 / (br[1] - tl[1]);
- var i, len, s;
- for (i = 0, len = this.shaderPrograms.length; i < len; i++)
- {
- s = this.shaderPrograms[i];
- s.hasCurrentMatMV = false;
- if (s.locMatP)
- {
- this.gl.useProgram(s.shaderProgram);
- this.gl.uniformMatrix4fv(s.locMatP, false, this.matP);
- }
- }
- this.gl.useProgram(this.shaderPrograms[this.lastProgram].shaderProgram);
- this.gl.bindTexture(this.gl.TEXTURE_2D, null);
- this.gl.activeTexture(this.gl.TEXTURE1);
- this.gl.bindTexture(this.gl.TEXTURE_2D, null);
- this.gl.activeTexture(this.gl.TEXTURE0);
- this.lastTexture0 = null;
- this.lastTexture1 = null;
- };
- GLWrap_.prototype.resetModelView = function ()
- {
- mat4.lookAt(this.cam, this.look, this.up, this.matMV);
- mat4.scale(this.matMV, this.worldScale);
- };
- GLWrap_.prototype.translate = function (x, y)
- {
- if (x === 0 && y === 0)
- return;
- this.tmpVec3[0] = x;// * this.worldScale[0];
- this.tmpVec3[1] = y;// * this.worldScale[1];
- this.tmpVec3[2] = 0;
- mat4.translate(this.matMV, this.tmpVec3);
- };
- GLWrap_.prototype.scale = function (x, y)
- {
- if (x === 1 && y === 1)
- return;
- this.tmpVec3[0] = x;
- this.tmpVec3[1] = y;
- this.tmpVec3[2] = 1;
- mat4.scale(this.matMV, this.tmpVec3);
- };
- GLWrap_.prototype.rotateZ = function (a)
- {
- if (a === 0)
- return;
- mat4.rotateZ(this.matMV, a);
- };
- GLWrap_.prototype.updateModelView = function()
- {
- var anydiff = false;
- for (var i = 0; i < 16; i++)
- {
- if (this.lastMV[i] !== this.matMV[i])
- {
- anydiff = true;
- break;
- }
- }
- if (!anydiff)
- return;
- var b = this.pushBatch();
- b.type = BATCH_UPDATEMODELVIEW;
- if (b.mat4param)
- mat4.set(this.matMV, b.mat4param);
- else
- b.mat4param = mat4.create(this.matMV);
- mat4.set(this.matMV, this.lastMV);
- this.hasQuadBatchTop = false;
- this.hasPointBatchTop = false;
- };
- /*
- var debugBatch = false;
- jQuery(document).mousedown(
- function(info) {
- if (info.which === 2)
- debugBatch = true;
- }
- );
- */
- function GLBatchJob(type_, glwrap_)
- {
- this.type = type_;
- this.glwrap = glwrap_;
- this.gl = glwrap_.gl;
- this.opacityParam = 0; // for setOpacity()
- this.startIndex = 0; // for quad()
- this.indexCount = 0; // "
- this.texParam = null; // for setTexture()
- this.mat4param = null; // for updateModelView()
- this.shaderParams = []; // for user parameters
- cr.seal(this);
- };
- GLBatchJob.prototype.doSetTexture = function ()
- {
- this.gl.bindTexture(this.gl.TEXTURE_2D, this.texParam);
- };
- GLBatchJob.prototype.doSetTexture1 = function ()
- {
- var gl = this.gl;
- gl.activeTexture(gl.TEXTURE1);
- gl.bindTexture(gl.TEXTURE_2D, this.texParam);
- gl.activeTexture(gl.TEXTURE0);
- };
- GLBatchJob.prototype.doSetOpacity = function ()
- {
- var o = this.opacityParam;
- var glwrap = this.glwrap;
- glwrap.currentOpacity = o;
- var curProg = glwrap.currentShader;
- if (curProg.locOpacity && curProg.lpOpacity !== o)
- {
- curProg.lpOpacity = o;
- this.gl.uniform1f(curProg.locOpacity, o);
- }
- };
- GLBatchJob.prototype.doQuad = function ()
- {
- this.gl.drawElements(this.gl.TRIANGLES, this.indexCount, this.gl.UNSIGNED_SHORT, this.startIndex * 2);
- };
- GLBatchJob.prototype.doSetBlend = function ()
- {
- this.gl.blendFunc(this.startIndex, this.indexCount);
- };
- GLBatchJob.prototype.doUpdateModelView = function ()
- {
- var i, len, s, shaderPrograms = this.glwrap.shaderPrograms, currentProgram = this.glwrap.currentProgram;
- for (i = 0, len = shaderPrograms.length; i < len; i++)
- {
- s = shaderPrograms[i];
- if (i === currentProgram && s.locMatMV)
- {
- s.updateMatMV(this.mat4param);
- s.hasCurrentMatMV = true;
- }
- else
- s.hasCurrentMatMV = false;
- }
- mat4.set(this.mat4param, this.glwrap.currentMV);
- };
- GLBatchJob.prototype.doRenderToTexture = function ()
- {
- var gl = this.gl;
- var glwrap = this.glwrap;
- if (this.texParam)
- {
- if (glwrap.lastTexture1 === this.texParam)
- {
- gl.activeTexture(gl.TEXTURE1);
- gl.bindTexture(gl.TEXTURE_2D, null);
- glwrap.lastTexture1 = null;
- gl.activeTexture(gl.TEXTURE0);
- }
- gl.bindFramebuffer(gl.FRAMEBUFFER, glwrap.fbo);
- gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texParam, 0);
- }
- else
- {
- gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, null, 0);
- gl.bindFramebuffer(gl.FRAMEBUFFER, null);
- }
- };
- GLBatchJob.prototype.doClear = function ()
- {
- var gl = this.gl;
- if (this.startIndex === 0) // clear whole surface
- {
- gl.clearColor(this.mat4param[0], this.mat4param[1], this.mat4param[2], this.mat4param[3]);
- gl.clear(gl.COLOR_BUFFER_BIT);
- }
- else // clear rectangle
- {
- gl.enable(gl.SCISSOR_TEST);
- gl.scissor(this.mat4param[0], this.mat4param[1], this.mat4param[2], this.mat4param[3]);
- gl.clearColor(0, 0, 0, 0);
- gl.clear(this.gl.COLOR_BUFFER_BIT);
- gl.disable(gl.SCISSOR_TEST);
- }
- };
- GLBatchJob.prototype.doPoints = function ()
- {
- var gl = this.gl;
- var glwrap = this.glwrap;
- var s = glwrap.shaderPrograms[1];
- gl.useProgram(s.shaderProgram);
- if (!s.hasCurrentMatMV && s.locMatMV)
- {
- s.updateMatMV(glwrap.currentMV);
- s.hasCurrentMatMV = true;
- }
- gl.enableVertexAttribArray(s.locAPos);
- gl.bindBuffer(gl.ARRAY_BUFFER, glwrap.pointBuffer);
- gl.vertexAttribPointer(s.locAPos, 4, gl.FLOAT, false, 0, 0);
- gl.drawArrays(gl.POINTS, this.startIndex / 4, this.indexCount);
- s = glwrap.currentShader;
- gl.useProgram(s.shaderProgram);
- if (s.locAPos >= 0)
- {
- gl.enableVertexAttribArray(s.locAPos);
- gl.bindBuffer(gl.ARRAY_BUFFER, glwrap.vertexBuffers[glwrap.curBuffer]);
- gl.vertexAttribPointer(s.locAPos, 2, gl.FLOAT, false, 0, 0);
- }
- if (s.locATex >= 0)
- {
- gl.enableVertexAttribArray(s.locATex);
- gl.bindBuffer(gl.ARRAY_BUFFER, glwrap.texcoordBuffers[glwrap.curBuffer]);
- gl.vertexAttribPointer(s.locATex, 2, gl.FLOAT, false, 0, 0);
- }
- };
- GLBatchJob.prototype.doSetProgram = function ()
- {
- var gl = this.gl;
- var glwrap = this.glwrap;
- var s = glwrap.shaderPrograms[this.startIndex]; // recycled param to save memory
- glwrap.currentProgram = this.startIndex; // current batch program
- glwrap.currentShader = s;
- gl.useProgram(s.shaderProgram); // switch to
- if (!s.hasCurrentMatMV && s.locMatMV)
- {
- s.updateMatMV(glwrap.currentMV);
- s.hasCurrentMatMV = true;
- }
- if (s.locOpacity && s.lpOpacity !== glwrap.currentOpacity)
- {
- s.lpOpacity = glwrap.currentOpacity;
- gl.uniform1f(s.locOpacity, glwrap.currentOpacity);
- }
- if (s.locAPos >= 0)
- {
- gl.enableVertexAttribArray(s.locAPos);
- gl.bindBuffer(gl.ARRAY_BUFFER, glwrap.vertexBuffers[glwrap.curBuffer]);
- gl.vertexAttribPointer(s.locAPos, 2, gl.FLOAT, false, 0, 0);
- }
- if (s.locATex >= 0)
- {
- gl.enableVertexAttribArray(s.locATex);
- gl.bindBuffer(gl.ARRAY_BUFFER, glwrap.texcoordBuffers[glwrap.curBuffer]);
- gl.vertexAttribPointer(s.locATex, 2, gl.FLOAT, false, 0, 0);
- }
- }
- GLBatchJob.prototype.doSetProgramParameters = function ()
- {
- var i, len, s = this.glwrap.currentShader;
- var gl = this.gl;
- var mat4param = this.mat4param;
- if (s.locSamplerBack && this.glwrap.lastTexture1 !== this.texParam)
- {
- gl.activeTexture(gl.TEXTURE1);
- gl.bindTexture(gl.TEXTURE_2D, this.texParam);
- this.glwrap.lastTexture1 = this.texParam;
- gl.activeTexture(gl.TEXTURE0);
- }
- var v = mat4param[0];
- var v2;
- if (s.locPixelWidth && v !== s.lpPixelWidth)
- {
- s.lpPixelWidth = v;
- gl.uniform1f(s.locPixelWidth, v);
- }
- v = mat4param[1];
- if (s.locPixelHeight && v !== s.lpPixelHeight)
- {
- s.lpPixelHeight = v;
- gl.uniform1f(s.locPixelHeight, v);
- }
- v = mat4param[2];
- v2 = mat4param[3];
- if (s.locDestStart && (v !== s.lpDestStartX || v2 !== s.lpDestStartY))
- {
- s.lpDestStartX = v;
- s.lpDestStartY = v2;
- gl.uniform2f(s.locDestStart, v, v2);
- }
- v = mat4param[4];
- v2 = mat4param[5];
- if (s.locDestEnd && (v !== s.lpDestEndX || v2 !== s.lpDestEndY))
- {
- s.lpDestEndX = v;
- s.lpDestEndY = v;
- gl.uniform2f(s.locDestEnd, v, v2);
- }
- v = mat4param[6];
- if (s.locLayerScale && v !== s.lpLayerScale)
- {
- s.lpLayerScale = v;
- gl.uniform1f(s.locLayerScale, v);
- }
- v = mat4param[7];
- if (s.locLayerAngle && v !== s.lpLayerAngle)
- {
- s.lpLayerAngle = v;
- gl.uniform1f(s.locLayerAngle, v);
- }
- v = mat4param[8];
- v2 = mat4param[9];
- if (s.locViewOrigin && (v !== s.lpViewOriginX || v2 !== s.lpViewOriginY))
- {
- s.lpViewOriginX = v;
- s.lpViewOriginY = v2;
- gl.uniform2f(s.locViewOrigin, v, v2);
- }
- v = mat4param[10];
- v2 = mat4param[11];
- if (s.locScrollPos && (v !== s.lpScrollPosX || v2 !== s.lpScrollPosY))
- {
- s.lpScrollPosX = v;
- s.lpScrollPosY = v2;
- gl.uniform2f(s.locScrollPos, v, v2);
- }
- if (s.locSeconds)
- gl.uniform1f(s.locSeconds, cr.performance_now() / 1000.0);
- if (s.parameters.length)
- {
- for (i = 0, len = s.parameters.length; i < len; i++)
- {
- v = this.shaderParams[i];
- if (v !== s.lastCustomParams[i])
- {
- s.lastCustomParams[i] = v;
- gl.uniform1f(s.parameters[i][1], v);
- }
- }
- }
- };
- GLWrap_.prototype.pushBatch = function ()
- {
- if (this.batchPtr === this.batch.length)
- this.batch.push(new GLBatchJob(BATCH_NULL, this));
- return this.batch[this.batchPtr++];
- };
- GLWrap_.prototype.endBatch = function ()
- {
- if (this.batchPtr === 0)
- return;
- if (this.gl.isContextLost())
- return;
- var gl = this.gl;
- if (this.pointPtr > 0)
- {
- gl.bindBuffer(gl.ARRAY_BUFFER, this.pointBuffer);
- gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.pointData.subarray(0, this.pointPtr));
- if (s && s.locAPos >= 0 && s.name === "<point>")
- gl.vertexAttribPointer(s.locAPos, 4, gl.FLOAT, false, 0, 0);
- }
- if (this.vertexPtr > 0)
- {
- var s = this.currentShader;
- gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffers[this.curBuffer]);
- gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertexData.subarray(0, this.vertexPtr));
- if (s && s.locAPos >= 0 && s.name !== "<point>")
- gl.vertexAttribPointer(s.locAPos, 2, gl.FLOAT, false, 0, 0);
- gl.bindBuffer(gl.ARRAY_BUFFER, this.texcoordBuffers[this.curBuffer]);
- gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.texcoordData.subarray(0, this.vertexPtr));
- if (s && s.locATex >= 0 && s.name !== "<point>")
- gl.vertexAttribPointer(s.locATex, 2, gl.FLOAT, false, 0, 0);
- }
- var i, len, b;
- for (i = 0, len = this.batchPtr; i < len; i++)
- {
- b = this.batch[i];
- switch (b.type) {
- case 1:
- b.doQuad();
- break;
- case 2:
- b.doSetTexture();
- break;
- case 3:
- b.doSetOpacity();
- break;
- case 4:
- b.doSetBlend();
- break;
- case 5:
- b.doUpdateModelView();
- break;
- case 6:
- b.doRenderToTexture();
- break;
- case 7:
- b.doClear();
- break;
- case 8:
- b.doPoints();
- break;
- case 9:
- b.doSetProgram();
- break;
- case 10:
- b.doSetProgramParameters();
- break;
- case 11:
- b.doSetTexture1();
- break;
- }
- }
- this.batchPtr = 0;
- this.vertexPtr = 0;
- this.pointPtr = 0;
- this.hasQuadBatchTop = false;
- this.hasPointBatchTop = false;
- this.curBuffer++;
- if (this.curBuffer >= MULTI_BUFFERS)
- this.curBuffer = 0;
- };
- GLWrap_.prototype.setOpacity = function (op)
- {
- if (op === this.lastOpacity)
- return;
- var b = this.pushBatch();
- b.type = BATCH_SETOPACITY;
- b.opacityParam = op;
- this.lastOpacity = op;
- this.hasQuadBatchTop = false;
- this.hasPointBatchTop = false;
- };
- GLWrap_.prototype.setTexture = function (tex)
- {
- if (tex === this.lastTexture0)
- return;
- ;
- var b = this.pushBatch();
- b.type = BATCH_SETTEXTURE;
- b.texParam = tex;
- this.lastTexture0 = tex;
- this.hasQuadBatchTop = false;
- this.hasPointBatchTop = false;
- };
- GLWrap_.prototype.setBlend = function (s, d)
- {
- if (s === this.lastSrcBlend && d === this.lastDestBlend)
- return;
- var b = this.pushBatch();
- b.type = BATCH_SETBLEND;
- b.startIndex = s; // recycle params to save memory
- b.indexCount = d;
- this.lastSrcBlend = s;
- this.lastDestBlend = d;
- this.hasQuadBatchTop = false;
- this.hasPointBatchTop = false;
- };
- GLWrap_.prototype.isPremultipliedAlphaBlend = function ()
- {
- return (this.lastSrcBlend === this.gl.ONE && this.lastDestBlend === this.gl.ONE_MINUS_SRC_ALPHA);
- };
- GLWrap_.prototype.setAlphaBlend = function ()
- {
- this.setBlend(this.gl.ONE, this.gl.ONE_MINUS_SRC_ALPHA);
- };
- GLWrap_.prototype.setNoPremultiplyAlphaBlend = function ()
- {
- this.setBlend(this.gl.SRC_ALPHA, this.gl.ONE_MINUS_SRC_ALPHA);
- };
- var LAST_VERTEX = MAX_VERTICES * 2 - 8;
- GLWrap_.prototype.quad = function(tlx, tly, trx, try_, brx, bry, blx, bly)
- {
- if (this.vertexPtr >= LAST_VERTEX)
- this.endBatch();
- var v = this.vertexPtr; // vertex cursor
- var vd = this.vertexData; // vertex data array
- var td = this.texcoordData; // texture coord data array
- if (this.hasQuadBatchTop)
- {
- this.batch[this.batchPtr - 1].indexCount += 6;
- }
- else
- {
- var b = this.pushBatch();
- b.type = BATCH_QUAD;
- b.startIndex = (v / 4) * 3;
- b.indexCount = 6;
- this.hasQuadBatchTop = true;
- this.hasPointBatchTop = false;
- }
- vd[v] = tlx;
- td[v++] = 0;
- vd[v] = tly;
- td[v++] = 0;
- vd[v] = trx;
- td[v++] = 1;
- vd[v] = try_;
- td[v++] = 0;
- vd[v] = brx;
- td[v++] = 1;
- vd[v] = bry;
- td[v++] = 1;
- vd[v] = blx;
- td[v++] = 0;
- vd[v] = bly;
- td[v++] = 1;
- this.vertexPtr = v;
- };
- GLWrap_.prototype.quadTex = function(tlx, tly, trx, try_, brx, bry, blx, bly, rcTex)
- {
- if (this.vertexPtr >= LAST_VERTEX)
- this.endBatch();
- var v = this.vertexPtr; // vertex cursor
- var vd = this.vertexData; // vertex data array
- var td = this.texcoordData; // texture coord data array
- if (this.hasQuadBatchTop)
- {
- this.batch[this.batchPtr - 1].indexCount += 6;
- }
- else
- {
- var b = this.pushBatch();
- b.type = BATCH_QUAD;
- b.startIndex = (v / 4) * 3;
- b.indexCount = 6;
- this.hasQuadBatchTop = true;
- this.hasPointBatchTop = false;
- }
- var rc_left = rcTex.left;
- var rc_top = rcTex.top;
- var rc_right = rcTex.right;
- var rc_bottom = rcTex.bottom;
- vd[v] = tlx;
- td[v++] = rc_left;
- vd[v] = tly;
- td[v++] = rc_top;
- vd[v] = trx;
- td[v++] = rc_right;
- vd[v] = try_;
- td[v++] = rc_top;
- vd[v] = brx;
- td[v++] = rc_right;
- vd[v] = bry;
- td[v++] = rc_bottom;
- vd[v] = blx;
- td[v++] = rc_left;
- vd[v] = bly;
- td[v++] = rc_bottom;
- this.vertexPtr = v;
- };
- GLWrap_.prototype.quadTexUV = function(tlx, tly, trx, try_, brx, bry, blx, bly, tlu, tlv, tru, trv, bru, brv, blu, blv)
- {
- if (this.vertexPtr >= LAST_VERTEX)
- this.endBatch();
- var v = this.vertexPtr; // vertex cursor
- var vd = this.vertexData; // vertex data array
- var td = this.texcoordData; // texture coord data array
- if (this.hasQuadBatchTop)
- {
- this.batch[this.batchPtr - 1].indexCount += 6;
- }
- else
- {
- var b = this.pushBatch();
- b.type = BATCH_QUAD;
- b.startIndex = (v / 4) * 3;
- b.indexCount = 6;
- this.hasQuadBatchTop = true;
- this.hasPointBatchTop = false;
- }
- vd[v] = tlx;
- td[v++] = tlu;
- vd[v] = tly;
- td[v++] = tlv;
- vd[v] = trx;
- td[v++] = tru;
- vd[v] = try_;
- td[v++] = trv;
- vd[v] = brx;
- td[v++] = bru;
- vd[v] = bry;
- td[v++] = brv;
- vd[v] = blx;
- td[v++] = blu;
- vd[v] = bly;
- td[v++] = blv;
- this.vertexPtr = v;
- };
- GLWrap_.prototype.convexPoly = function(pts)
- {
- var pts_count = pts.length / 2;
- ;
- var tris = pts_count - 2; // 3 points = 1 tri, 4 points = 2 tris, 5 points = 3 tris etc.
- var last_tri = tris - 1;
- var p0x = pts[0];
- var p0y = pts[1];
- var i, i2, p1x, p1y, p2x, p2y, p3x, p3y;
- for (i = 0; i < tris; i += 2) // draw 2 triangles at a time
- {
- i2 = i * 2;
- p1x = pts[i2 + 2];
- p1y = pts[i2 + 3];
- p2x = pts[i2 + 4];
- p2y = pts[i2 + 5];
- if (i === last_tri)
- {
- this.quad(p0x, p0y, p1x, p1y, p2x, p2y, p2x, p2y);
- }
- else
- {
- p3x = pts[i2 + 6];
- p3y = pts[i2 + 7];
- this.quad(p0x, p0y, p1x, p1y, p2x, p2y, p3x, p3y);
- }
- }
- };
- var LAST_POINT = MAX_POINTS - 4;
- GLWrap_.prototype.point = function(x_, y_, size_, opacity_)
- {
- if (this.pointPtr >= LAST_POINT)
- this.endBatch();
- var p = this.pointPtr; // point cursor
- var pd = this.pointData; // point data array
- if (this.hasPointBatchTop)
- {
- this.batch[this.batchPtr - 1].indexCount++;
- }
- else
- {
- var b = this.pushBatch();
- b.type = BATCH_POINTS;
- b.startIndex = p;
- b.indexCount = 1;
- this.hasPointBatchTop = true;
- this.hasQuadBatchTop = false;
- }
- pd[p++] = x_;
- pd[p++] = y_;
- pd[p++] = size_;
- pd[p++] = opacity_;
- this.pointPtr = p;
- };
- GLWrap_.prototype.switchProgram = function (progIndex)
- {
- if (this.lastProgram === progIndex)
- return; // no change
- var shaderProg = this.shaderPrograms[progIndex];
- if (!shaderProg)
- {
- if (this.lastProgram === 0)
- return; // already on default shader
- progIndex = 0;
- shaderProg = this.shaderPrograms[0];
- }
- var b = this.pushBatch();
- b.type = BATCH_SETPROGRAM;
- b.startIndex = progIndex;
- this.lastProgram = progIndex;
- this.hasQuadBatchTop = false;
- this.hasPointBatchTop = false;
- };
- GLWrap_.prototype.programUsesDest = function (progIndex)
- {
- var s = this.shaderPrograms[progIndex];
- return !!(s.locDestStart || s.locDestEnd);
- };
- GLWrap_.prototype.programUsesCrossSampling = function (progIndex)
- {
- var s = this.shaderPrograms[progIndex];
- return !!(s.locDestStart || s.locDestEnd || s.crossSampling);
- };
- GLWrap_.prototype.programExtendsBox = function (progIndex)
- {
- var s = this.shaderPrograms[progIndex];
- return s.extendBoxHorizontal !== 0 || s.extendBoxVertical !== 0;
- };
- GLWrap_.prototype.getProgramBoxExtendHorizontal = function (progIndex)
- {
- return this.shaderPrograms[progIndex].extendBoxHorizontal;
- };
- GLWrap_.prototype.getProgramBoxExtendVertical = function (progIndex)
- {
- return this.shaderPrograms[progIndex].extendBoxVertical;
- };
- GLWrap_.prototype.getProgramParameterType = function (progIndex, paramIndex)
- {
- return this.shaderPrograms[progIndex].parameters[paramIndex][2];
- };
- GLWrap_.prototype.programIsAnimated = function (progIndex)
- {
- return this.shaderPrograms[progIndex].animated;
- };
- GLWrap_.prototype.setProgramParameters = function (backTex, pixelWidth, pixelHeight, destStartX, destStartY, destEndX, destEndY, layerScale, layerAngle, viewOriginLeft, viewOriginTop, scrollPosX, scrollPosY, params)
- {
- var i, len;
- var s = this.shaderPrograms[this.lastProgram];
- var b, mat4param, shaderParams;
- if (s.hasAnyOptionalUniforms || params.length)
- {
- b = this.pushBatch();
- b.type = BATCH_SETPROGRAMPARAMETERS;
- if (b.mat4param)
- mat4.set(this.matMV, b.mat4param);
- else
- b.mat4param = mat4.create();
- mat4param = b.mat4param;
- mat4param[0] = pixelWidth;
- mat4param[1] = pixelHeight;
- mat4param[2] = destStartX;
- mat4param[3] = destStartY;
- mat4param[4] = destEndX;
- mat4param[5] = destEndY;
- mat4param[6] = layerScale;
- mat4param[7] = layerAngle;
- mat4param[8] = viewOriginLeft;
- mat4param[9] = viewOriginTop;
- mat4param[10] = scrollPosX;
- mat4param[11] = scrollPosY;
- if (s.locSamplerBack)
- {
- ;
- b.texParam = backTex;
- }
- else
- b.texParam = null;
- if (params.length)
- {
- shaderParams = b.shaderParams;
- shaderParams.length = params.length;
- for (i = 0, len = params.length; i < len; i++)
- shaderParams[i] = params[i];
- }
- this.hasQuadBatchTop = false;
- this.hasPointBatchTop = false;
- }
- };
- GLWrap_.prototype.clear = function (r, g, b_, a)
- {
- var b = this.pushBatch();
- b.type = BATCH_CLEAR;
- b.startIndex = 0; // clear all mode
- if (!b.mat4param)
- b.mat4param = mat4.create();
- b.mat4param[0] = r;
- b.mat4param[1] = g;
- b.mat4param[2] = b_;
- b.mat4param[3] = a;
- this.hasQuadBatchTop = false;
- this.hasPointBatchTop = false;
- };
- GLWrap_.prototype.clearRect = function (x, y, w, h)
- {
- if (w < 0 || h < 0)
- return; // invalid clear area
- var b = this.pushBatch();
- b.type = BATCH_CLEAR;
- b.startIndex = 1; // clear rect mode
- if (!b.mat4param)
- b.mat4param = mat4.create();
- b.mat4param[0] = x;
- b.mat4param[1] = y;
- b.mat4param[2] = w;
- b.mat4param[3] = h;
- this.hasQuadBatchTop = false;
- this.hasPointBatchTop = false;
- };
- GLWrap_.prototype.present = function ()
- {
- this.endBatch();
- this.gl.flush();
- /*
- if (debugBatch)
- {
- ;
- debugBatch = false;
- }
- */
- };
- function nextHighestPowerOfTwo(x) {
- --x;
- for (var i = 1; i < 32; i <<= 1) {
- x = x | x >> i;
- }
- return x + 1;
- }
- var all_textures = [];
- var textures_by_src = {};
- GLWrap_.prototype.contextLost = function ()
- {
- all_textures.length = 0;
- textures_by_src = {};
- };
- var BF_RGBA8 = 0;
- var BF_RGB8 = 1;
- var BF_RGBA4 = 2;
- var BF_RGB5_A1 = 3;
- var BF_RGB565 = 4;
- GLWrap_.prototype.loadTexture = function (img, tiling, linearsampling, pixelformat, tiletype, nomip)
- {
- tiling = !!tiling;
- linearsampling = !!linearsampling;
- var tex_key = img.src + "," + tiling + "," + linearsampling + (tiling ? ("," + tiletype) : "");
- var webGL_texture = null;
- if (typeof img.src !== "undefined" && textures_by_src.hasOwnProperty(tex_key))
- {
- webGL_texture = textures_by_src[tex_key];
- webGL_texture.c2refcount++;
- return webGL_texture;
- }
- this.endBatch();
- ;
- var gl = this.gl;
- var isPOT = (cr.isPOT(img.width) && cr.isPOT(img.height));
- webGL_texture = gl.createTexture();
- gl.bindTexture(gl.TEXTURE_2D, webGL_texture);
- gl.pixelStorei(gl["UNPACK_PREMULTIPLY_ALPHA_WEBGL"], true);
- var internalformat = gl.RGBA;
- var format = gl.RGBA;
- var type = gl.UNSIGNED_BYTE;
- if (pixelformat && !this.isIE)
- {
- switch (pixelformat) {
- case BF_RGB8:
- internalformat = gl.RGB;
- format = gl.RGB;
- break;
- case BF_RGBA4:
- type = gl.UNSIGNED_SHORT_4_4_4_4;
- break;
- case BF_RGB5_A1:
- type = gl.UNSIGNED_SHORT_5_5_5_1;
- break;
- case BF_RGB565:
- internalformat = gl.RGB;
- format = gl.RGB;
- type = gl.UNSIGNED_SHORT_5_6_5;
- break;
- }
- }
- if (!isPOT && tiling)
- {
- var canvas = document.createElement("canvas");
- canvas.width = cr.nextHighestPowerOfTwo(img.width);
- canvas.height = cr.nextHighestPowerOfTwo(img.height);
- var ctx = canvas.getContext("2d");
- ctx["webkitImageSmoothingEnabled"] = linearsampling;
- ctx["mozImageSmoothingEnabled"] = linearsampling;
- ctx["msImageSmoothingEnabled"] = linearsampling;
- ctx["imageSmoothingEnabled"] = linearsampling;
- ctx.drawImage(img,
- 0, 0, img.width, img.height,
- 0, 0, canvas.width, canvas.height);
- gl.texImage2D(gl.TEXTURE_2D, 0, internalformat, format, type, canvas);
- }
- else
- gl.texImage2D(gl.TEXTURE_2D, 0, internalformat, format, type, img);
- if (tiling)
- {
- if (tiletype === "repeat-x")
- {
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- }
- else if (tiletype === "repeat-y")
- {
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
- }
- else
- {
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
- }
- }
- else
- {
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- }
- if (linearsampling)
- {
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
- if (isPOT && this.enable_mipmaps && !nomip)
- {
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
- gl.generateMipmap(gl.TEXTURE_2D);
- }
- else
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
- }
- else
- {
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
- }
- gl.bindTexture(gl.TEXTURE_2D, null);
- this.lastTexture0 = null;
- webGL_texture.c2width = img.width;
- webGL_texture.c2height = img.height;
- webGL_texture.c2refcount = 1;
- webGL_texture.c2texkey = tex_key;
- all_textures.push(webGL_texture);
- textures_by_src[tex_key] = webGL_texture;
- return webGL_texture;
- };
- GLWrap_.prototype.createEmptyTexture = function (w, h, linearsampling, _16bit, tiling)
- {
- this.endBatch();
- var gl = this.gl;
- if (this.isIE)
- _16bit = false;
- var webGL_texture = gl.createTexture();
- gl.bindTexture(gl.TEXTURE_2D, webGL_texture);
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, w, h, 0, gl.RGBA, _16bit ? gl.UNSIGNED_SHORT_4_4_4_4 : gl.UNSIGNED_BYTE, null);
- if (tiling)
- {
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
- }
- else
- {
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- }
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linearsampling ? gl.LINEAR : gl.NEAREST);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linearsampling ? gl.LINEAR : gl.NEAREST);
- gl.bindTexture(gl.TEXTURE_2D, null);
- this.lastTexture0 = null;
- webGL_texture.c2width = w;
- webGL_texture.c2height = h;
- all_textures.push(webGL_texture);
- return webGL_texture;
- };
- GLWrap_.prototype.videoToTexture = function (video_, texture_, _16bit)
- {
- this.endBatch();
- var gl = this.gl;
- if (this.isIE)
- _16bit = false;
- gl.bindTexture(gl.TEXTURE_2D, texture_);
- gl.pixelStorei(gl["UNPACK_PREMULTIPLY_ALPHA_WEBGL"], true);
- try {
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, _16bit ? gl.UNSIGNED_SHORT_4_4_4_4 : gl.UNSIGNED_BYTE, video_);
- }
- catch (e)
- {
- if (console && console.error)
- console.error("Error updating WebGL texture: ", e);
- }
- gl.bindTexture(gl.TEXTURE_2D, null);
- this.lastTexture0 = null;
- };
- GLWrap_.prototype.deleteTexture = function (tex)
- {
- if (!tex)
- return;
- if (typeof tex.c2refcount !== "undefined" && tex.c2refcount > 1)
- {
- tex.c2refcount--;
- return;
- }
- this.endBatch();
- if (tex === this.lastTexture0)
- {
- this.gl.bindTexture(this.gl.TEXTURE_2D, null);
- this.lastTexture0 = null;
- }
- if (tex === this.lastTexture1)
- {
- this.gl.activeTexture(this.gl.TEXTURE1);
- this.gl.bindTexture(this.gl.TEXTURE_2D, null);
- this.gl.activeTexture(this.gl.TEXTURE0);
- this.lastTexture1 = null;
- }
- cr.arrayFindRemove(all_textures, tex);
- if (typeof tex.c2texkey !== "undefined")
- delete textures_by_src[tex.c2texkey];
- this.gl.deleteTexture(tex);
- };
- GLWrap_.prototype.estimateVRAM = function ()
- {
- var total = this.width * this.height * 4 * 2;
- var i, len, t;
- for (i = 0, len = all_textures.length; i < len; i++)
- {
- t = all_textures[i];
- total += (t.c2width * t.c2height * 4);
- }
- return total;
- };
- GLWrap_.prototype.textureCount = function ()
- {
- return all_textures.length;
- };
- GLWrap_.prototype.setRenderingToTexture = function (tex)
- {
- if (tex === this.renderToTex)
- return;
- ;
- var b = this.pushBatch();
- b.type = BATCH_RENDERTOTEXTURE;
- b.texParam = tex;
- this.renderToTex = tex;
- this.hasQuadBatchTop = false;
- this.hasPointBatchTop = false;
- };
- cr.GLWrap = GLWrap_;
- }());
- ;
- (function()
- {
- function window_innerWidth()
- {
- if (typeof jQuery !== "undefined")
- return jQuery(window).width();
- else
- return window.innerWidth;
- };
- function window_innerHeight()
- {
- if (typeof jQuery !== "undefined")
- return jQuery(window).height();
- else
- return window.innerHeight;
- };
- function Runtime(canvas)
- {
- if (!canvas || (!canvas.getContext && !canvas["dc"]))
- return;
- if (canvas["c2runtime"])
- return;
- else
- canvas["c2runtime"] = this;
- var self = this;
- this.isCrosswalk = /crosswalk/i.test(navigator.userAgent) || /xwalk/i.test(navigator.userAgent) || !!(typeof window["c2isCrosswalk"] !== "undefined" && window["c2isCrosswalk"]);
- this.isCordova = this.isCrosswalk || (typeof window["device"] !== "undefined" && (typeof window["device"]["cordova"] !== "undefined" || typeof window["device"]["phonegap"] !== "undefined")) || (typeof window["c2iscordova"] !== "undefined" && window["c2iscordova"]);
- this.isPhoneGap = this.isCordova;
- this.isDirectCanvas = !!canvas["dc"];
- this.isAppMobi = (typeof window["AppMobi"] !== "undefined" || this.isDirectCanvas);
- this.isCocoonJs = !!window["c2cocoonjs"];
- this.isEjecta = !!window["c2ejecta"];
- if (this.isCocoonJs)
- {
- CocoonJS["App"]["onSuspended"].addEventListener(function() {
- self["setSuspended"](true);
- });
- CocoonJS["App"]["onActivated"].addEventListener(function () {
- self["setSuspended"](false);
- });
- }
- if (this.isEjecta)
- {
- document.addEventListener("pagehide", function() {
- self["setSuspended"](true);
- });
- document.addEventListener("pageshow", function() {
- self["setSuspended"](false);
- });
- document.addEventListener("resize", function () {
- self["setSize"](window.innerWidth, window.innerHeight);
- });
- }
- this.isDomFree = (this.isDirectCanvas || this.isCocoonJs || this.isEjecta);
- this.isIE = /msie/i.test(navigator.userAgent) || /trident/i.test(navigator.userAgent) || /iemobile/i.test(navigator.userAgent) || /edge\//i.test(navigator.userAgent);
- this.isTizen = /tizen/i.test(navigator.userAgent);
- this.isAndroid = /android/i.test(navigator.userAgent) && !this.isTizen && !this.isIE; // IE mobile and Tizen masquerade as Android
- this.isiPhone = (/iphone/i.test(navigator.userAgent) || /ipod/i.test(navigator.userAgent)) && !this.isIE; // treat ipod as an iphone; IE mobile masquerades as iPhone
- this.isiPad = /ipad/i.test(navigator.userAgent);
- this.isiOS = this.isiPhone || this.isiPad || this.isEjecta;
- this.isiPhoneiOS6 = (this.isiPhone && /os\s6/i.test(navigator.userAgent));
- this.isChrome = (/chrome/i.test(navigator.userAgent) || /chromium/i.test(navigator.userAgent)) && !this.isIE; // note true on Chromium-based webview on Android 4.4+; IE 'Edge' mode also pretends to be Chrome
- this.isAmazonWebApp = /amazonwebappplatform/i.test(navigator.userAgent);
- this.isFirefox = /firefox/i.test(navigator.userAgent);
- this.isSafari = /safari/i.test(navigator.userAgent) && !this.isChrome && !this.isIE; // Chrome and IE Mobile masquerade as Safari
- this.isWindows = /windows/i.test(navigator.userAgent);
- this.isNWjs = (typeof window["c2nodewebkit"] !== "undefined" || typeof window["c2nwjs"] !== "undefined" || /nodewebkit/i.test(navigator.userAgent) || /nwjs/i.test(navigator.userAgent));
- this.isNodeWebkit = this.isNWjs; // old name for backwards compat
- this.isArcade = (typeof window["is_scirra_arcade"] !== "undefined");
- this.isWindows8App = !!(typeof window["c2isWindows8"] !== "undefined" && window["c2isWindows8"]);
- this.isWindows8Capable = !!(typeof window["c2isWindows8Capable"] !== "undefined" && window["c2isWindows8Capable"]);
- this.isWindowsPhone8 = !!(typeof window["c2isWindowsPhone8"] !== "undefined" && window["c2isWindowsPhone8"]);
- this.isWindowsPhone81 = !!(typeof window["c2isWindowsPhone81"] !== "undefined" && window["c2isWindowsPhone81"]);
- this.isWinJS = (this.isWindows8App || this.isWindows8Capable || this.isWindowsPhone81); // note not WP8.0
- this.isBlackberry10 = !!(typeof window["c2isBlackberry10"] !== "undefined" && window["c2isBlackberry10"]);
- this.isAndroidStockBrowser = (this.isAndroid && !this.isChrome && !this.isCrosswalk && !this.isFirefox && !this.isAmazonWebApp && !this.isDomFree);
- this.devicePixelRatio = 1;
- this.isMobile = (this.isCordova || this.isCrosswalk || this.isAppMobi || this.isCocoonJs || this.isAndroid || this.isiOS || this.isWindowsPhone8 || this.isWindowsPhone81 || this.isBlackberry10 || this.isTizen || this.isEjecta);
- if (!this.isMobile)
- {
- this.isMobile = /(blackberry|bb10|playbook|palm|symbian|nokia|windows\s+ce|phone|mobile|tablet|kindle|silk)/i.test(navigator.userAgent);
- }
- if (typeof cr_is_preview !== "undefined" && !this.isNWjs && (window.location.search === "?nw" || /nodewebkit/i.test(navigator.userAgent) || /nwjs/i.test(navigator.userAgent)))
- {
- this.isNWjs = true;
- }
- this.isDebug = (typeof cr_is_preview !== "undefined" && window.location.search.indexOf("debug") > -1);
- this.canvas = canvas;
- this.canvasdiv = document.getElementById("c2canvasdiv");
- this.gl = null;
- this.glwrap = null;
- this.glUnmaskedRenderer = "(unavailable)";
- this.ctx = null;
- this.fullscreenOldMarginCss = "";
- this.firstInFullscreen = false;
- this.oldWidth = 0; // for restoring non-fullscreen canvas after fullscreen
- this.oldHeight = 0;
- this.canvas.oncontextmenu = function (e) { if (e.preventDefault) e.preventDefault(); return false; };
- this.canvas.onselectstart = function (e) { if (e.preventDefault) e.preventDefault(); return false; };
- if (this.isDirectCanvas)
- window["c2runtime"] = this;
- if (this.isNWjs)
- {
- window["ondragover"] = function(e) { e.preventDefault(); return false; };
- window["ondrop"] = function(e) { e.preventDefault(); return false; };
- require("nw.gui")["App"]["clearCache"]();
- }
- if (this.isAndroidStockBrowser && typeof jQuery !== "undefined")
- {
- jQuery("canvas").parents("*").css("overflow", "visible");
- }
- this.width = canvas.width;
- this.height = canvas.height;
- this.draw_width = this.width;
- this.draw_height = this.height;
- this.cssWidth = this.width;
- this.cssHeight = this.height;
- this.lastWindowWidth = window.innerWidth;
- this.lastWindowHeight = window.innerHeight;
- this.forceCanvasAlpha = false; // allow plugins to force the canvas to display with alpha channel
- this.redraw = true;
- this.isSuspended = false;
- if (!Date.now) {
- Date.now = function now() {
- return +new Date();
- };
- }
- this.plugins = [];
- this.types = {};
- this.types_by_index = [];
- this.behaviors = [];
- this.layouts = {};
- this.layouts_by_index = [];
- this.eventsheets = {};
- this.eventsheets_by_index = [];
- this.wait_for_textures = []; // for blocking until textures loaded
- this.triggers_to_postinit = [];
- this.all_global_vars = [];
- this.all_local_vars = [];
- this.solidBehavior = null;
- this.jumpthruBehavior = null;
- this.shadowcasterBehavior = null;
- this.deathRow = {};
- this.hasPendingInstances = false; // true if anything exists in create row or death row
- this.isInClearDeathRow = false;
- this.isInOnDestroy = 0; // needs to support recursion so increments and decrements and is true if > 0
- this.isRunningEvents = false;
- this.createRow = [];
- this.isLoadingState = false;
- this.saveToSlot = "";
- this.loadFromSlot = "";
- this.loadFromJson = "";
- this.lastSaveJson = "";
- this.signalledContinuousPreview = false;
- this.suspendDrawing = false; // for hiding display until continuous preview loads
- this.dt = 0;
- this.dt1 = 0;
- this.logictime = 0; // used to calculate CPUUtilisation
- this.cpuutilisation = 0;
- this.timescale = 1.0;
- this.kahanTime = new cr.KahanAdder();
- this.wallTime = new cr.KahanAdder();
- this.last_tick_time = 0;
- this.fps = 0;
- this.last_fps_time = 0;
- this.tickcount = 0;
- this.execcount = 0;
- this.framecount = 0; // for fps
- this.objectcount = 0;
- this.changelayout = null;
- this.destroycallbacks = [];
- this.event_stack = [];
- this.event_stack_index = -1;
- this.localvar_stack = [[]];
- this.localvar_stack_index = 0;
- this.trigger_depth = 0; // recursion depth for triggers
- this.pushEventStack(null);
- this.loop_stack = [];
- this.loop_stack_index = -1;
- this.next_uid = 0;
- this.next_puid = 0; // permanent unique ids
- this.layout_first_tick = true;
- this.family_count = 0;
- this.suspend_events = [];
- this.raf_id = -1;
- this.timeout_id = -1;
- this.isloading = true;
- this.loadingprogress = 0;
- this.isNodeFullscreen = false;
- this.stackLocalCount = 0; // number of stack-based local vars for recursion
- this.audioInstance = null;
- this.had_a_click = false;
- this.isInUserInputEvent = false;
- this.objects_to_pretick = new cr.ObjectSet();
- this.objects_to_tick = new cr.ObjectSet();
- this.objects_to_tick2 = new cr.ObjectSet();
- this.registered_collisions = [];
- this.temp_poly = new cr.CollisionPoly([]);
- this.temp_poly2 = new cr.CollisionPoly([]);
- this.allGroups = []; // array of all event groups
- this.groups_by_name = {};
- this.cndsBySid = {};
- this.actsBySid = {};
- this.varsBySid = {};
- this.blocksBySid = {};
- this.running_layout = null; // currently running layout
- this.layer_canvas = null; // for layers "render-to-texture"
- this.layer_ctx = null;
- this.layer_tex = null;
- this.layout_tex = null;
- this.layout_canvas = null;
- this.layout_ctx = null;
- this.is_WebGL_context_lost = false;
- this.uses_background_blending = false; // if any shader uses background blending, so entire layout renders to texture
- this.fx_tex = [null, null];
- this.fullscreen_scaling = 0;
- this.files_subfolder = ""; // path with project files
- this.objectsByUid = {}; // maps every in-use UID (as a string) to its instance
- this.loaderlogo = null;
- this.snapshotCanvas = null;
- this.snapshotData = "";
- this.objectRefTable = [];
- this.requestProjectData();
- };
- Runtime.prototype.requestProjectData = function ()
- {
- var self = this;
- var xhr;
- if (this.isWindowsPhone8)
- xhr = new ActiveXObject("Microsoft.XMLHTTP");
- else
- xhr = new XMLHttpRequest();
- var datajs_filename = "data.js";
- if (this.isWindows8App || this.isWindowsPhone8 || this.isWindowsPhone81)
- datajs_filename = "data.json";
- xhr.open("GET", datajs_filename, true);
- var supportsJsonResponse = false;
- if (!this.isDomFree && ("response" in xhr) && ("responseType" in xhr))
- {
- try {
- xhr["responseType"] = "json";
- supportsJsonResponse = (xhr["responseType"] === "json");
- }
- catch (e) {
- supportsJsonResponse = false;
- }
- }
- if (!supportsJsonResponse && ("responseType" in xhr))
- {
- try {
- xhr["responseType"] = "text";
- }
- catch (e) {}
- }
- if ("overrideMimeType" in xhr)
- {
- try {
- xhr["overrideMimeType"]("application/json; charset=utf-8");
- }
- catch (e) {}
- }
- if (this.isWindowsPhone8)
- {
- xhr.onreadystatechange = function ()
- {
- if (xhr.readyState !== 4)
- return;
- self.loadProject(JSON.parse(xhr["responseText"]));
- };
- }
- else
- {
- xhr.onload = function ()
- {
- if (supportsJsonResponse)
- {
- self.loadProject(xhr["response"]); // already parsed by browser
- }
- else
- {
- if (self.isEjecta)
- {
- var str = xhr["responseText"];
- str = str.substr(str.indexOf("{")); // trim any BOM
- self.loadProject(JSON.parse(str));
- }
- else
- {
- self.loadProject(JSON.parse(xhr["responseText"])); // forced to sync parse JSON
- }
- }
- };
- xhr.onerror = function (e)
- {
- cr.logerror("Error requesting " + datajs_filename + ":");
- cr.logerror(e);
- };
- }
- xhr.send();
- };
- Runtime.prototype.initRendererAndLoader = function ()
- {
- var self = this;
- var i, len, j, lenj, k, lenk, t, s, l, y;
- this.isRetina = ((!this.isDomFree || this.isEjecta) && this.useHighDpi && !this.isAndroidStockBrowser);
- if (this.fullscreen_mode === 0 && this.isiOS)
- this.isRetina = false;
- this.devicePixelRatio = (this.isRetina ? (window["devicePixelRatio"] || window["webkitDevicePixelRatio"] || window["mozDevicePixelRatio"] || window["msDevicePixelRatio"] || 1) : 1);
- this.ClearDeathRow();
- var attribs;
- var alpha_canvas = !!(this.forceCanvasAlpha || (this.alphaBackground && !(this.isNWjs || this.isWinJS || this.isWindowsPhone8 || this.isCrosswalk || this.isCordova || this.isAmazonWebApp)));
- if (this.fullscreen_mode > 0)
- this["setSize"](window_innerWidth(), window_innerHeight(), true);
- try {
- if (this.enableWebGL && (this.isCocoonJs || this.isEjecta || !this.isDomFree))
- {
- attribs = {
- "alpha": alpha_canvas,
- "depth": false,
- "antialias": false,
- "failIfMajorPerformanceCaveat": true
- };
- this.gl = (this.canvas.getContext("webgl", attribs) || this.canvas.getContext("experimental-webgl", attribs));
- }
- }
- catch (e) {
- }
- if (this.gl)
- {
- var debug_ext = this.gl.getExtension("WEBGL_debug_renderer_info");
- if (debug_ext)
- {
- var unmasked_vendor = this.gl.getParameter(debug_ext.UNMASKED_VENDOR_WEBGL);
- var unmasked_renderer = this.gl.getParameter(debug_ext.UNMASKED_RENDERER_WEBGL);
- this.glUnmaskedRenderer = unmasked_renderer + " [" + unmasked_vendor + "]";
- ;
- }
- else
- {
- ;
- }
- if (!this.isDomFree)
- {
- this.overlay_canvas = document.createElement("canvas");
- jQuery(this.overlay_canvas).appendTo(this.canvas.parentNode);
- this.overlay_canvas.oncontextmenu = function (e) { return false; };
- this.overlay_canvas.onselectstart = function (e) { return false; };
- this.overlay_canvas.width = this.cssWidth;
- this.overlay_canvas.height = this.cssHeight;
- jQuery(this.overlay_canvas).css({"width": this.cssWidth + "px",
- "height": this.cssHeight + "px"});
- this.positionOverlayCanvas();
- this.overlay_ctx = this.overlay_canvas.getContext("2d");
- }
- this.glwrap = new cr.GLWrap(this.gl, this.isMobile);
- this.glwrap.setSize(this.canvas.width, this.canvas.height);
- this.glwrap.enable_mipmaps = (this.downscalingQuality !== 0);
- this.ctx = null;
- this.canvas.addEventListener("webglcontextlost", function (ev) {
- ev.preventDefault();
- self.onContextLost();
- cr.logexport("[Construct 2] WebGL context lost");
- window["cr_setSuspended"](true); // stop rendering
- }, false);
- this.canvas.addEventListener("webglcontextrestored", function (ev) {
- self.glwrap.initState();
- self.glwrap.setSize(self.glwrap.width, self.glwrap.height, true);
- self.layer_tex = null;
- self.layout_tex = null;
- self.fx_tex[0] = null;
- self.fx_tex[1] = null;
- self.onContextRestored();
- self.redraw = true;
- cr.logexport("[Construct 2] WebGL context restored");
- window["cr_setSuspended"](false); // resume rendering
- }, false);
- for (i = 0, len = this.types_by_index.length; i < len; i++)
- {
- t = this.types_by_index[i];
- for (j = 0, lenj = t.effect_types.length; j < lenj; j++)
- {
- s = t.effect_types[j];
- s.shaderindex = this.glwrap.getShaderIndex(s.id);
- this.uses_background_blending = this.uses_background_blending || this.glwrap.programUsesDest(s.shaderindex);
- }
- }
- for (i = 0, len = this.layouts_by_index.length; i < len; i++)
- {
- l = this.layouts_by_index[i];
- for (j = 0, lenj = l.effect_types.length; j < lenj; j++)
- {
- s = l.effect_types[j];
- s.shaderindex = this.glwrap.getShaderIndex(s.id);
- }
- for (j = 0, lenj = l.layers.length; j < lenj; j++)
- {
- y = l.layers[j];
- for (k = 0, lenk = y.effect_types.length; k < lenk; k++)
- {
- s = y.effect_types[k];
- s.shaderindex = this.glwrap.getShaderIndex(s.id);
- this.uses_background_blending = this.uses_background_blending || this.glwrap.programUsesDest(s.shaderindex);
- }
- }
- }
- }
- else
- {
- if (this.fullscreen_mode > 0 && this.isDirectCanvas)
- {
- ;
- this.canvas = null;
- document.oncontextmenu = function (e) { return false; };
- document.onselectstart = function (e) { return false; };
- this.ctx = AppMobi["canvas"]["getContext"]("2d");
- try {
- this.ctx["samplingMode"] = this.linearSampling ? "smooth" : "sharp";
- this.ctx["globalScale"] = 1;
- this.ctx["HTML5CompatibilityMode"] = true;
- this.ctx["imageSmoothingEnabled"] = this.linearSampling;
- } catch(e){}
- if (this.width !== 0 && this.height !== 0)
- {
- this.ctx.width = this.width;
- this.ctx.height = this.height;
- }
- }
- if (!this.ctx)
- {
- ;
- if (this.isCocoonJs)
- {
- attribs = {
- "antialias": !!this.linearSampling,
- "alpha": alpha_canvas
- };
- this.ctx = this.canvas.getContext("2d", attribs);
- }
- else
- {
- attribs = {
- "alpha": alpha_canvas
- };
- this.ctx = this.canvas.getContext("2d", attribs);
- }
- this.ctx["webkitImageSmoothingEnabled"] = this.linearSampling;
- this.ctx["mozImageSmoothingEnabled"] = this.linearSampling;
- this.ctx["msImageSmoothingEnabled"] = this.linearSampling;
- this.ctx["imageSmoothingEnabled"] = this.linearSampling;
- }
- this.overlay_canvas = null;
- this.overlay_ctx = null;
- }
- this.tickFunc = function (timestamp) { self.tick(false, timestamp); };
- if (window != window.top && !this.isDomFree && !this.isWinJS && !this.isWindowsPhone8)
- {
- document.addEventListener("mousedown", function () {
- window.focus();
- }, true);
- document.addEventListener("touchstart", function () {
- window.focus();
- }, true);
- }
- if (typeof cr_is_preview !== "undefined")
- {
- if (this.isCocoonJs)
- console.log("[Construct 2] In preview-over-wifi via CocoonJS mode");
- if (window.location.search.indexOf("continuous") > -1)
- {
- cr.logexport("Reloading for continuous preview");
- this.loadFromSlot = "__c2_continuouspreview";
- this.suspendDrawing = true;
- }
- if (this.pauseOnBlur && !this.isMobile)
- {
- jQuery(window).focus(function ()
- {
- self["setSuspended"](false);
- });
- jQuery(window).blur(function ()
- {
- self["setSuspended"](true);
- });
- }
- }
- if (!this.isDomFree)
- {
- var unfocusFormControlFunc = function (e) {
- if (cr.isCanvasInputEvent(e) && document["activeElement"] && document["activeElement"] !== document.getElementsByTagName("body")[0] && document["activeElement"].blur)
- {
- try {
- document["activeElement"].blur();
- }
- catch (e) {}
- }
- }
- if (window.navigator["pointerEnabled"])
- {
- document.addEventListener("pointerdown", unfocusFormControlFunc);
- }
- else if (window.navigator["msPointerEnabled"])
- {
- document.addEventListener("MSPointerDown", unfocusFormControlFunc);
- }
- else
- {
- document.addEventListener("touchstart", unfocusFormControlFunc);
- }
- document.addEventListener("mousedown", unfocusFormControlFunc);
- }
- if (this.fullscreen_mode === 0 && this.isRetina && this.devicePixelRatio > 1)
- {
- this["setSize"](this.original_width, this.original_height, true);
- }
- this.tryLockOrientation();
- this.getready(); // determine things to preload
- this.go(); // run loading screen
- this.extra = {};
- cr.seal(this);
- };
- var webkitRepaintFlag = false;
- Runtime.prototype["setSize"] = function (w, h, force)
- {
- var offx = 0, offy = 0;
- var neww = 0, newh = 0, intscale = 0;
- var tryHideAddressBar = (this.isiPhoneiOS6 && this.isSafari && !navigator["standalone"] && !this.isDomFree && !this.isCordova);
- if (tryHideAddressBar)
- h += 60; // height of Safari iPhone iOS 6 address bar
- if (this.lastWindowWidth === w && this.lastWindowHeight === h && !force)
- return;
- this.lastWindowWidth = w;
- this.lastWindowHeight = h;
- var mode = this.fullscreen_mode;
- var orig_aspect, cur_aspect;
- var isfullscreen = (document["mozFullScreen"] || document["webkitIsFullScreen"] || !!document["msFullscreenElement"] || document["fullScreen"] || this.isNodeFullscreen) && !this.isCordova;
- if (!isfullscreen && this.fullscreen_mode === 0 && !force)
- return; // ignore size events when not fullscreen and not using a fullscreen-in-browser mode
- if (isfullscreen && this.fullscreen_scaling > 0)
- mode = this.fullscreen_scaling;
- var dpr = this.devicePixelRatio;
- if (mode >= 4)
- {
- orig_aspect = this.original_width / this.original_height;
- cur_aspect = w / h;
- if (cur_aspect > orig_aspect)
- {
- neww = h * orig_aspect;
- if (mode === 5) // integer scaling
- {
- intscale = (neww * dpr) / this.original_width;
- if (intscale > 1)
- intscale = Math.floor(intscale);
- else if (intscale < 1)
- intscale = 1 / Math.ceil(1 / intscale);
- neww = this.original_width * intscale / dpr;
- newh = this.original_height * intscale / dpr;
- offx = (w - neww) / 2;
- offy = (h - newh) / 2;
- w = neww;
- h = newh;
- }
- else
- {
- offx = (w - neww) / 2;
- w = neww;
- }
- }
- else
- {
- newh = w / orig_aspect;
- if (mode === 5) // integer scaling
- {
- intscale = (newh * dpr) / this.original_height;
- if (intscale > 1)
- intscale = Math.floor(intscale);
- else if (intscale < 1)
- intscale = 1 / Math.ceil(1 / intscale);
- neww = this.original_width * intscale / dpr;
- newh = this.original_height * intscale / dpr;
- offx = (w - neww) / 2;
- offy = (h - newh) / 2;
- w = neww;
- h = newh;
- }
- else
- {
- offy = (h - newh) / 2;
- h = newh;
- }
- }
- if (isfullscreen && !this.isNWjs)
- {
- offx = 0;
- offy = 0;
- }
- }
- else if (this.isNWjs && this.isNodeFullscreen && this.fullscreen_mode_set === 0)
- {
- offx = Math.floor((w - this.original_width) / 2);
- offy = Math.floor((h - this.original_height) / 2);
- w = this.original_width;
- h = this.original_height;
- }
- if (mode < 2)
- this.aspect_scale = dpr;
- if (this.isRetina && this.isiPad && dpr > 1) // don't apply to iPad 1-2
- {
- if (w >= 1024)
- w = 1023; // 2046 retina pixels
- if (h >= 1024)
- h = 1023;
- }
- this.cssWidth = Math.round(w);
- this.cssHeight = Math.round(h);
- this.width = Math.round(w * dpr);
- this.height = Math.round(h * dpr);
- this.redraw = true;
- if (this.wantFullscreenScalingQuality)
- {
- this.draw_width = this.width;
- this.draw_height = this.height;
- this.fullscreenScalingQuality = true;
- }
- else
- {
- if ((this.width < this.original_width && this.height < this.original_height) || mode === 1)
- {
- this.draw_width = this.width;
- this.draw_height = this.height;
- this.fullscreenScalingQuality = true;
- }
- else
- {
- this.draw_width = this.original_width;
- this.draw_height = this.original_height;
- this.fullscreenScalingQuality = false;
- /*var orig_aspect = this.original_width / this.original_height;
- var cur_aspect = this.width / this.height;
- if ((this.fullscreen_mode !== 2 && cur_aspect > orig_aspect) || (this.fullscreen_mode === 2 && cur_aspect < orig_aspect))
- this.aspect_scale = this.height / this.original_height;
- else
- this.aspect_scale = this.width / this.original_width;*/
- if (mode === 2) // scale inner
- {
- orig_aspect = this.original_width / this.original_height;
- cur_aspect = this.lastWindowWidth / this.lastWindowHeight;
- if (cur_aspect < orig_aspect)
- this.draw_width = this.draw_height * cur_aspect;
- else if (cur_aspect > orig_aspect)
- this.draw_height = this.draw_width / cur_aspect;
- }
- else if (mode === 3)
- {
- orig_aspect = this.original_width / this.original_height;
- cur_aspect = this.lastWindowWidth / this.lastWindowHeight;
- if (cur_aspect > orig_aspect)
- this.draw_width = this.draw_height * cur_aspect;
- else if (cur_aspect < orig_aspect)
- this.draw_height = this.draw_width / cur_aspect;
- }
- }
- }
- if (this.canvasdiv && !this.isDomFree)
- {
- jQuery(this.canvasdiv).css({"width": Math.round(w) + "px",
- "height": Math.round(h) + "px",
- "margin-left": Math.floor(offx) + "px",
- "margin-top": Math.floor(offy) + "px"});
- if (typeof cr_is_preview !== "undefined")
- {
- jQuery("#borderwrap").css({"width": Math.round(w) + "px",
- "height": Math.round(h) + "px"});
- }
- }
- if (this.canvas)
- {
- this.canvas.width = Math.round(w * dpr);
- this.canvas.height = Math.round(h * dpr);
- if (this.isEjecta)
- {
- this.canvas.style.left = Math.floor(offx) + "px";
- this.canvas.style.top = Math.floor(offy) + "px";
- this.canvas.style.width = Math.round(w) + "px";
- this.canvas.style.height = Math.round(h) + "px";
- }
- else if (this.isRetina && !this.isDomFree)
- {
- this.canvas.style.width = Math.round(w) + "px";
- this.canvas.style.height = Math.round(h) + "px";
- }
- }
- if (this.overlay_canvas)
- {
- this.overlay_canvas.width = Math.round(w);
- this.overlay_canvas.height = Math.round(h);
- this.overlay_canvas.style.width = Math.round(w) + "px";
- this.overlay_canvas.style.height = Math.round(h) + "px";
- }
- if (this.glwrap)
- {
- this.glwrap.setSize(Math.round(w * dpr), Math.round(h * dpr));
- }
- if (this.isDirectCanvas && this.ctx)
- {
- this.ctx.width = Math.round(w);
- this.ctx.height = Math.round(h);
- }
- if (this.ctx)
- {
- this.ctx["webkitImageSmoothingEnabled"] = this.linearSampling;
- this.ctx["mozImageSmoothingEnabled"] = this.linearSampling;
- this.ctx["msImageSmoothingEnabled"] = this.linearSampling;
- this.ctx["imageSmoothingEnabled"] = this.linearSampling;
- }
- this.tryLockOrientation();
- if (!this.isDomFree && (tryHideAddressBar || this.isiPhone))
- {
- window.setTimeout(function () {
- window.scrollTo(0, 1);
- }, 100);
- }
- };
- Runtime.prototype.tryLockOrientation = function ()
- {
- if (!this.autoLockOrientation || this.orientations === 0)
- return;
- var orientation = "portrait";
- if (this.orientations === 2)
- orientation = "landscape";
- if (screen["orientation"] && screen["orientation"]["lock"])
- screen["orientation"]["lock"](orientation);
- else if (screen["lockOrientation"])
- screen["lockOrientation"](orientation);
- else if (screen["webkitLockOrientation"])
- screen["webkitLockOrientation"](orientation);
- else if (screen["mozLockOrientation"])
- screen["mozLockOrientation"](orientation);
- else if (screen["msLockOrientation"])
- screen["msLockOrientation"](orientation);
- };
- Runtime.prototype.onContextLost = function ()
- {
- this.glwrap.contextLost();
- this.is_WebGL_context_lost = true;
- var i, len, t;
- for (i = 0, len = this.types_by_index.length; i < len; i++)
- {
- t = this.types_by_index[i];
- if (t.onLostWebGLContext)
- t.onLostWebGLContext();
- }
- };
- Runtime.prototype.onContextRestored = function ()
- {
- this.is_WebGL_context_lost = false;
- var i, len, t;
- for (i = 0, len = this.types_by_index.length; i < len; i++)
- {
- t = this.types_by_index[i];
- if (t.onRestoreWebGLContext)
- t.onRestoreWebGLContext();
- }
- };
- Runtime.prototype.positionOverlayCanvas = function()
- {
- if (this.isDomFree)
- return;
- var isfullscreen = (document["mozFullScreen"] || document["webkitIsFullScreen"] || document["fullScreen"] || !!document["msFullscreenElement"] || this.isNodeFullscreen) && !this.isCordova;
- var overlay_position = isfullscreen ? jQuery(this.canvas).offset() : jQuery(this.canvas).position();
- overlay_position.position = "absolute";
- jQuery(this.overlay_canvas).css(overlay_position);
- };
- var caf = window["cancelAnimationFrame"] ||
- window["mozCancelAnimationFrame"] ||
- window["webkitCancelAnimationFrame"] ||
- window["msCancelAnimationFrame"] ||
- window["oCancelAnimationFrame"];
- Runtime.prototype["setSuspended"] = function (s)
- {
- var i, len;
- if (s && !this.isSuspended)
- {
- cr.logexport("[Construct 2] Suspending");
- this.isSuspended = true; // next tick will be last
- if (this.raf_id !== -1 && caf) // note: CocoonJS does not implement cancelAnimationFrame
- caf(this.raf_id);
- if (this.timeout_id !== -1)
- clearTimeout(this.timeout_id);
- for (i = 0, len = this.suspend_events.length; i < len; i++)
- this.suspend_events[i](true);
- }
- else if (!s && this.isSuspended)
- {
- cr.logexport("[Construct 2] Resuming");
- this.isSuspended = false;
- this.last_tick_time = cr.performance_now(); // ensure first tick is a zero-dt one
- this.last_fps_time = cr.performance_now(); // reset FPS counter
- this.framecount = 0;
- this.logictime = 0;
- for (i = 0, len = this.suspend_events.length; i < len; i++)
- this.suspend_events[i](false);
- this.tick(false); // kick off runtime again
- }
- };
- Runtime.prototype.addSuspendCallback = function (f)
- {
- this.suspend_events.push(f);
- };
- Runtime.prototype.GetObjectReference = function (i)
- {
- ;
- return this.objectRefTable[i];
- };
- Runtime.prototype.loadProject = function (data_response)
- {
- ;
- if (!data_response || !data_response["project"])
- cr.logerror("Project model unavailable");
- var pm = data_response["project"];
- this.name = pm[0];
- this.first_layout = pm[1];
- this.fullscreen_mode = pm[12]; // 0 = off, 1 = crop, 2 = scale inner, 3 = scale outer, 4 = letterbox scale, 5 = integer letterbox scale
- this.fullscreen_mode_set = pm[12];
- this.original_width = pm[10];
- this.original_height = pm[11];
- this.parallax_x_origin = this.original_width / 2;
- this.parallax_y_origin = this.original_height / 2;
- if (this.isDomFree && !this.isEjecta && (pm[12] >= 4 || pm[12] === 0))
- {
- cr.logexport("[Construct 2] Letterbox scale fullscreen modes are not supported on this platform - falling back to 'Scale outer'");
- this.fullscreen_mode = 3;
- this.fullscreen_mode_set = 3;
- }
- this.uses_loader_layout = pm[18];
- this.loaderstyle = pm[19];
- if (this.loaderstyle === 0)
- {
- this.loaderlogo = new Image();
- this.loaderlogo.crossOrigin = "anonymous";
- this.loaderlogo.src = "loading-logo.png";
- }
- this.next_uid = pm[21];
- this.objectRefTable = cr.getObjectRefTable();
- this.system = new cr.system_object(this);
- var i, len, j, lenj, k, lenk, idstr, m, b, t, f, p;
- var plugin, plugin_ctor;
- for (i = 0, len = pm[2].length; i < len; i++)
- {
- m = pm[2][i];
- p = this.GetObjectReference(m[0]);
- ;
- cr.add_common_aces(m, p.prototype);
- plugin = new p(this);
- plugin.singleglobal = m[1];
- plugin.is_world = m[2];
- plugin.must_predraw = m[9];
- if (plugin.onCreate)
- plugin.onCreate(); // opportunity to override default ACEs
- cr.seal(plugin);
- this.plugins.push(plugin);
- }
- this.objectRefTable = cr.getObjectRefTable();
- for (i = 0, len = pm[3].length; i < len; i++)
- {
- m = pm[3][i];
- plugin_ctor = this.GetObjectReference(m[1]);
- ;
- plugin = null;
- for (j = 0, lenj = this.plugins.length; j < lenj; j++)
- {
- if (this.plugins[j] instanceof plugin_ctor)
- {
- plugin = this.plugins[j];
- break;
- }
- }
- ;
- ;
- var type_inst = new plugin.Type(plugin);
- ;
- type_inst.name = m[0];
- type_inst.is_family = m[2];
- type_inst.instvar_sids = m[3].slice(0);
- type_inst.vars_count = m[3].length;
- type_inst.behs_count = m[4];
- type_inst.fx_count = m[5];
- type_inst.sid = m[11];
- if (type_inst.is_family)
- {
- type_inst.members = []; // types in this family
- type_inst.family_index = this.family_count++;
- type_inst.families = null;
- }
- else
- {
- type_inst.members = null;
- type_inst.family_index = -1;
- type_inst.families = []; // families this type belongs to
- }
- type_inst.family_var_map = null;
- type_inst.family_beh_map = null;
- type_inst.family_fx_map = null;
- type_inst.is_contained = false;
- type_inst.container = null;
- if (m[6])
- {
- type_inst.texture_file = m[6][0];
- type_inst.texture_filesize = m[6][1];
- type_inst.texture_pixelformat = m[6][2];
- }
- else
- {
- type_inst.texture_file = null;
- type_inst.texture_filesize = 0;
- type_inst.texture_pixelformat = 0; // rgba8
- }
- if (m[7])
- {
- type_inst.animations = m[7];
- }
- else
- {
- type_inst.animations = null;
- }
- type_inst.index = i; // save index in to types array in type
- type_inst.instances = []; // all instances of this type
- type_inst.deadCache = []; // destroyed instances to recycle next create
- type_inst.solstack = [new cr.selection(type_inst)]; // initialise SOL stack with one empty SOL
- type_inst.cur_sol = 0;
- type_inst.default_instance = null;
- type_inst.default_layerindex = 0;
- type_inst.stale_iids = true;
- type_inst.updateIIDs = cr.type_updateIIDs;
- type_inst.getFirstPicked = cr.type_getFirstPicked;
- type_inst.getPairedInstance = cr.type_getPairedInstance;
- type_inst.getCurrentSol = cr.type_getCurrentSol;
- type_inst.pushCleanSol = cr.type_pushCleanSol;
- type_inst.pushCopySol = cr.type_pushCopySol;
- type_inst.popSol = cr.type_popSol;
- type_inst.getBehaviorByName = cr.type_getBehaviorByName;
- type_inst.getBehaviorIndexByName = cr.type_getBehaviorIndexByName;
- type_inst.getEffectIndexByName = cr.type_getEffectIndexByName;
- type_inst.applySolToContainer = cr.type_applySolToContainer;
- type_inst.getInstanceByIID = cr.type_getInstanceByIID;
- type_inst.collision_grid = new cr.SparseGrid(this.original_width, this.original_height);
- type_inst.any_cell_changed = true;
- type_inst.any_instance_parallaxed = false;
- type_inst.extra = {};
- type_inst.toString = cr.type_toString;
- type_inst.behaviors = [];
- for (j = 0, lenj = m[8].length; j < lenj; j++)
- {
- b = m[8][j];
- var behavior_ctor = this.GetObjectReference(b[1]);
- var behavior_plugin = null;
- for (k = 0, lenk = this.behaviors.length; k < lenk; k++)
- {
- if (this.behaviors[k] instanceof behavior_ctor)
- {
- behavior_plugin = this.behaviors[k];
- break;
- }
- }
- if (!behavior_plugin)
- {
- behavior_plugin = new behavior_ctor(this);
- behavior_plugin.my_types = []; // types using this behavior
- behavior_plugin.my_instances = new cr.ObjectSet(); // instances of this behavior
- if (behavior_plugin.onCreate)
- behavior_plugin.onCreate();
- cr.seal(behavior_plugin);
- this.behaviors.push(behavior_plugin);
- if (cr.behaviors.solid && behavior_plugin instanceof cr.behaviors.solid)
- this.solidBehavior = behavior_plugin;
- if (cr.behaviors.jumpthru && behavior_plugin instanceof cr.behaviors.jumpthru)
- this.jumpthruBehavior = behavior_plugin;
- if (cr.behaviors.shadowcaster && behavior_plugin instanceof cr.behaviors.shadowcaster)
- this.shadowcasterBehavior = behavior_plugin;
- }
- if (behavior_plugin.my_types.indexOf(type_inst) === -1)
- behavior_plugin.my_types.push(type_inst);
- var behavior_type = new behavior_plugin.Type(behavior_plugin, type_inst);
- behavior_type.name = b[0];
- behavior_type.sid = b[2];
- behavior_type.onCreate();
- cr.seal(behavior_type);
- type_inst.behaviors.push(behavior_type);
- }
- type_inst.global = m[9];
- type_inst.isOnLoaderLayout = m[10];
- type_inst.effect_types = [];
- for (j = 0, lenj = m[12].length; j < lenj; j++)
- {
- type_inst.effect_types.push({
- id: m[12][j][0],
- name: m[12][j][1],
- shaderindex: -1,
- active: true,
- index: j
- });
- }
- type_inst.tile_poly_data = m[13];
- if (!this.uses_loader_layout || type_inst.is_family || type_inst.isOnLoaderLayout || !plugin.is_world)
- {
- type_inst.onCreate();
- cr.seal(type_inst);
- }
- if (type_inst.name)
- this.types[type_inst.name] = type_inst;
- this.types_by_index.push(type_inst);
- if (plugin.singleglobal)
- {
- var instance = new plugin.Instance(type_inst);
- instance.uid = this.next_uid++;
- instance.puid = this.next_puid++;
- instance.iid = 0;
- instance.get_iid = cr.inst_get_iid;
- instance.toString = cr.inst_toString;
- instance.properties = m[14];
- instance.onCreate();
- cr.seal(instance);
- type_inst.instances.push(instance);
- this.objectsByUid[instance.uid.toString()] = instance;
- }
- }
- for (i = 0, len = pm[4].length; i < len; i++)
- {
- var familydata = pm[4][i];
- var familytype = this.types_by_index[familydata[0]];
- var familymember;
- for (j = 1, lenj = familydata.length; j < lenj; j++)
- {
- familymember = this.types_by_index[familydata[j]];
- familymember.families.push(familytype);
- familytype.members.push(familymember);
- }
- }
- for (i = 0, len = pm[27].length; i < len; i++)
- {
- var containerdata = pm[27][i];
- var containertypes = [];
- for (j = 0, lenj = containerdata.length; j < lenj; j++)
- containertypes.push(this.types_by_index[containerdata[j]]);
- for (j = 0, lenj = containertypes.length; j < lenj; j++)
- {
- containertypes[j].is_contained = true;
- containertypes[j].container = containertypes;
- }
- }
- if (this.family_count > 0)
- {
- for (i = 0, len = this.types_by_index.length; i < len; i++)
- {
- t = this.types_by_index[i];
- if (t.is_family || !t.families.length)
- continue;
- t.family_var_map = new Array(this.family_count);
- t.family_beh_map = new Array(this.family_count);
- t.family_fx_map = new Array(this.family_count);
- var all_fx = [];
- var varsum = 0;
- var behsum = 0;
- var fxsum = 0;
- for (j = 0, lenj = t.families.length; j < lenj; j++)
- {
- f = t.families[j];
- t.family_var_map[f.family_index] = varsum;
- varsum += f.vars_count;
- t.family_beh_map[f.family_index] = behsum;
- behsum += f.behs_count;
- t.family_fx_map[f.family_index] = fxsum;
- fxsum += f.fx_count;
- for (k = 0, lenk = f.effect_types.length; k < lenk; k++)
- all_fx.push(cr.shallowCopy({}, f.effect_types[k]));
- }
- t.effect_types = all_fx.concat(t.effect_types);
- for (j = 0, lenj = t.effect_types.length; j < lenj; j++)
- t.effect_types[j].index = j;
- }
- }
- for (i = 0, len = pm[5].length; i < len; i++)
- {
- m = pm[5][i];
- var layout = new cr.layout(this, m);
- cr.seal(layout);
- this.layouts[layout.name] = layout;
- this.layouts_by_index.push(layout);
- }
- for (i = 0, len = pm[6].length; i < len; i++)
- {
- m = pm[6][i];
- var sheet = new cr.eventsheet(this, m);
- cr.seal(sheet);
- this.eventsheets[sheet.name] = sheet;
- this.eventsheets_by_index.push(sheet);
- }
- for (i = 0, len = this.eventsheets_by_index.length; i < len; i++)
- this.eventsheets_by_index[i].postInit();
- for (i = 0, len = this.eventsheets_by_index.length; i < len; i++)
- this.eventsheets_by_index[i].updateDeepIncludes();
- for (i = 0, len = this.triggers_to_postinit.length; i < len; i++)
- this.triggers_to_postinit[i].postInit();
- this.triggers_to_postinit.length = 0;
- this.audio_to_preload = pm[7];
- this.files_subfolder = pm[8];
- this.pixel_rounding = pm[9];
- this.aspect_scale = 1.0;
- this.enableWebGL = pm[13];
- this.linearSampling = pm[14];
- this.alphaBackground = pm[15];
- this.versionstr = pm[16];
- this.useHighDpi = pm[17];
- this.orientations = pm[20]; // 0 = any, 1 = portrait, 2 = landscape
- this.autoLockOrientation = (this.orientations > 0);
- this.pauseOnBlur = pm[22];
- this.wantFullscreenScalingQuality = pm[23]; // false = low quality, true = high quality
- this.fullscreenScalingQuality = this.wantFullscreenScalingQuality;
- this.downscalingQuality = pm[24]; // 0 = low (mips off), 1 = medium (mips on, dense spritesheet), 2 = high (mips on, sparse spritesheet)
- this.preloadSounds = pm[25]; // 0 = no, 1 = yes
- this.projectName = pm[26];
- this.start_time = Date.now();
- this.objectRefTable.length = 0;
- this.initRendererAndLoader();
- };
- var anyImageHadError = false;
- Runtime.prototype.waitForImageLoad = function (img_, src_)
- {
- img_["cocoonLazyLoad"] = true;
- img_.onerror = function (e)
- {
- img_.c2error = true;
- anyImageHadError = true;
- if (console && console.error)
- console.error("Error loading image '" + img_.src + "': ", e);
- };
- if (this.isEjecta)
- {
- img_.src = src_;
- }
- else if (!img_.src)
- {
- if (typeof XAPKReader !== "undefined")
- {
- XAPKReader.get(src_, function (expanded_url)
- {
- img_.src = expanded_url;
- }, function (e)
- {
- img_.c2error = true;
- anyImageHadError = true;
- if (console && console.error)
- console.error("Error extracting image '" + src_ + "' from expansion file: ", e);
- });
- }
- else
- {
- img_.crossOrigin = "anonymous"; // required for Arcade sandbox compatibility
- img_.src = src_;
- }
- }
- this.wait_for_textures.push(img_);
- };
- Runtime.prototype.findWaitingTexture = function (src_)
- {
- var i, len;
- for (i = 0, len = this.wait_for_textures.length; i < len; i++)
- {
- if (this.wait_for_textures[i].cr_src === src_)
- return this.wait_for_textures[i];
- }
- return null;
- };
- var audio_preload_totalsize = 0;
- var audio_preload_started = false;
- Runtime.prototype.getready = function ()
- {
- if (!this.audioInstance)
- return;
- audio_preload_totalsize = this.audioInstance.setPreloadList(this.audio_to_preload);
- };
- Runtime.prototype.areAllTexturesAndSoundsLoaded = function ()
- {
- var totalsize = audio_preload_totalsize;
- var completedsize = 0;
- var audiocompletedsize = 0;
- var ret = true;
- var i, len, img;
- for (i = 0, len = this.wait_for_textures.length; i < len; i++)
- {
- img = this.wait_for_textures[i];
- var filesize = img.cr_filesize;
- if (!filesize || filesize <= 0)
- filesize = 50000;
- totalsize += filesize;
- if (!!img.src && (img.complete || img["loaded"]) && !img.c2error)
- completedsize += filesize;
- else
- ret = false; // not all textures loaded
- }
- if (ret && this.preloadSounds && this.audioInstance)
- {
- if (!audio_preload_started)
- {
- this.audioInstance.startPreloads();
- audio_preload_started = true;
- }
- audiocompletedsize = this.audioInstance.getPreloadedSize();
- completedsize += audiocompletedsize;
- if (audiocompletedsize < audio_preload_totalsize)
- ret = false; // not done yet
- }
- if (totalsize == 0)
- this.progress = 0;
- else
- this.progress = (completedsize / totalsize);
- return ret;
- };
- Runtime.prototype.go = function ()
- {
- if (!this.ctx && !this.glwrap)
- return;
- var ctx = this.ctx || this.overlay_ctx;
- if (this.overlay_canvas)
- this.positionOverlayCanvas();
- this.progress = 0;
- this.last_progress = -1;
- if (this.areAllTexturesAndSoundsLoaded())
- this.go_loading_finished();
- else
- {
- var ms_elapsed = Date.now() - this.start_time;
- if (ctx)
- {
- var overlay_width = this.width;
- var overlay_height = this.height;
- var multiplier = this.devicePixelRatio;
- if (this.overlay_canvas)
- {
- overlay_width = this.cssWidth;
- overlay_height = this.cssHeight;
- multiplier = 1;
- }
- if (this.loaderstyle !== 3 && (this.isCocoonJs || (ms_elapsed >= 500 && this.last_progress != this.progress)))
- {
- ctx.clearRect(0, 0, overlay_width, overlay_height);
- var mx = overlay_width / 2;
- var my = overlay_height / 2;
- var haslogo = (this.loaderstyle === 0 && this.loaderlogo.complete);
- var hlw = 40 * multiplier;
- var hlh = 0;
- var logowidth = 80 * multiplier;
- var logoheight;
- if (haslogo)
- {
- logowidth = this.loaderlogo.width * multiplier;
- logoheight = this.loaderlogo.height * multiplier;
- hlw = logowidth / 2;
- hlh = logoheight / 2;
- ctx.drawImage(this.loaderlogo, cr.floor(mx - hlw), cr.floor(my - hlh), logowidth, logoheight);
- }
- if (this.loaderstyle <= 1)
- {
- my += hlh + (haslogo ? 12 * multiplier : 0);
- mx -= hlw;
- mx = cr.floor(mx) + 0.5;
- my = cr.floor(my) + 0.5;
- ctx.fillStyle = anyImageHadError ? "red" : "DodgerBlue";
- ctx.fillRect(mx, my, Math.floor(logowidth * this.progress), 6 * multiplier);
- ctx.strokeStyle = "black";
- ctx.strokeRect(mx, my, logowidth, 6 * multiplier);
- ctx.strokeStyle = "white";
- ctx.strokeRect(mx - 1 * multiplier, my - 1 * multiplier, logowidth + 2 * multiplier, 8 * multiplier);
- }
- else if (this.loaderstyle === 2)
- {
- ctx.font = (this.isEjecta ? "12pt ArialMT" : "12pt Arial");
- ctx.fillStyle = anyImageHadError ? "#f00" : "#999";
- ctx.textBaseLine = "middle";
- var percent_text = Math.round(this.progress * 100) + "%";
- var text_dim = ctx.measureText ? ctx.measureText(percent_text) : null;
- var text_width = text_dim ? text_dim.width : 0;
- ctx.fillText(percent_text, mx - (text_width / 2), my);
- }
- }
- this.last_progress = this.progress;
- }
- setTimeout((function (self) { return function () { self.go(); }; })(this), (this.isCocoonJs ? 10 : 100));
- }
- };
- Runtime.prototype.go_loading_finished = function ()
- {
- if (this.overlay_canvas)
- {
- this.canvas.parentNode.removeChild(this.overlay_canvas);
- this.overlay_ctx = null;
- this.overlay_canvas = null;
- }
- this.start_time = Date.now();
- this.last_fps_time = cr.performance_now(); // for counting framerate
- var i, len, t;
- if (this.uses_loader_layout)
- {
- for (i = 0, len = this.types_by_index.length; i < len; i++)
- {
- t = this.types_by_index[i];
- if (!t.is_family && !t.isOnLoaderLayout && t.plugin.is_world)
- {
- t.onCreate();
- cr.seal(t);
- }
- }
- }
- else
- this.isloading = false;
- for (i = 0, len = this.layouts_by_index.length; i < len; i++)
- {
- this.layouts_by_index[i].createGlobalNonWorlds();
- }
- if (this.fullscreen_mode >= 2)
- {
- var orig_aspect = this.original_width / this.original_height;
- var cur_aspect = this.width / this.height;
- if ((this.fullscreen_mode !== 2 && cur_aspect > orig_aspect) || (this.fullscreen_mode === 2 && cur_aspect < orig_aspect))
- this.aspect_scale = this.height / this.original_height;
- else
- this.aspect_scale = this.width / this.original_width;
- }
- if (this.first_layout)
- this.layouts[this.first_layout].startRunning();
- else
- this.layouts_by_index[0].startRunning();
- ;
- if (!this.uses_loader_layout)
- {
- this.loadingprogress = 1;
- this.trigger(cr.system_object.prototype.cnds.OnLoadFinished, null);
- }
- if (navigator["splashscreen"] && navigator["splashscreen"]["hide"])
- navigator["splashscreen"]["hide"]();
- for (i = 0, len = this.types_by_index.length; i < len; i++)
- {
- t = this.types_by_index[i];
- if (t.onAppBegin)
- t.onAppBegin();
- }
- if (document["hidden"] || document["webkitHidden"] || document["mozHidden"] || document["msHidden"])
- {
- window["cr_setSuspended"](true); // stop rendering
- }
- else
- {
- this.tick(false);
- }
- if (this.isDirectCanvas)
- AppMobi["webview"]["execute"]("onGameReady();");
- };
- var raf = window["requestAnimationFrame"] ||
- window["mozRequestAnimationFrame"] ||
- window["webkitRequestAnimationFrame"] ||
- window["msRequestAnimationFrame"] ||
- window["oRequestAnimationFrame"];
- Runtime.prototype.tick = function (background_wake, timestamp, debug_step)
- {
- if (!this.running_layout)
- return;
- var nowtime = cr.performance_now();
- var logic_start = nowtime;
- if (!debug_step && this.isSuspended && !background_wake)
- return;
- if (!background_wake)
- {
- if (raf)
- this.raf_id = raf(this.tickFunc);
- else
- {
- this.timeout_id = setTimeout(this.tickFunc, this.isMobile ? 1 : 16);
- }
- }
- var raf_time = timestamp || nowtime;
- var fsmode = this.fullscreen_mode;
- var isfullscreen = (document["mozFullScreen"] || document["webkitIsFullScreen"] || document["fullScreen"] || !!document["msFullscreenElement"]) && !this.isCordova;
- if ((isfullscreen || this.isNodeFullscreen) && this.fullscreen_scaling > 0)
- fsmode = this.fullscreen_scaling;
- if (fsmode > 0 && (!this.isiOS || window.self !== window.top))
- {
- var curwidth = window.innerWidth;
- var curheight = window.innerHeight;
- if (this.lastWindowWidth !== curwidth || this.lastWindowHeight !== curheight)
- {
- this["setSize"](window_innerWidth(), window_innerHeight());
- }
- }
- if (!this.isDomFree)
- {
- if (isfullscreen)
- {
- if (!this.firstInFullscreen)
- {
- this.fullscreenOldMarginCss = jQuery(this.canvas).css("margin") || "0";
- this.firstInFullscreen = true;
- }
- if (!this.isChrome && !this.isNWjs)
- {
- jQuery(this.canvas).css({
- "margin-left": "" + Math.floor((screen.width - (this.width / this.devicePixelRatio)) / 2) + "px",
- "margin-top": "" + Math.floor((screen.height - (this.height / this.devicePixelRatio)) / 2) + "px"
- });
- }
- }
- else
- {
- if (this.firstInFullscreen)
- {
- if (!this.isChrome && !this.isNWjs)
- {
- jQuery(this.canvas).css("margin", this.fullscreenOldMarginCss);
- }
- this.fullscreenOldMarginCss = "";
- this.firstInFullscreen = false;
- if (this.fullscreen_mode === 0)
- {
- this["setSize"](Math.round(this.oldWidth / this.devicePixelRatio), Math.round(this.oldHeight / this.devicePixelRatio), true);
- }
- }
- else
- {
- this.oldWidth = this.width;
- this.oldHeight = this.height;
- }
- }
- }
- if (this.isloading)
- {
- var done = this.areAllTexturesAndSoundsLoaded(); // updates this.progress
- this.loadingprogress = this.progress;
- if (done)
- {
- this.isloading = false;
- this.progress = 1;
- this.trigger(cr.system_object.prototype.cnds.OnLoadFinished, null);
- }
- }
- this.logic(raf_time);
- if ((this.redraw || this.isCocoonJs) && !this.is_WebGL_context_lost && !this.suspendDrawing && !background_wake)
- {
- this.redraw = false;
- if (this.glwrap)
- this.drawGL();
- else
- this.draw();
- if (this.snapshotCanvas)
- {
- if (this.canvas && this.canvas.toDataURL)
- {
- this.snapshotData = this.canvas.toDataURL(this.snapshotCanvas[0], this.snapshotCanvas[1]);
- if (window["cr_onSnapshot"])
- window["cr_onSnapshot"](this.snapshotData);
- this.trigger(cr.system_object.prototype.cnds.OnCanvasSnapshot, null);
- }
- this.snapshotCanvas = null;
- }
- }
- if (!this.hit_breakpoint)
- {
- this.tickcount++;
- this.execcount++;
- this.framecount++;
- }
- this.logictime += cr.performance_now() - logic_start;
- };
- Runtime.prototype.logic = function (cur_time)
- {
- var i, leni, j, lenj, k, lenk, type, inst, binst;
- if (cur_time - this.last_fps_time >= 1000) // every 1 second
- {
- this.last_fps_time += 1000;
- if (cur_time - this.last_fps_time >= 1000)
- this.last_fps_time = cur_time;
- this.fps = this.framecount;
- this.framecount = 0;
- this.cpuutilisation = this.logictime;
- this.logictime = 0;
- }
- if (this.last_tick_time !== 0)
- {
- var ms_diff = cur_time - this.last_tick_time;
- if (ms_diff < 0)
- ms_diff = 0;
- this.dt1 = ms_diff / 1000.0; // dt measured in seconds
- if (this.dt1 > 0.5)
- this.dt1 = 0;
- else if (this.dt1 > 0.1)
- this.dt1 = 0.1;
- }
- this.last_tick_time = cur_time;
- this.dt = this.dt1 * this.timescale;
- this.kahanTime.add(this.dt);
- this.wallTime.add(this.dt1);
- var isfullscreen = (document["mozFullScreen"] || document["webkitIsFullScreen"] || document["fullScreen"] || !!document["msFullscreenElement"] || this.isNodeFullscreen) && !this.isCordova;
- if (this.fullscreen_mode >= 2 /* scale */ || (isfullscreen && this.fullscreen_scaling > 0))
- {
- var orig_aspect = this.original_width / this.original_height;
- var cur_aspect = this.width / this.height;
- var mode = this.fullscreen_mode;
- if (isfullscreen && this.fullscreen_scaling > 0)
- mode = this.fullscreen_scaling;
- if ((mode !== 2 && cur_aspect > orig_aspect) || (mode === 2 && cur_aspect < orig_aspect))
- {
- this.aspect_scale = this.height / this.original_height;
- }
- else
- {
- this.aspect_scale = this.width / this.original_width;
- }
- if (this.running_layout)
- {
- this.running_layout.scrollToX(this.running_layout.scrollX);
- this.running_layout.scrollToY(this.running_layout.scrollY);
- }
- }
- else
- this.aspect_scale = (this.isRetina ? this.devicePixelRatio : 1);
- this.ClearDeathRow();
- this.isInOnDestroy++;
- this.system.runWaits(); // prevent instance list changing
- this.isInOnDestroy--;
- this.ClearDeathRow(); // allow instance list changing
- this.isInOnDestroy++;
- var tickarr = this.objects_to_pretick.valuesRef();
- for (i = 0, leni = tickarr.length; i < leni; i++)
- tickarr[i].pretick();
- for (i = 0, leni = this.types_by_index.length; i < leni; i++)
- {
- type = this.types_by_index[i];
- if (type.is_family || (!type.behaviors.length && !type.families.length))
- continue;
- for (j = 0, lenj = type.instances.length; j < lenj; j++)
- {
- inst = type.instances[j];
- for (k = 0, lenk = inst.behavior_insts.length; k < lenk; k++)
- {
- inst.behavior_insts[k].tick();
- }
- }
- }
- for (i = 0, leni = this.types_by_index.length; i < leni; i++)
- {
- type = this.types_by_index[i];
- if (type.is_family || (!type.behaviors.length && !type.families.length))
- continue; // type doesn't have any behaviors
- for (j = 0, lenj = type.instances.length; j < lenj; j++)
- {
- inst = type.instances[j];
- for (k = 0, lenk = inst.behavior_insts.length; k < lenk; k++)
- {
- binst = inst.behavior_insts[k];
- if (binst.posttick)
- binst.posttick();
- }
- }
- }
- tickarr = this.objects_to_tick.valuesRef();
- for (i = 0, leni = tickarr.length; i < leni; i++)
- tickarr[i].tick();
- this.isInOnDestroy--; // end preventing instance lists from being changed
- this.handleSaveLoad(); // save/load now if queued
- i = 0;
- while (this.changelayout && i++ < 10)
- {
- this.doChangeLayout(this.changelayout);
- }
- for (i = 0, leni = this.eventsheets_by_index.length; i < leni; i++)
- this.eventsheets_by_index[i].hasRun = false;
- if (this.running_layout.event_sheet)
- this.running_layout.event_sheet.run();
- this.registered_collisions.length = 0;
- this.layout_first_tick = false;
- this.isInOnDestroy++; // prevent instance lists from being changed
- for (i = 0, leni = this.types_by_index.length; i < leni; i++)
- {
- type = this.types_by_index[i];
- if (type.is_family || (!type.behaviors.length && !type.families.length))
- continue; // type doesn't have any behaviors
- for (j = 0, lenj = type.instances.length; j < lenj; j++)
- {
- var inst = type.instances[j];
- for (k = 0, lenk = inst.behavior_insts.length; k < lenk; k++)
- {
- binst = inst.behavior_insts[k];
- if (binst.tick2)
- binst.tick2();
- }
- }
- }
- tickarr = this.objects_to_tick2.valuesRef();
- for (i = 0, leni = tickarr.length; i < leni; i++)
- tickarr[i].tick2();
- this.isInOnDestroy--; // end preventing instance lists from being changed
- };
- Runtime.prototype.doChangeLayout = function (changeToLayout)
- {
- ;
- var prev_layout = this.running_layout;
- this.running_layout.stopRunning();
- var i, len, j, lenj, k, lenk, type, inst, binst;
- if (this.glwrap)
- {
- for (i = 0, len = this.types_by_index.length; i < len; i++)
- {
- type = this.types_by_index[i];
- if (type.is_family)
- continue;
- if (type.unloadTextures && (!type.global || type.instances.length === 0) && changeToLayout.initial_types.indexOf(type) === -1)
- {
- type.unloadTextures();
- }
- }
- }
- if (prev_layout == changeToLayout)
- this.system.waits.length = 0;
- this.registered_collisions.length = 0;
- changeToLayout.startRunning();
- for (i = 0, len = this.types_by_index.length; i < len; i++)
- {
- type = this.types_by_index[i];
- if (!type.global && !type.plugin.singleglobal)
- continue;
- for (j = 0, lenj = type.instances.length; j < lenj; j++)
- {
- inst = type.instances[j];
- if (inst.onLayoutChange)
- inst.onLayoutChange();
- if (inst.behavior_insts)
- {
- for (k = 0, lenk = inst.behavior_insts.length; k < lenk; k++)
- {
- binst = inst.behavior_insts[k];
- if (binst.onLayoutChange)
- binst.onLayoutChange();
- }
- }
- }
- }
- this.redraw = true;
- this.layout_first_tick = true;
- this.ClearDeathRow();
- };
- Runtime.prototype.pretickMe = function (inst)
- {
- this.objects_to_pretick.add(inst);
- };
- Runtime.prototype.unpretickMe = function (inst)
- {
- this.objects_to_pretick.remove(inst);
- };
- Runtime.prototype.tickMe = function (inst)
- {
- this.objects_to_tick.add(inst);
- };
- Runtime.prototype.untickMe = function (inst)
- {
- this.objects_to_tick.remove(inst);
- };
- Runtime.prototype.tick2Me = function (inst)
- {
- this.objects_to_tick2.add(inst);
- };
- Runtime.prototype.untick2Me = function (inst)
- {
- this.objects_to_tick2.remove(inst);
- };
- Runtime.prototype.getDt = function (inst)
- {
- if (!inst || inst.my_timescale === -1.0)
- return this.dt;
- return this.dt1 * inst.my_timescale;
- };
- Runtime.prototype.draw = function ()
- {
- this.running_layout.draw(this.ctx);
- if (this.isDirectCanvas)
- this.ctx["present"]();
- };
- Runtime.prototype.drawGL = function ()
- {
- this.running_layout.drawGL(this.glwrap);
- this.glwrap.present();
- };
- Runtime.prototype.addDestroyCallback = function (f)
- {
- if (f)
- this.destroycallbacks.push(f);
- };
- Runtime.prototype.removeDestroyCallback = function (f)
- {
- cr.arrayFindRemove(this.destroycallbacks, f);
- };
- Runtime.prototype.getObjectByUID = function (uid_)
- {
- ;
- var uidstr = uid_.toString();
- if (this.objectsByUid.hasOwnProperty(uidstr))
- return this.objectsByUid[uidstr];
- else
- return null;
- };
- var objectset_cache = [];
- function alloc_objectset()
- {
- if (objectset_cache.length)
- return objectset_cache.pop();
- else
- return new cr.ObjectSet();
- };
- function free_objectset(s)
- {
- s.clear();
- objectset_cache.push(s);
- };
- Runtime.prototype.DestroyInstance = function (inst)
- {
- var i, len;
- var type = inst.type;
- var typename = type.name;
- var has_typename = this.deathRow.hasOwnProperty(typename);
- var obj_set = null;
- if (has_typename)
- {
- obj_set = this.deathRow[typename];
- if (obj_set.contains(inst))
- return; // already had DestroyInstance called
- }
- else
- {
- obj_set = alloc_objectset();
- this.deathRow[typename] = obj_set;
- }
- obj_set.add(inst);
- this.hasPendingInstances = true;
- if (inst.is_contained)
- {
- for (i = 0, len = inst.siblings.length; i < len; i++)
- {
- this.DestroyInstance(inst.siblings[i]);
- }
- }
- if (this.isInClearDeathRow)
- obj_set.values_cache.push(inst);
- this.isInOnDestroy++; // support recursion
- this.trigger(Object.getPrototypeOf(inst.type.plugin).cnds.OnDestroyed, inst);
- this.isInOnDestroy--;
- };
- Runtime.prototype.ClearDeathRow = function ()
- {
- if (!this.hasPendingInstances)
- return;
- var inst, type, instances;
- var i, j, leni, lenj, obj_set;
- this.isInClearDeathRow = true;
- for (i = 0, leni = this.createRow.length; i < leni; ++i)
- {
- inst = this.createRow[i];
- type = inst.type;
- type.instances.push(inst);
- for (j = 0, lenj = type.families.length; j < lenj; ++j)
- {
- type.families[j].instances.push(inst);
- type.families[j].stale_iids = true;
- }
- }
- this.createRow.length = 0;
- this.IterateDeathRow(); // moved to separate function so for-in performance doesn't hobble entire function
- cr.wipe(this.deathRow); // all objectsets have already been recycled
- this.isInClearDeathRow = false;
- this.hasPendingInstances = false;
- };
- Runtime.prototype.IterateDeathRow = function ()
- {
- for (var p in this.deathRow)
- {
- if (this.deathRow.hasOwnProperty(p))
- {
- this.ClearDeathRowForType(this.deathRow[p]);
- }
- }
- };
- Runtime.prototype.ClearDeathRowForType = function (obj_set)
- {
- var arr = obj_set.valuesRef(); // get array of items from set
- ;
- var type = arr[0].type;
- ;
- ;
- var i, len, j, lenj, w, f, layer_instances, inst;
- cr.arrayRemoveAllFromObjectSet(type.instances, obj_set);
- type.stale_iids = true;
- if (type.instances.length === 0)
- type.any_instance_parallaxed = false;
- for (i = 0, len = type.families.length; i < len; ++i)
- {
- f = type.families[i];
- cr.arrayRemoveAllFromObjectSet(f.instances, obj_set);
- f.stale_iids = true;
- }
- for (i = 0, len = this.system.waits.length; i < len; ++i)
- {
- w = this.system.waits[i];
- if (w.sols.hasOwnProperty(type.index))
- cr.arrayRemoveAllFromObjectSet(w.sols[type.index].insts, obj_set);
- if (!type.is_family)
- {
- for (j = 0, lenj = type.families.length; j < lenj; ++j)
- {
- f = type.families[j];
- if (w.sols.hasOwnProperty(f.index))
- cr.arrayRemoveAllFromObjectSet(w.sols[f.index].insts, obj_set);
- }
- }
- }
- var first_layer = arr[0].layer;
- if (first_layer)
- {
- if (first_layer.useRenderCells)
- {
- layer_instances = first_layer.instances;
- for (i = 0, len = layer_instances.length; i < len; ++i)
- {
- inst = layer_instances[i];
- if (!obj_set.contains(inst))
- continue; // not destroying this instance
- inst.update_bbox();
- first_layer.render_grid.update(inst, inst.rendercells, null);
- inst.rendercells.set(0, 0, -1, -1);
- }
- }
- cr.arrayRemoveAllFromObjectSet(first_layer.instances, obj_set);
- first_layer.setZIndicesStaleFrom(0);
- }
- for (i = 0; i < arr.length; ++i) // check array length every time in case it changes
- {
- this.ClearDeathRowForSingleInstance(arr[i], type);
- }
- free_objectset(obj_set);
- this.redraw = true;
- };
- Runtime.prototype.ClearDeathRowForSingleInstance = function (inst, type)
- {
- var i, len, binst;
- for (i = 0, len = this.destroycallbacks.length; i < len; ++i)
- this.destroycallbacks[i](inst);
- if (inst.collcells)
- {
- type.collision_grid.update(inst, inst.collcells, null);
- }
- var layer = inst.layer;
- if (layer)
- {
- layer.removeFromInstanceList(inst, true); // remove from both instance list and render grid
- }
- if (inst.behavior_insts)
- {
- for (i = 0, len = inst.behavior_insts.length; i < len; ++i)
- {
- binst = inst.behavior_insts[i];
- if (binst.onDestroy)
- binst.onDestroy();
- binst.behavior.my_instances.remove(inst);
- }
- }
- this.objects_to_pretick.remove(inst);
- this.objects_to_tick.remove(inst);
- this.objects_to_tick2.remove(inst);
- if (inst.onDestroy)
- inst.onDestroy();
- if (this.objectsByUid.hasOwnProperty(inst.uid.toString()))
- delete this.objectsByUid[inst.uid.toString()];
- this.objectcount--;
- if (type.deadCache.length < 100)
- type.deadCache.push(inst);
- };
- Runtime.prototype.createInstance = function (type, layer, sx, sy)
- {
- if (type.is_family)
- {
- var i = cr.floor(Math.random() * type.members.length);
- return this.createInstance(type.members[i], layer, sx, sy);
- }
- if (!type.default_instance)
- {
- return null;
- }
- return this.createInstanceFromInit(type.default_instance, layer, false, sx, sy, false);
- };
- var all_behaviors = [];
- Runtime.prototype.createInstanceFromInit = function (initial_inst, layer, is_startup_instance, sx, sy, skip_siblings)
- {
- var i, len, j, lenj, p, effect_fallback, x, y;
- if (!initial_inst)
- return null;
- var type = this.types_by_index[initial_inst[1]];
- ;
- ;
- var is_world = type.plugin.is_world;
- ;
- if (this.isloading && is_world && !type.isOnLoaderLayout)
- return null;
- if (is_world && !this.glwrap && initial_inst[0][11] === 11)
- return null;
- var original_layer = layer;
- if (!is_world)
- layer = null;
- var inst;
- if (type.deadCache.length)
- {
- inst = type.deadCache.pop();
- inst.recycled = true;
- type.plugin.Instance.call(inst, type);
- }
- else
- {
- inst = new type.plugin.Instance(type);
- inst.recycled = false;
- }
- if (is_startup_instance && !skip_siblings && !this.objectsByUid.hasOwnProperty(initial_inst[2].toString()))
- inst.uid = initial_inst[2];
- else
- inst.uid = this.next_uid++;
- this.objectsByUid[inst.uid.toString()] = inst;
- inst.puid = this.next_puid++;
- inst.iid = type.instances.length;
- for (i = 0, len = this.createRow.length; i < len; ++i)
- {
- if (this.createRow[i].type === type)
- inst.iid++;
- }
- inst.get_iid = cr.inst_get_iid;
- inst.toString = cr.inst_toString;
- var initial_vars = initial_inst[3];
- if (inst.recycled)
- {
- cr.wipe(inst.extra);
- }
- else
- {
- inst.extra = {};
- if (typeof cr_is_preview !== "undefined")
- {
- inst.instance_var_names = [];
- inst.instance_var_names.length = initial_vars.length;
- for (i = 0, len = initial_vars.length; i < len; i++)
- inst.instance_var_names[i] = initial_vars[i][1];
- }
- inst.instance_vars = [];
- inst.instance_vars.length = initial_vars.length;
- }
- for (i = 0, len = initial_vars.length; i < len; i++)
- inst.instance_vars[i] = initial_vars[i][0];
- if (is_world)
- {
- var wm = initial_inst[0];
- ;
- inst.x = cr.is_undefined(sx) ? wm[0] : sx;
- inst.y = cr.is_undefined(sy) ? wm[1] : sy;
- inst.z = wm[2];
- inst.width = wm[3];
- inst.height = wm[4];
- inst.depth = wm[5];
- inst.angle = wm[6];
- inst.opacity = wm[7];
- inst.hotspotX = wm[8];
- inst.hotspotY = wm[9];
- inst.blend_mode = wm[10];
- effect_fallback = wm[11];
- if (!this.glwrap && type.effect_types.length) // no WebGL renderer and shaders used
- inst.blend_mode = effect_fallback; // use fallback blend mode - destroy mode was handled above
- inst.compositeOp = cr.effectToCompositeOp(inst.blend_mode);
- if (this.gl)
- cr.setGLBlend(inst, inst.blend_mode, this.gl);
- if (inst.recycled)
- {
- for (i = 0, len = wm[12].length; i < len; i++)
- {
- for (j = 0, lenj = wm[12][i].length; j < lenj; j++)
- inst.effect_params[i][j] = wm[12][i][j];
- }
- inst.bbox.set(0, 0, 0, 0);
- inst.collcells.set(0, 0, -1, -1);
- inst.rendercells.set(0, 0, -1, -1);
- inst.bquad.set_from_rect(inst.bbox);
- inst.bbox_changed_callbacks.length = 0;
- }
- else
- {
- inst.effect_params = wm[12].slice(0);
- for (i = 0, len = inst.effect_params.length; i < len; i++)
- inst.effect_params[i] = wm[12][i].slice(0);
- inst.active_effect_types = [];
- inst.active_effect_flags = [];
- inst.active_effect_flags.length = type.effect_types.length;
- inst.bbox = new cr.rect(0, 0, 0, 0);
- inst.collcells = new cr.rect(0, 0, -1, -1);
- inst.rendercells = new cr.rect(0, 0, -1, -1);
- inst.bquad = new cr.quad();
- inst.bbox_changed_callbacks = [];
- inst.set_bbox_changed = cr.set_bbox_changed;
- inst.add_bbox_changed_callback = cr.add_bbox_changed_callback;
- inst.contains_pt = cr.inst_contains_pt;
- inst.update_bbox = cr.update_bbox;
- inst.update_render_cell = cr.update_render_cell;
- inst.update_collision_cell = cr.update_collision_cell;
- inst.get_zindex = cr.inst_get_zindex;
- }
- inst.tilemap_exists = false;
- inst.tilemap_width = 0;
- inst.tilemap_height = 0;
- inst.tilemap_data = null;
- if (wm.length === 14)
- {
- inst.tilemap_exists = true;
- inst.tilemap_width = wm[13][0];
- inst.tilemap_height = wm[13][1];
- inst.tilemap_data = wm[13][2];
- }
- for (i = 0, len = type.effect_types.length; i < len; i++)
- inst.active_effect_flags[i] = true;
- inst.updateActiveEffects = cr.inst_updateActiveEffects;
- inst.updateActiveEffects();
- inst.uses_shaders = !!inst.active_effect_types.length;
- inst.bbox_changed = true;
- inst.cell_changed = true;
- type.any_cell_changed = true;
- inst.visible = true;
- inst.my_timescale = -1.0;
- inst.layer = layer;
- inst.zindex = layer.instances.length; // will be placed at top of current layer
- if (typeof inst.collision_poly === "undefined")
- inst.collision_poly = null;
- inst.collisionsEnabled = true;
- this.redraw = true;
- }
- var initial_props, binst;
- all_behaviors.length = 0;
- for (i = 0, len = type.families.length; i < len; i++)
- {
- all_behaviors.push.apply(all_behaviors, type.families[i].behaviors);
- }
- all_behaviors.push.apply(all_behaviors, type.behaviors);
- if (inst.recycled)
- {
- for (i = 0, len = all_behaviors.length; i < len; i++)
- {
- var btype = all_behaviors[i];
- binst = inst.behavior_insts[i];
- binst.recycled = true;
- btype.behavior.Instance.call(binst, btype, inst);
- initial_props = initial_inst[4][i];
- for (j = 0, lenj = initial_props.length; j < lenj; j++)
- binst.properties[j] = initial_props[j];
- binst.onCreate();
- btype.behavior.my_instances.add(inst);
- }
- }
- else
- {
- inst.behavior_insts = [];
- for (i = 0, len = all_behaviors.length; i < len; i++)
- {
- var btype = all_behaviors[i];
- var binst = new btype.behavior.Instance(btype, inst);
- binst.recycled = false;
- binst.properties = initial_inst[4][i].slice(0);
- binst.onCreate();
- cr.seal(binst);
- inst.behavior_insts.push(binst);
- btype.behavior.my_instances.add(inst);
- }
- }
- initial_props = initial_inst[5];
- if (inst.recycled)
- {
- for (i = 0, len = initial_props.length; i < len; i++)
- inst.properties[i] = initial_props[i];
- }
- else
- inst.properties = initial_props.slice(0);
- this.createRow.push(inst);
- this.hasPendingInstances = true;
- if (layer)
- {
- ;
- layer.appendToInstanceList(inst, true);
- if (layer.parallaxX !== 1 || layer.parallaxY !== 1)
- type.any_instance_parallaxed = true;
- }
- this.objectcount++;
- if (type.is_contained)
- {
- inst.is_contained = true;
- if (inst.recycled)
- inst.siblings.length = 0;
- else
- inst.siblings = []; // note: should not include self in siblings
- if (!is_startup_instance && !skip_siblings) // layout links initial instances
- {
- for (i = 0, len = type.container.length; i < len; i++)
- {
- if (type.container[i] === type)
- continue;
- if (!type.container[i].default_instance)
- {
- return null;
- }
- inst.siblings.push(this.createInstanceFromInit(type.container[i].default_instance, original_layer, false, is_world ? inst.x : sx, is_world ? inst.y : sy, true));
- }
- for (i = 0, len = inst.siblings.length; i < len; i++)
- {
- inst.siblings[i].siblings.push(inst);
- for (j = 0; j < len; j++)
- {
- if (i !== j)
- inst.siblings[i].siblings.push(inst.siblings[j]);
- }
- }
- }
- }
- else
- {
- inst.is_contained = false;
- inst.siblings = null;
- }
- inst.onCreate();
- if (!inst.recycled)
- cr.seal(inst);
- for (i = 0, len = inst.behavior_insts.length; i < len; i++)
- {
- if (inst.behavior_insts[i].postCreate)
- inst.behavior_insts[i].postCreate();
- }
- return inst;
- };
- Runtime.prototype.getLayerByName = function (layer_name)
- {
- var i, len;
- for (i = 0, len = this.running_layout.layers.length; i < len; i++)
- {
- var layer = this.running_layout.layers[i];
- if (cr.equals_nocase(layer.name, layer_name))
- return layer;
- }
- return null;
- };
- Runtime.prototype.getLayerByNumber = function (index)
- {
- index = cr.floor(index);
- if (index < 0)
- index = 0;
- if (index >= this.running_layout.layers.length)
- index = this.running_layout.layers.length - 1;
- return this.running_layout.layers[index];
- };
- Runtime.prototype.getLayer = function (l)
- {
- if (cr.is_number(l))
- return this.getLayerByNumber(l);
- else
- return this.getLayerByName(l.toString());
- };
- Runtime.prototype.clearSol = function (solModifiers)
- {
- var i, len;
- for (i = 0, len = solModifiers.length; i < len; i++)
- {
- solModifiers[i].getCurrentSol().select_all = true;
- }
- };
- Runtime.prototype.pushCleanSol = function (solModifiers)
- {
- var i, len;
- for (i = 0, len = solModifiers.length; i < len; i++)
- {
- solModifiers[i].pushCleanSol();
- }
- };
- Runtime.prototype.pushCopySol = function (solModifiers)
- {
- var i, len;
- for (i = 0, len = solModifiers.length; i < len; i++)
- {
- solModifiers[i].pushCopySol();
- }
- };
- Runtime.prototype.popSol = function (solModifiers)
- {
- var i, len;
- for (i = 0, len = solModifiers.length; i < len; i++)
- {
- solModifiers[i].popSol();
- }
- };
- Runtime.prototype.updateAllCells = function (type)
- {
- if (!type.any_cell_changed)
- return; // all instances must already be up-to-date
- var i, len, instances = type.instances;
- for (i = 0, len = instances.length; i < len; ++i)
- {
- instances[i].update_collision_cell();
- }
- var createRow = this.createRow;
- for (i = 0, len = createRow.length; i < len; ++i)
- {
- if (createRow[i].type === type)
- createRow[i].update_collision_cell();
- }
- type.any_cell_changed = false;
- };
- Runtime.prototype.getCollisionCandidates = function (layer, rtype, bbox, candidates)
- {
- var i, len, t;
- var is_parallaxed = (layer ? (layer.parallaxX !== 1 || layer.parallaxY !== 1) : false);
- if (rtype.is_family)
- {
- for (i = 0, len = rtype.members.length; i < len; ++i)
- {
- t = rtype.members[i];
- if (is_parallaxed || t.any_instance_parallaxed)
- {
- cr.appendArray(candidates, t.instances);
- }
- else
- {
- this.updateAllCells(t);
- t.collision_grid.queryRange(bbox, candidates);
- }
- }
- }
- else
- {
- if (is_parallaxed || rtype.any_instance_parallaxed)
- {
- cr.appendArray(candidates, rtype.instances);
- }
- else
- {
- this.updateAllCells(rtype);
- rtype.collision_grid.queryRange(bbox, candidates);
- }
- }
- };
- Runtime.prototype.getTypesCollisionCandidates = function (layer, types, bbox, candidates)
- {
- var i, len;
- for (i = 0, len = types.length; i < len; ++i)
- {
- this.getCollisionCandidates(layer, types[i], bbox, candidates);
- }
- };
- Runtime.prototype.getSolidCollisionCandidates = function (layer, bbox, candidates)
- {
- var solid = this.getSolidBehavior();
- if (!solid)
- return null;
- this.getTypesCollisionCandidates(layer, solid.my_types, bbox, candidates);
- };
- Runtime.prototype.getJumpthruCollisionCandidates = function (layer, bbox, candidates)
- {
- var jumpthru = this.getJumpthruBehavior();
- if (!jumpthru)
- return null;
- this.getTypesCollisionCandidates(layer, jumpthru.my_types, bbox, candidates);
- };
- Runtime.prototype.testAndSelectCanvasPointOverlap = function (type, ptx, pty, inverted)
- {
- var sol = type.getCurrentSol();
- var i, j, inst, len;
- var lx, ly;
- if (sol.select_all)
- {
- if (!inverted)
- {
- sol.select_all = false;
- sol.instances.length = 0; // clear contents
- }
- for (i = 0, len = type.instances.length; i < len; i++)
- {
- inst = type.instances[i];
- inst.update_bbox();
- lx = inst.layer.canvasToLayer(ptx, pty, true);
- ly = inst.layer.canvasToLayer(ptx, pty, false);
- if (inst.contains_pt(lx, ly))
- {
- if (inverted)
- return false;
- else
- sol.instances.push(inst);
- }
- }
- }
- else
- {
- j = 0;
- for (i = 0, len = sol.instances.length; i < len; i++)
- {
- inst = sol.instances[i];
- inst.update_bbox();
- lx = inst.layer.canvasToLayer(ptx, pty, true);
- ly = inst.layer.canvasToLayer(ptx, pty, false);
- if (inst.contains_pt(lx, ly))
- {
- if (inverted)
- return false;
- else
- {
- sol.instances[j] = sol.instances[i];
- j++;
- }
- }
- }
- if (!inverted)
- sol.instances.length = j;
- }
- type.applySolToContainer();
- if (inverted)
- return true; // did not find anything overlapping
- else
- return sol.hasObjects();
- };
- Runtime.prototype.testOverlap = function (a, b)
- {
- if (!a || !b || a === b || !a.collisionsEnabled || !b.collisionsEnabled)
- return false;
- a.update_bbox();
- b.update_bbox();
- var layera = a.layer;
- var layerb = b.layer;
- var different_layers = (layera !== layerb && (layera.parallaxX !== layerb.parallaxX || layerb.parallaxY !== layerb.parallaxY || layera.scale !== layerb.scale || layera.angle !== layerb.angle || layera.zoomRate !== layerb.zoomRate));
- var i, len, i2, i21, x, y, haspolya, haspolyb, polya, polyb;
- if (!different_layers) // same layers: easy check
- {
- if (!a.bbox.intersects_rect(b.bbox))
- return false;
- if (!a.bquad.intersects_quad(b.bquad))
- return false;
- if (a.tilemap_exists && b.tilemap_exists)
- return false;
- if (a.tilemap_exists)
- return this.testTilemapOverlap(a, b);
- if (b.tilemap_exists)
- return this.testTilemapOverlap(b, a);
- haspolya = (a.collision_poly && !a.collision_poly.is_empty());
- haspolyb = (b.collision_poly && !b.collision_poly.is_empty());
- if (!haspolya && !haspolyb)
- return true;
- if (haspolya)
- {
- a.collision_poly.cache_poly(a.width, a.height, a.angle);
- polya = a.collision_poly;
- }
- else
- {
- this.temp_poly.set_from_quad(a.bquad, a.x, a.y, a.width, a.height);
- polya = this.temp_poly;
- }
- if (haspolyb)
- {
- b.collision_poly.cache_poly(b.width, b.height, b.angle);
- polyb = b.collision_poly;
- }
- else
- {
- this.temp_poly.set_from_quad(b.bquad, b.x, b.y, b.width, b.height);
- polyb = this.temp_poly;
- }
- return polya.intersects_poly(polyb, b.x - a.x, b.y - a.y);
- }
- else // different layers: need to do full translated check
- {
- haspolya = (a.collision_poly && !a.collision_poly.is_empty());
- haspolyb = (b.collision_poly && !b.collision_poly.is_empty());
- if (haspolya)
- {
- a.collision_poly.cache_poly(a.width, a.height, a.angle);
- this.temp_poly.set_from_poly(a.collision_poly);
- }
- else
- {
- this.temp_poly.set_from_quad(a.bquad, a.x, a.y, a.width, a.height);
- }
- polya = this.temp_poly;
- if (haspolyb)
- {
- b.collision_poly.cache_poly(b.width, b.height, b.angle);
- this.temp_poly2.set_from_poly(b.collision_poly);
- }
- else
- {
- this.temp_poly2.set_from_quad(b.bquad, b.x, b.y, b.width, b.height);
- }
- polyb = this.temp_poly2;
- for (i = 0, len = polya.pts_count; i < len; i++)
- {
- i2 = i * 2;
- i21 = i2 + 1;
- x = polya.pts_cache[i2];
- y = polya.pts_cache[i21];
- polya.pts_cache[i2] = layera.layerToCanvas(x + a.x, y + a.y, true);
- polya.pts_cache[i21] = layera.layerToCanvas(x + a.x, y + a.y, false);
- }
- polya.update_bbox();
- for (i = 0, len = polyb.pts_count; i < len; i++)
- {
- i2 = i * 2;
- i21 = i2 + 1;
- x = polyb.pts_cache[i2];
- y = polyb.pts_cache[i21];
- polyb.pts_cache[i2] = layerb.layerToCanvas(x + b.x, y + b.y, true);
- polyb.pts_cache[i21] = layerb.layerToCanvas(x + b.x, y + b.y, false);
- }
- polyb.update_bbox();
- return polya.intersects_poly(polyb, 0, 0);
- }
- };
- var tmpQuad = new cr.quad();
- var tmpRect = new cr.rect(0, 0, 0, 0);
- var collrect_candidates = [];
- Runtime.prototype.testTilemapOverlap = function (tm, a)
- {
- var i, len, c, rc;
- var bbox = a.bbox;
- var tmx = tm.x;
- var tmy = tm.y;
- tm.getCollisionRectCandidates(bbox, collrect_candidates);
- var collrects = collrect_candidates;
- var haspolya = (a.collision_poly && !a.collision_poly.is_empty());
- for (i = 0, len = collrects.length; i < len; ++i)
- {
- c = collrects[i];
- rc = c.rc;
- if (bbox.intersects_rect_off(rc, tmx, tmy))
- {
- tmpQuad.set_from_rect(rc);
- tmpQuad.offset(tmx, tmy);
- if (tmpQuad.intersects_quad(a.bquad))
- {
- if (haspolya)
- {
- a.collision_poly.cache_poly(a.width, a.height, a.angle);
- if (c.poly)
- {
- if (c.poly.intersects_poly(a.collision_poly, a.x - (tmx + rc.left), a.y - (tmy + rc.top)))
- {
- collrect_candidates.length = 0;
- return true;
- }
- }
- else
- {
- this.temp_poly.set_from_quad(tmpQuad, 0, 0, rc.right - rc.left, rc.bottom - rc.top);
- if (this.temp_poly.intersects_poly(a.collision_poly, a.x, a.y))
- {
- collrect_candidates.length = 0;
- return true;
- }
- }
- }
- else
- {
- if (c.poly)
- {
- this.temp_poly.set_from_quad(a.bquad, 0, 0, a.width, a.height);
- if (c.poly.intersects_poly(this.temp_poly, -(tmx + rc.left), -(tmy + rc.top)))
- {
- collrect_candidates.length = 0;
- return true;
- }
- }
- else
- {
- collrect_candidates.length = 0;
- return true;
- }
- }
- }
- }
- }
- collrect_candidates.length = 0;
- return false;
- };
- Runtime.prototype.testRectOverlap = function (r, b)
- {
- if (!b || !b.collisionsEnabled)
- return false;
- b.update_bbox();
- var layerb = b.layer;
- var haspolyb, polyb;
- if (!b.bbox.intersects_rect(r))
- return false;
- if (b.tilemap_exists)
- {
- b.getCollisionRectCandidates(r, collrect_candidates);
- var collrects = collrect_candidates;
- var i, len, c, tilerc;
- var tmx = b.x;
- var tmy = b.y;
- for (i = 0, len = collrects.length; i < len; ++i)
- {
- c = collrects[i];
- tilerc = c.rc;
- if (r.intersects_rect_off(tilerc, tmx, tmy))
- {
- if (c.poly)
- {
- this.temp_poly.set_from_rect(r, 0, 0);
- if (c.poly.intersects_poly(this.temp_poly, -(tmx + tilerc.left), -(tmy + tilerc.top)))
- {
- collrect_candidates.length = 0;
- return true;
- }
- }
- else
- {
- collrect_candidates.length = 0;
- return true;
- }
- }
- }
- collrect_candidates.length = 0;
- return false;
- }
- else
- {
- tmpQuad.set_from_rect(r);
- if (!b.bquad.intersects_quad(tmpQuad))
- return false;
- haspolyb = (b.collision_poly && !b.collision_poly.is_empty());
- if (!haspolyb)
- return true;
- b.collision_poly.cache_poly(b.width, b.height, b.angle);
- tmpQuad.offset(-r.left, -r.top);
- this.temp_poly.set_from_quad(tmpQuad, 0, 0, 1, 1);
- return b.collision_poly.intersects_poly(this.temp_poly, r.left - b.x, r.top - b.y);
- }
- };
- Runtime.prototype.testSegmentOverlap = function (x1, y1, x2, y2, b)
- {
- if (!b || !b.collisionsEnabled)
- return false;
- b.update_bbox();
- var layerb = b.layer;
- var haspolyb, polyb;
- tmpRect.set(cr.min(x1, x2), cr.min(y1, y2), cr.max(x1, x2), cr.max(y1, y2));
- if (!b.bbox.intersects_rect(tmpRect))
- return false;
- if (b.tilemap_exists)
- {
- b.getCollisionRectCandidates(tmpRect, collrect_candidates);
- var collrects = collrect_candidates;
- var i, len, c, tilerc;
- var tmx = b.x;
- var tmy = b.y;
- for (i = 0, len = collrects.length; i < len; ++i)
- {
- c = collrects[i];
- tilerc = c.rc;
- if (tmpRect.intersects_rect_off(tilerc, tmx, tmy))
- {
- tmpQuad.set_from_rect(tilerc);
- tmpQuad.offset(tmx, tmy);
- if (tmpQuad.intersects_segment(x1, y1, x2, y2))
- {
- if (c.poly)
- {
- if (c.poly.intersects_segment(tmx + tilerc.left, tmy + tilerc.top, x1, y1, x2, y2))
- {
- collrect_candidates.length = 0;
- return true;
- }
- }
- else
- {
- collrect_candidates.length = 0;
- return true;
- }
- }
- }
- }
- collrect_candidates.length = 0;
- return false;
- }
- else
- {
- if (!b.bquad.intersects_segment(x1, y1, x2, y2))
- return false;
- haspolyb = (b.collision_poly && !b.collision_poly.is_empty());
- if (!haspolyb)
- return true;
- b.collision_poly.cache_poly(b.width, b.height, b.angle);
- return b.collision_poly.intersects_segment(b.x, b.y, x1, y1, x2, y2);
- }
- };
- Runtime.prototype.typeHasBehavior = function (t, b)
- {
- if (!b)
- return false;
- var i, len, j, lenj, f;
- for (i = 0, len = t.behaviors.length; i < len; i++)
- {
- if (t.behaviors[i].behavior instanceof b)
- return true;
- }
- if (!t.is_family)
- {
- for (i = 0, len = t.families.length; i < len; i++)
- {
- f = t.families[i];
- for (j = 0, lenj = f.behaviors.length; j < lenj; j++)
- {
- if (f.behaviors[j].behavior instanceof b)
- return true;
- }
- }
- }
- return false;
- };
- Runtime.prototype.typeHasNoSaveBehavior = function (t)
- {
- return this.typeHasBehavior(t, cr.behaviors.NoSave);
- };
- Runtime.prototype.typeHasPersistBehavior = function (t)
- {
- return this.typeHasBehavior(t, cr.behaviors.Persist);
- };
- Runtime.prototype.getSolidBehavior = function ()
- {
- return this.solidBehavior;
- };
- Runtime.prototype.getJumpthruBehavior = function ()
- {
- return this.jumpthruBehavior;
- };
- var candidates = [];
- Runtime.prototype.testOverlapSolid = function (inst)
- {
- var i, len, s;
- inst.update_bbox();
- this.getSolidCollisionCandidates(inst.layer, inst.bbox, candidates);
- for (i = 0, len = candidates.length; i < len; ++i)
- {
- s = candidates[i];
- if (!s.extra["solidEnabled"])
- continue;
- if (this.testOverlap(inst, s))
- {
- candidates.length = 0;
- return s;
- }
- }
- candidates.length = 0;
- return null;
- };
- Runtime.prototype.testRectOverlapSolid = function (r)
- {
- var i, len, s;
- this.getSolidCollisionCandidates(null, r, candidates);
- for (i = 0, len = candidates.length; i < len; ++i)
- {
- s = candidates[i];
- if (!s.extra["solidEnabled"])
- continue;
- if (this.testRectOverlap(r, s))
- {
- candidates.length = 0;
- return s;
- }
- }
- candidates.length = 0;
- return null;
- };
- var jumpthru_array_ret = [];
- Runtime.prototype.testOverlapJumpThru = function (inst, all)
- {
- var ret = null;
- if (all)
- {
- ret = jumpthru_array_ret;
- ret.length = 0;
- }
- inst.update_bbox();
- this.getJumpthruCollisionCandidates(inst.layer, inst.bbox, candidates);
- var i, len, j;
- for (i = 0, len = candidates.length; i < len; ++i)
- {
- j = candidates[i];
- if (!j.extra["jumpthruEnabled"])
- continue;
- if (this.testOverlap(inst, j))
- {
- if (all)
- ret.push(j);
- else
- {
- candidates.length = 0;
- return j;
- }
- }
- }
- candidates.length = 0;
- return ret;
- };
- Runtime.prototype.pushOutSolid = function (inst, xdir, ydir, dist, include_jumpthrus, specific_jumpthru)
- {
- var push_dist = dist || 50;
- var oldx = inst.x
- var oldy = inst.y;
- var i;
- var last_overlapped = null, secondlast_overlapped = null;
- for (i = 0; i < push_dist; i++)
- {
- inst.x = (oldx + (xdir * i));
- inst.y = (oldy + (ydir * i));
- inst.set_bbox_changed();
- if (!this.testOverlap(inst, last_overlapped))
- {
- last_overlapped = this.testOverlapSolid(inst);
- if (last_overlapped)
- secondlast_overlapped = last_overlapped;
- if (!last_overlapped)
- {
- if (include_jumpthrus)
- {
- if (specific_jumpthru)
- last_overlapped = (this.testOverlap(inst, specific_jumpthru) ? specific_jumpthru : null);
- else
- last_overlapped = this.testOverlapJumpThru(inst);
- if (last_overlapped)
- secondlast_overlapped = last_overlapped;
- }
- if (!last_overlapped)
- {
- if (secondlast_overlapped)
- this.pushInFractional(inst, xdir, ydir, secondlast_overlapped, 16);
- return true;
- }
- }
- }
- }
- inst.x = oldx;
- inst.y = oldy;
- inst.set_bbox_changed();
- return false;
- };
- Runtime.prototype.pushOut = function (inst, xdir, ydir, dist, otherinst)
- {
- var push_dist = dist || 50;
- var oldx = inst.x
- var oldy = inst.y;
- var i;
- for (i = 0; i < push_dist; i++)
- {
- inst.x = (oldx + (xdir * i));
- inst.y = (oldy + (ydir * i));
- inst.set_bbox_changed();
- if (!this.testOverlap(inst, otherinst))
- return true;
- }
- inst.x = oldx;
- inst.y = oldy;
- inst.set_bbox_changed();
- return false;
- };
- Runtime.prototype.pushInFractional = function (inst, xdir, ydir, obj, limit)
- {
- var divisor = 2;
- var frac;
- var forward = false;
- var overlapping = false;
- var bestx = inst.x;
- var besty = inst.y;
- while (divisor <= limit)
- {
- frac = 1 / divisor;
- divisor *= 2;
- inst.x += xdir * frac * (forward ? 1 : -1);
- inst.y += ydir * frac * (forward ? 1 : -1);
- inst.set_bbox_changed();
- if (this.testOverlap(inst, obj))
- {
- forward = true;
- overlapping = true;
- }
- else
- {
- forward = false;
- overlapping = false;
- bestx = inst.x;
- besty = inst.y;
- }
- }
- if (overlapping)
- {
- inst.x = bestx;
- inst.y = besty;
- inst.set_bbox_changed();
- }
- };
- Runtime.prototype.pushOutSolidNearest = function (inst, max_dist_)
- {
- var max_dist = (cr.is_undefined(max_dist_) ? 100 : max_dist_);
- var dist = 0;
- var oldx = inst.x
- var oldy = inst.y;
- var dir = 0;
- var dx = 0, dy = 0;
- var last_overlapped = this.testOverlapSolid(inst);
- if (!last_overlapped)
- return true; // already clear of solids
- while (dist <= max_dist)
- {
- switch (dir) {
- case 0: dx = 0; dy = -1; dist++; break;
- case 1: dx = 1; dy = -1; break;
- case 2: dx = 1; dy = 0; break;
- case 3: dx = 1; dy = 1; break;
- case 4: dx = 0; dy = 1; break;
- case 5: dx = -1; dy = 1; break;
- case 6: dx = -1; dy = 0; break;
- case 7: dx = -1; dy = -1; break;
- }
- dir = (dir + 1) % 8;
- inst.x = cr.floor(oldx + (dx * dist));
- inst.y = cr.floor(oldy + (dy * dist));
- inst.set_bbox_changed();
- if (!this.testOverlap(inst, last_overlapped))
- {
- last_overlapped = this.testOverlapSolid(inst);
- if (!last_overlapped)
- return true;
- }
- }
- inst.x = oldx;
- inst.y = oldy;
- inst.set_bbox_changed();
- return false;
- };
- Runtime.prototype.registerCollision = function (a, b)
- {
- if (!a.collisionsEnabled || !b.collisionsEnabled)
- return;
- this.registered_collisions.push([a, b]);
- };
- Runtime.prototype.checkRegisteredCollision = function (a, b)
- {
- var i, len, x;
- for (i = 0, len = this.registered_collisions.length; i < len; i++)
- {
- x = this.registered_collisions[i];
- if ((x[0] == a && x[1] == b) || (x[0] == b && x[1] == a))
- return true;
- }
- return false;
- };
- Runtime.prototype.calculateSolidBounceAngle = function(inst, startx, starty, obj)
- {
- var objx = inst.x;
- var objy = inst.y;
- var radius = cr.max(10, cr.distanceTo(startx, starty, objx, objy));
- var startangle = cr.angleTo(startx, starty, objx, objy);
- var firstsolid = obj || this.testOverlapSolid(inst);
- if (!firstsolid)
- return cr.clamp_angle(startangle + cr.PI);
- var cursolid = firstsolid;
- var i, curangle, anticlockwise_free_angle, clockwise_free_angle;
- var increment = cr.to_radians(5); // 5 degree increments
- for (i = 1; i < 36; i++)
- {
- curangle = startangle - i * increment;
- inst.x = startx + Math.cos(curangle) * radius;
- inst.y = starty + Math.sin(curangle) * radius;
- inst.set_bbox_changed();
- if (!this.testOverlap(inst, cursolid))
- {
- cursolid = obj ? null : this.testOverlapSolid(inst);
- if (!cursolid)
- {
- anticlockwise_free_angle = curangle;
- break;
- }
- }
- }
- if (i === 36)
- anticlockwise_free_angle = cr.clamp_angle(startangle + cr.PI);
- var cursolid = firstsolid;
- for (i = 1; i < 36; i++)
- {
- curangle = startangle + i * increment;
- inst.x = startx + Math.cos(curangle) * radius;
- inst.y = starty + Math.sin(curangle) * radius;
- inst.set_bbox_changed();
- if (!this.testOverlap(inst, cursolid))
- {
- cursolid = obj ? null : this.testOverlapSolid(inst);
- if (!cursolid)
- {
- clockwise_free_angle = curangle;
- break;
- }
- }
- }
- if (i === 36)
- clockwise_free_angle = cr.clamp_angle(startangle + cr.PI);
- inst.x = objx;
- inst.y = objy;
- inst.set_bbox_changed();
- if (clockwise_free_angle === anticlockwise_free_angle)
- return clockwise_free_angle;
- var half_diff = cr.angleDiff(clockwise_free_angle, anticlockwise_free_angle) / 2;
- var normal;
- if (cr.angleClockwise(clockwise_free_angle, anticlockwise_free_angle))
- {
- normal = cr.clamp_angle(anticlockwise_free_angle + half_diff + cr.PI);
- }
- else
- {
- normal = cr.clamp_angle(clockwise_free_angle + half_diff);
- }
- ;
- var vx = Math.cos(startangle);
- var vy = Math.sin(startangle);
- var nx = Math.cos(normal);
- var ny = Math.sin(normal);
- var v_dot_n = vx * nx + vy * ny;
- var rx = vx - 2 * v_dot_n * nx;
- var ry = vy - 2 * v_dot_n * ny;
- return cr.angleTo(0, 0, rx, ry);
- };
- var triggerSheetIndex = -1;
- Runtime.prototype.trigger = function (method, inst, value /* for fast triggers */)
- {
- ;
- if (!this.running_layout)
- return false;
- var sheet = this.running_layout.event_sheet;
- if (!sheet)
- return false; // no event sheet active; nothing to trigger
- var ret = false;
- var r, i, len;
- triggerSheetIndex++;
- var deep_includes = sheet.deep_includes;
- for (i = 0, len = deep_includes.length; i < len; ++i)
- {
- r = this.triggerOnSheet(method, inst, deep_includes[i], value);
- ret = ret || r;
- }
- r = this.triggerOnSheet(method, inst, sheet, value);
- ret = ret || r;
- triggerSheetIndex--;
- return ret;
- };
- Runtime.prototype.triggerOnSheet = function (method, inst, sheet, value)
- {
- var ret = false;
- var i, leni, r, families;
- if (!inst)
- {
- r = this.triggerOnSheetForTypeName(method, inst, "system", sheet, value);
- ret = ret || r;
- }
- else
- {
- r = this.triggerOnSheetForTypeName(method, inst, inst.type.name, sheet, value);
- ret = ret || r;
- families = inst.type.families;
- for (i = 0, leni = families.length; i < leni; ++i)
- {
- r = this.triggerOnSheetForTypeName(method, inst, families[i].name, sheet, value);
- ret = ret || r;
- }
- }
- return ret; // true if anything got triggered
- };
- Runtime.prototype.triggerOnSheetForTypeName = function (method, inst, type_name, sheet, value)
- {
- var i, leni;
- var ret = false, ret2 = false;
- var trig, index;
- var fasttrigger = (typeof value !== "undefined");
- var triggers = (fasttrigger ? sheet.fasttriggers : sheet.triggers);
- var obj_entry = triggers[type_name];
- if (!obj_entry)
- return ret;
- var triggers_list = null;
- for (i = 0, leni = obj_entry.length; i < leni; ++i)
- {
- if (obj_entry[i].method == method)
- {
- triggers_list = obj_entry[i].evs;
- break;
- }
- }
- if (!triggers_list)
- return ret;
- var triggers_to_fire;
- if (fasttrigger)
- {
- triggers_to_fire = triggers_list[value];
- }
- else
- {
- triggers_to_fire = triggers_list;
- }
- if (!triggers_to_fire)
- return null;
- for (i = 0, leni = triggers_to_fire.length; i < leni; i++)
- {
- trig = triggers_to_fire[i][0];
- index = triggers_to_fire[i][1];
- ret2 = this.executeSingleTrigger(inst, type_name, trig, index);
- ret = ret || ret2;
- }
- return ret;
- };
- Runtime.prototype.executeSingleTrigger = function (inst, type_name, trig, index)
- {
- var i, leni;
- var ret = false;
- this.trigger_depth++;
- var current_event = this.getCurrentEventStack().current_event;
- if (current_event)
- this.pushCleanSol(current_event.solModifiersIncludingParents);
- var isrecursive = (this.trigger_depth > 1); // calling trigger from inside another trigger
- this.pushCleanSol(trig.solModifiersIncludingParents);
- if (isrecursive)
- this.pushLocalVarStack();
- var event_stack = this.pushEventStack(trig);
- event_stack.current_event = trig;
- if (inst)
- {
- var sol = this.types[type_name].getCurrentSol();
- sol.select_all = false;
- sol.instances.length = 1;
- sol.instances[0] = inst;
- this.types[type_name].applySolToContainer();
- }
- var ok_to_run = true;
- if (trig.parent)
- {
- var temp_parents_arr = event_stack.temp_parents_arr;
- var cur_parent = trig.parent;
- while (cur_parent)
- {
- temp_parents_arr.push(cur_parent);
- cur_parent = cur_parent.parent;
- }
- temp_parents_arr.reverse();
- for (i = 0, leni = temp_parents_arr.length; i < leni; i++)
- {
- if (!temp_parents_arr[i].run_pretrigger()) // parent event failed
- {
- ok_to_run = false;
- break;
- }
- }
- }
- if (ok_to_run)
- {
- this.execcount++;
- if (trig.orblock)
- trig.run_orblocktrigger(index);
- else
- trig.run();
- ret = ret || event_stack.last_event_true;
- }
- this.popEventStack();
- if (isrecursive)
- this.popLocalVarStack();
- this.popSol(trig.solModifiersIncludingParents);
- if (current_event)
- this.popSol(current_event.solModifiersIncludingParents);
- if (this.hasPendingInstances && this.isInOnDestroy === 0 && triggerSheetIndex === 0 && !this.isRunningEvents)
- {
- this.ClearDeathRow();
- }
- this.trigger_depth--;
- return ret;
- };
- Runtime.prototype.getCurrentCondition = function ()
- {
- var evinfo = this.getCurrentEventStack();
- return evinfo.current_event.conditions[evinfo.cndindex];
- };
- Runtime.prototype.getCurrentAction = function ()
- {
- var evinfo = this.getCurrentEventStack();
- return evinfo.current_event.actions[evinfo.actindex];
- };
- Runtime.prototype.pushLocalVarStack = function ()
- {
- this.localvar_stack_index++;
- if (this.localvar_stack_index >= this.localvar_stack.length)
- this.localvar_stack.push([]);
- };
- Runtime.prototype.popLocalVarStack = function ()
- {
- ;
- this.localvar_stack_index--;
- };
- Runtime.prototype.getCurrentLocalVarStack = function ()
- {
- return this.localvar_stack[this.localvar_stack_index];
- };
- Runtime.prototype.pushEventStack = function (cur_event)
- {
- this.event_stack_index++;
- if (this.event_stack_index >= this.event_stack.length)
- this.event_stack.push(new cr.eventStackFrame());
- var ret = this.getCurrentEventStack();
- ret.reset(cur_event);
- return ret;
- };
- Runtime.prototype.popEventStack = function ()
- {
- ;
- this.event_stack_index--;
- };
- Runtime.prototype.getCurrentEventStack = function ()
- {
- return this.event_stack[this.event_stack_index];
- };
- Runtime.prototype.pushLoopStack = function (name_)
- {
- this.loop_stack_index++;
- if (this.loop_stack_index >= this.loop_stack.length)
- {
- this.loop_stack.push(cr.seal({ name: name_, index: 0, stopped: false }));
- }
- var ret = this.getCurrentLoop();
- ret.name = name_;
- ret.index = 0;
- ret.stopped = false;
- return ret;
- };
- Runtime.prototype.popLoopStack = function ()
- {
- ;
- this.loop_stack_index--;
- };
- Runtime.prototype.getCurrentLoop = function ()
- {
- return this.loop_stack[this.loop_stack_index];
- };
- Runtime.prototype.getEventVariableByName = function (name, scope)
- {
- var i, leni, j, lenj, sheet, e;
- while (scope)
- {
- for (i = 0, leni = scope.subevents.length; i < leni; i++)
- {
- e = scope.subevents[i];
- if (e instanceof cr.eventvariable && cr.equals_nocase(name, e.name))
- return e;
- }
- scope = scope.parent;
- }
- for (i = 0, leni = this.eventsheets_by_index.length; i < leni; i++)
- {
- sheet = this.eventsheets_by_index[i];
- for (j = 0, lenj = sheet.events.length; j < lenj; j++)
- {
- e = sheet.events[j];
- if (e instanceof cr.eventvariable && cr.equals_nocase(name, e.name))
- return e;
- }
- }
- return null;
- };
- Runtime.prototype.getLayoutBySid = function (sid_)
- {
- var i, len;
- for (i = 0, len = this.layouts_by_index.length; i < len; i++)
- {
- if (this.layouts_by_index[i].sid === sid_)
- return this.layouts_by_index[i];
- }
- return null;
- };
- Runtime.prototype.getObjectTypeBySid = function (sid_)
- {
- var i, len;
- for (i = 0, len = this.types_by_index.length; i < len; i++)
- {
- if (this.types_by_index[i].sid === sid_)
- return this.types_by_index[i];
- }
- return null;
- };
- Runtime.prototype.getGroupBySid = function (sid_)
- {
- var i, len;
- for (i = 0, len = this.allGroups.length; i < len; i++)
- {
- if (this.allGroups[i].sid === sid_)
- return this.allGroups[i];
- }
- return null;
- };
- Runtime.prototype.doCanvasSnapshot = function (format_, quality_)
- {
- this.snapshotCanvas = [format_, quality_];
- this.redraw = true; // force redraw so snapshot is always taken
- };
- function makeSaveDb(e)
- {
- var db = e.target.result;
- db.createObjectStore("saves", { keyPath: "slot" });
- };
- function IndexedDB_WriteSlot(slot_, data_, oncomplete_, onerror_)
- {
- var request = indexedDB.open("_C2SaveStates");
- request.onupgradeneeded = makeSaveDb;
- request.onerror = onerror_;
- request.onsuccess = function (e)
- {
- var db = e.target.result;
- db.onerror = onerror_;
- var transaction = db.transaction(["saves"], "readwrite");
- var objectStore = transaction.objectStore("saves");
- var putReq = objectStore.put({"slot": slot_, "data": data_ });
- putReq.onsuccess = oncomplete_;
- };
- };
- function IndexedDB_ReadSlot(slot_, oncomplete_, onerror_)
- {
- var request = indexedDB.open("_C2SaveStates");
- request.onupgradeneeded = makeSaveDb;
- request.onerror = onerror_;
- request.onsuccess = function (e)
- {
- var db = e.target.result;
- db.onerror = onerror_;
- var transaction = db.transaction(["saves"]);
- var objectStore = transaction.objectStore("saves");
- var readReq = objectStore.get(slot_);
- readReq.onsuccess = function (e)
- {
- if (readReq.result)
- oncomplete_(readReq.result["data"]);
- else
- oncomplete_(null);
- };
- };
- };
- Runtime.prototype.signalContinuousPreview = function ()
- {
- this.signalledContinuousPreview = true;
- };
- function doContinuousPreviewReload()
- {
- cr.logexport("Reloading for continuous preview");
- if (!!window["c2cocoonjs"])
- {
- CocoonJS["App"]["reload"]();
- }
- else
- {
- if (window.location.search.indexOf("continuous") > -1)
- window.location.reload(true);
- else
- window.location = window.location + "?continuous";
- }
- };
- Runtime.prototype.handleSaveLoad = function ()
- {
- var self = this;
- var savingToSlot = this.saveToSlot;
- var savingJson = this.lastSaveJson;
- var loadingFromSlot = this.loadFromSlot;
- var continuous = false;
- if (this.signalledContinuousPreview)
- {
- continuous = true;
- savingToSlot = "__c2_continuouspreview";
- this.signalledContinuousPreview = false;
- }
- if (savingToSlot.length)
- {
- this.ClearDeathRow();
- savingJson = this.saveToJSONString();
- if (window.indexedDB && !this.isCocoonJs)
- {
- IndexedDB_WriteSlot(savingToSlot, savingJson, function ()
- {
- cr.logexport("Saved state to IndexedDB storage (" + savingJson.length + " bytes)");
- self.lastSaveJson = savingJson;
- self.trigger(cr.system_object.prototype.cnds.OnSaveComplete, null);
- self.lastSaveJson = "";
- if (continuous)
- doContinuousPreviewReload();
- }, function (e)
- {
- try {
- localStorage.setItem("__c2save_" + savingToSlot, savingJson);
- cr.logexport("Saved state to WebStorage (" + savingJson.length + " bytes)");
- self.lastSaveJson = savingJson;
- self.trigger(cr.system_object.prototype.cnds.OnSaveComplete, null);
- self.lastSaveJson = "";
- if (continuous)
- doContinuousPreviewReload();
- }
- catch (f)
- {
- cr.logexport("Failed to save game state: " + e + "; " + f);
- }
- });
- }
- else
- {
- try {
- localStorage.setItem("__c2save_" + savingToSlot, savingJson);
- cr.logexport("Saved state to WebStorage (" + savingJson.length + " bytes)");
- self.lastSaveJson = savingJson;
- this.trigger(cr.system_object.prototype.cnds.OnSaveComplete, null);
- self.lastSaveJson = "";
- if (continuous)
- doContinuousPreviewReload();
- }
- catch (e)
- {
- cr.logexport("Error saving to WebStorage: " + e);
- }
- }
- this.saveToSlot = "";
- this.loadFromSlot = "";
- this.loadFromJson = "";
- }
- if (loadingFromSlot.length)
- {
- if (window.indexedDB && !this.isCocoonJs)
- {
- IndexedDB_ReadSlot(loadingFromSlot, function (result_)
- {
- if (result_)
- {
- self.loadFromJson = result_;
- cr.logexport("Loaded state from IndexedDB storage (" + self.loadFromJson.length + " bytes)");
- }
- else
- {
- self.loadFromJson = localStorage.getItem("__c2save_" + loadingFromSlot) || "";
- cr.logexport("Loaded state from WebStorage (" + self.loadFromJson.length + " bytes)");
- }
- self.suspendDrawing = false;
- if (!self.loadFromJson.length)
- self.trigger(cr.system_object.prototype.cnds.OnLoadFailed, null);
- }, function (e)
- {
- self.loadFromJson = localStorage.getItem("__c2save_" + loadingFromSlot) || "";
- cr.logexport("Loaded state from WebStorage (" + self.loadFromJson.length + " bytes)");
- self.suspendDrawing = false;
- if (!self.loadFromJson.length)
- self.trigger(cr.system_object.prototype.cnds.OnLoadFailed, null);
- });
- }
- else
- {
- try {
- this.loadFromJson = localStorage.getItem("__c2save_" + loadingFromSlot) || "";
- cr.logexport("Loaded state from WebStorage (" + this.loadFromJson.length + " bytes)");
- }
- catch (e)
- {
- this.loadFromJson = "";
- }
- this.suspendDrawing = false;
- if (!self.loadFromJson.length)
- self.trigger(cr.system_object.prototype.cnds.OnLoadFailed, null);
- }
- this.loadFromSlot = "";
- this.saveToSlot = "";
- }
- if (this.loadFromJson.length)
- {
- this.ClearDeathRow();
- this.loadFromJSONString(this.loadFromJson);
- this.lastSaveJson = this.loadFromJson;
- this.trigger(cr.system_object.prototype.cnds.OnLoadComplete, null);
- this.lastSaveJson = "";
- this.loadFromJson = "";
- }
- };
- function CopyExtraObject(extra)
- {
- var p, ret = {};
- for (p in extra)
- {
- if (extra.hasOwnProperty(p))
- {
- if (extra[p] instanceof cr.ObjectSet)
- continue;
- if (extra[p] && typeof extra[p].c2userdata !== "undefined")
- continue;
- ret[p] = extra[p];
- }
- }
- return ret;
- };
- Runtime.prototype.saveToJSONString = function()
- {
- var i, len, j, lenj, type, layout, typeobj, g, c, a, v, p;
- var o = {
- "c2save": true,
- "version": 1,
- "rt": {
- "time": this.kahanTime.sum,
- "walltime": this.wallTime.sum,
- "timescale": this.timescale,
- "tickcount": this.tickcount,
- "execcount": this.execcount,
- "next_uid": this.next_uid,
- "running_layout": this.running_layout.sid,
- "start_time_offset": (Date.now() - this.start_time)
- },
- "types": {},
- "layouts": {},
- "events": {
- "groups": {},
- "cnds": {},
- "acts": {},
- "vars": {}
- }
- };
- for (i = 0, len = this.types_by_index.length; i < len; i++)
- {
- type = this.types_by_index[i];
- if (type.is_family || this.typeHasNoSaveBehavior(type))
- continue;
- typeobj = {
- "instances": []
- };
- if (cr.hasAnyOwnProperty(type.extra))
- typeobj["ex"] = CopyExtraObject(type.extra);
- for (j = 0, lenj = type.instances.length; j < lenj; j++)
- {
- typeobj["instances"].push(this.saveInstanceToJSON(type.instances[j]));
- }
- o["types"][type.sid.toString()] = typeobj;
- }
- for (i = 0, len = this.layouts_by_index.length; i < len; i++)
- {
- layout = this.layouts_by_index[i];
- o["layouts"][layout.sid.toString()] = layout.saveToJSON();
- }
- var ogroups = o["events"]["groups"];
- for (i = 0, len = this.allGroups.length; i < len; i++)
- {
- g = this.allGroups[i];
- ogroups[g.sid.toString()] = this.groups_by_name[g.group_name].group_active;
- }
- var ocnds = o["events"]["cnds"];
- for (p in this.cndsBySid)
- {
- if (this.cndsBySid.hasOwnProperty(p))
- {
- c = this.cndsBySid[p];
- if (cr.hasAnyOwnProperty(c.extra))
- ocnds[p] = { "ex": CopyExtraObject(c.extra) };
- }
- }
- var oacts = o["events"]["acts"];
- for (p in this.actsBySid)
- {
- if (this.actsBySid.hasOwnProperty(p))
- {
- a = this.actsBySid[p];
- if (cr.hasAnyOwnProperty(a.extra))
- oacts[p] = { "ex": a.extra };
- }
- }
- var ovars = o["events"]["vars"];
- for (p in this.varsBySid)
- {
- if (this.varsBySid.hasOwnProperty(p))
- {
- v = this.varsBySid[p];
- if (!v.is_constant && (!v.parent || v.is_static))
- ovars[p] = v.data;
- }
- }
- o["system"] = this.system.saveToJSON();
- return JSON.stringify(o);
- };
- Runtime.prototype.refreshUidMap = function ()
- {
- var i, len, type, j, lenj, inst;
- this.objectsByUid = {};
- for (i = 0, len = this.types_by_index.length; i < len; i++)
- {
- type = this.types_by_index[i];
- if (type.is_family)
- continue;
- for (j = 0, lenj = type.instances.length; j < lenj; j++)
- {
- inst = type.instances[j];
- this.objectsByUid[inst.uid.toString()] = inst;
- }
- }
- };
- Runtime.prototype.loadFromJSONString = function (str)
- {
- var o = JSON.parse(str);
- if (!o["c2save"])
- return; // probably not a c2 save state
- if (o["version"] > 1)
- return; // from future version of c2; assume not compatible
- var rt = o["rt"];
- this.kahanTime.reset();
- this.kahanTime.sum = rt["time"];
- this.wallTime.reset();
- this.wallTime.sum = rt["walltime"] || 0;
- this.timescale = rt["timescale"];
- this.tickcount = rt["tickcount"];
- this.execcount = rt["execcount"];
- this.start_time = Date.now() - rt["start_time_offset"];
- var layout_sid = rt["running_layout"];
- if (layout_sid !== this.running_layout.sid)
- {
- var changeToLayout = this.getLayoutBySid(layout_sid);
- if (changeToLayout)
- this.doChangeLayout(changeToLayout);
- else
- return; // layout that was saved on has gone missing (deleted?)
- }
- this.isLoadingState = true;
- var i, len, j, lenj, k, lenk, p, type, existing_insts, load_insts, inst, binst, layout, layer, g, iid, t;
- var otypes = o["types"];
- for (p in otypes)
- {
- if (otypes.hasOwnProperty(p))
- {
- type = this.getObjectTypeBySid(parseInt(p, 10));
- if (!type || type.is_family || this.typeHasNoSaveBehavior(type))
- continue;
- if (otypes[p]["ex"])
- type.extra = otypes[p]["ex"];
- else
- cr.wipe(type.extra);
- existing_insts = type.instances;
- load_insts = otypes[p]["instances"];
- for (i = 0, len = cr.min(existing_insts.length, load_insts.length); i < len; i++)
- {
- this.loadInstanceFromJSON(existing_insts[i], load_insts[i]);
- }
- for (i = load_insts.length, len = existing_insts.length; i < len; i++)
- this.DestroyInstance(existing_insts[i]);
- for (i = existing_insts.length, len = load_insts.length; i < len; i++)
- {
- layer = null;
- if (type.plugin.is_world)
- {
- layer = this.running_layout.getLayerBySid(load_insts[i]["w"]["l"]);
- if (!layer)
- continue;
- }
- inst = this.createInstanceFromInit(type.default_instance, layer, false, 0, 0, true);
- this.loadInstanceFromJSON(inst, load_insts[i]);
- }
- type.stale_iids = true;
- }
- }
- this.ClearDeathRow();
- this.refreshUidMap();
- var olayouts = o["layouts"];
- for (p in olayouts)
- {
- if (olayouts.hasOwnProperty(p))
- {
- layout = this.getLayoutBySid(parseInt(p, 10));
- if (!layout)
- continue; // must've gone missing
- layout.loadFromJSON(olayouts[p]);
- }
- }
- var ogroups = o["events"]["groups"];
- for (p in ogroups)
- {
- if (ogroups.hasOwnProperty(p))
- {
- g = this.getGroupBySid(parseInt(p, 10));
- if (g && this.groups_by_name[g.group_name])
- this.groups_by_name[g.group_name].setGroupActive(ogroups[p]);
- }
- }
- var ocnds = o["events"]["cnds"];
- for (p in ocnds)
- {
- if (ocnds.hasOwnProperty(p) && this.cndsBySid.hasOwnProperty(p))
- {
- this.cndsBySid[p].extra = ocnds[p]["ex"];
- }
- }
- var oacts = o["events"]["acts"];
- for (p in oacts)
- {
- if (oacts.hasOwnProperty(p) && this.actsBySid.hasOwnProperty(p))
- {
- this.actsBySid[p].extra = oacts[p]["ex"];
- }
- }
- var ovars = o["events"]["vars"];
- for (p in ovars)
- {
- if (ovars.hasOwnProperty(p) && this.varsBySid.hasOwnProperty(p))
- {
- this.varsBySid[p].data = ovars[p];
- }
- }
- this.next_uid = rt["next_uid"];
- this.isLoadingState = false;
- this.system.loadFromJSON(o["system"]);
- for (i = 0, len = this.types_by_index.length; i < len; i++)
- {
- type = this.types_by_index[i];
- if (type.is_family)
- continue;
- for (j = 0, lenj = type.instances.length; j < lenj; j++)
- {
- inst = type.instances[j];
- if (type.is_contained)
- {
- iid = inst.get_iid();
- inst.siblings.length = 0;
- for (k = 0, lenk = type.container.length; k < lenk; k++)
- {
- t = type.container[k];
- if (type === t)
- continue;
- ;
- inst.siblings.push(t.instances[iid]);
- }
- }
- if (inst.afterLoad)
- inst.afterLoad();
- if (inst.behavior_insts)
- {
- for (k = 0, lenk = inst.behavior_insts.length; k < lenk; k++)
- {
- binst = inst.behavior_insts[k];
- if (binst.afterLoad)
- binst.afterLoad();
- }
- }
- }
- }
- this.redraw = true;
- };
- Runtime.prototype.saveInstanceToJSON = function(inst, state_only)
- {
- var i, len, world, behinst, et;
- var type = inst.type;
- var plugin = type.plugin;
- var o = {};
- if (state_only)
- o["c2"] = true; // mark as known json data from Construct 2
- else
- o["uid"] = inst.uid;
- if (cr.hasAnyOwnProperty(inst.extra))
- o["ex"] = CopyExtraObject(inst.extra);
- if (inst.instance_vars && inst.instance_vars.length)
- {
- o["ivs"] = {};
- for (i = 0, len = inst.instance_vars.length; i < len; i++)
- {
- o["ivs"][inst.type.instvar_sids[i].toString()] = inst.instance_vars[i];
- }
- }
- if (plugin.is_world)
- {
- world = {
- "x": inst.x,
- "y": inst.y,
- "w": inst.width,
- "h": inst.height,
- "l": inst.layer.sid,
- "zi": inst.get_zindex()
- };
- if (inst.angle !== 0)
- world["a"] = inst.angle;
- if (inst.opacity !== 1)
- world["o"] = inst.opacity;
- if (inst.hotspotX !== 0.5)
- world["hX"] = inst.hotspotX;
- if (inst.hotspotY !== 0.5)
- world["hY"] = inst.hotspotY;
- if (inst.blend_mode !== 0)
- world["bm"] = inst.blend_mode;
- if (!inst.visible)
- world["v"] = inst.visible;
- if (!inst.collisionsEnabled)
- world["ce"] = inst.collisionsEnabled;
- if (inst.my_timescale !== -1)
- world["mts"] = inst.my_timescale;
- if (type.effect_types.length)
- {
- world["fx"] = [];
- for (i = 0, len = type.effect_types.length; i < len; i++)
- {
- et = type.effect_types[i];
- world["fx"].push({"name": et.name,
- "active": inst.active_effect_flags[et.index],
- "params": inst.effect_params[et.index] });
- }
- }
- o["w"] = world;
- }
- if (inst.behavior_insts && inst.behavior_insts.length)
- {
- o["behs"] = {};
- for (i = 0, len = inst.behavior_insts.length; i < len; i++)
- {
- behinst = inst.behavior_insts[i];
- if (behinst.saveToJSON)
- o["behs"][behinst.type.sid.toString()] = behinst.saveToJSON();
- }
- }
- if (inst.saveToJSON)
- o["data"] = inst.saveToJSON();
- return o;
- };
- Runtime.prototype.getInstanceVarIndexBySid = function (type, sid_)
- {
- var i, len;
- for (i = 0, len = type.instvar_sids.length; i < len; i++)
- {
- if (type.instvar_sids[i] === sid_)
- return i;
- }
- return -1;
- };
- Runtime.prototype.getBehaviorIndexBySid = function (inst, sid_)
- {
- var i, len;
- for (i = 0, len = inst.behavior_insts.length; i < len; i++)
- {
- if (inst.behavior_insts[i].type.sid === sid_)
- return i;
- }
- return -1;
- };
- Runtime.prototype.loadInstanceFromJSON = function(inst, o, state_only)
- {
- var p, i, len, iv, oivs, world, fxindex, obehs, behindex;
- var oldlayer;
- var type = inst.type;
- var plugin = type.plugin;
- if (state_only)
- {
- if (!o["c2"])
- return;
- }
- else
- inst.uid = o["uid"];
- if (o["ex"])
- inst.extra = o["ex"];
- else
- cr.wipe(inst.extra);
- oivs = o["ivs"];
- if (oivs)
- {
- for (p in oivs)
- {
- if (oivs.hasOwnProperty(p))
- {
- iv = this.getInstanceVarIndexBySid(type, parseInt(p, 10));
- if (iv < 0 || iv >= inst.instance_vars.length)
- continue; // must've gone missing
- inst.instance_vars[iv] = oivs[p];
- }
- }
- }
- if (plugin.is_world)
- {
- world = o["w"];
- if (inst.layer.sid !== world["l"])
- {
- oldlayer = inst.layer;
- inst.layer = this.running_layout.getLayerBySid(world["l"]);
- if (inst.layer)
- {
- oldlayer.removeFromInstanceList(inst, true);
- inst.layer.appendToInstanceList(inst, true);
- inst.set_bbox_changed();
- inst.layer.setZIndicesStaleFrom(0);
- }
- else
- {
- inst.layer = oldlayer;
- if (!state_only)
- this.DestroyInstance(inst);
- }
- }
- inst.x = world["x"];
- inst.y = world["y"];
- inst.width = world["w"];
- inst.height = world["h"];
- inst.zindex = world["zi"];
- inst.angle = world.hasOwnProperty("a") ? world["a"] : 0;
- inst.opacity = world.hasOwnProperty("o") ? world["o"] : 1;
- inst.hotspotX = world.hasOwnProperty("hX") ? world["hX"] : 0.5;
- inst.hotspotY = world.hasOwnProperty("hY") ? world["hY"] : 0.5;
- inst.visible = world.hasOwnProperty("v") ? world["v"] : true;
- inst.collisionsEnabled = world.hasOwnProperty("ce") ? world["ce"] : true;
- inst.my_timescale = world.hasOwnProperty("mts") ? world["mts"] : -1;
- inst.blend_mode = world.hasOwnProperty("bm") ? world["bm"] : 0;;
- inst.compositeOp = cr.effectToCompositeOp(inst.blend_mode);
- if (this.gl)
- cr.setGLBlend(inst, inst.blend_mode, this.gl);
- inst.set_bbox_changed();
- if (world.hasOwnProperty("fx"))
- {
- for (i = 0, len = world["fx"].length; i < len; i++)
- {
- fxindex = type.getEffectIndexByName(world["fx"][i]["name"]);
- if (fxindex < 0)
- continue; // must've gone missing
- inst.active_effect_flags[fxindex] = world["fx"][i]["active"];
- inst.effect_params[fxindex] = world["fx"][i]["params"];
- }
- }
- inst.updateActiveEffects();
- }
- obehs = o["behs"];
- if (obehs)
- {
- for (p in obehs)
- {
- if (obehs.hasOwnProperty(p))
- {
- behindex = this.getBehaviorIndexBySid(inst, parseInt(p, 10));
- if (behindex < 0)
- continue; // must've gone missing
- inst.behavior_insts[behindex].loadFromJSON(obehs[p]);
- }
- }
- }
- if (o["data"])
- inst.loadFromJSON(o["data"]);
- };
- cr.runtime = Runtime;
- cr.createRuntime = function (canvasid)
- {
- return new Runtime(document.getElementById(canvasid));
- };
- cr.createDCRuntime = function (w, h)
- {
- return new Runtime({ "dc": true, "width": w, "height": h });
- };
- window["cr_createRuntime"] = cr.createRuntime;
- window["cr_createDCRuntime"] = cr.createDCRuntime;
- window["createCocoonJSRuntime"] = function ()
- {
- window["c2cocoonjs"] = true;
- var canvas = document.createElement("screencanvas") || document.createElement("canvas");
- canvas.screencanvas = true;
- document.body.appendChild(canvas);
- var rt = new Runtime(canvas);
- window["c2runtime"] = rt;
- window.addEventListener("orientationchange", function () {
- window["c2runtime"]["setSize"](window.innerWidth, window.innerHeight);
- });
- window["c2runtime"]["setSize"](window.innerWidth, window.innerHeight);
- return rt;
- };
- window["createEjectaRuntime"] = function ()
- {
- var canvas = document.getElementById("canvas");
- var rt = new Runtime(canvas);
- window["c2runtime"] = rt;
- window["c2runtime"]["setSize"](window.innerWidth, window.innerHeight);
- return rt;
- };
- }());
- window["cr_getC2Runtime"] = function()
- {
- var canvas = document.getElementById("c2canvas");
- if (canvas)
- return canvas["c2runtime"];
- else if (window["c2runtime"])
- return window["c2runtime"];
- else
- return null;
- }
- window["cr_getSnapshot"] = function (format_, quality_)
- {
- var runtime = window["cr_getC2Runtime"]();
- if (runtime)
- runtime.doCanvasSnapshot(format_, quality_);
- }
- window["cr_sizeCanvas"] = function(w, h)
- {
- if (w === 0 || h === 0)
- return;
- var runtime = window["cr_getC2Runtime"]();
- if (runtime)
- runtime["setSize"](w, h);
- }
- window["cr_setSuspended"] = function(s)
- {
- var runtime = window["cr_getC2Runtime"]();
- if (runtime)
- runtime["setSuspended"](s);
- }
- ;
- (function()
- {
- function Layout(runtime, m)
- {
- this.runtime = runtime;
- this.event_sheet = null;
- this.scrollX = (this.runtime.original_width / 2);
- this.scrollY = (this.runtime.original_height / 2);
- this.scale = 1.0;
- this.angle = 0;
- this.first_visit = true;
- this.name = m[0];
- this.width = m[1];
- this.height = m[2];
- this.unbounded_scrolling = m[3];
- this.sheetname = m[4];
- this.sid = m[5];
- var lm = m[6];
- var i, len;
- this.layers = [];
- this.initial_types = [];
- for (i = 0, len = lm.length; i < len; i++)
- {
- var layer = new cr.layer(this, lm[i]);
- layer.number = i;
- cr.seal(layer);
- this.layers.push(layer);
- }
- var im = m[7];
- this.initial_nonworld = [];
- for (i = 0, len = im.length; i < len; i++)
- {
- var inst = im[i];
- var type = this.runtime.types_by_index[inst[1]];
- ;
- if (!type.default_instance)
- type.default_instance = inst;
- this.initial_nonworld.push(inst);
- if (this.initial_types.indexOf(type) === -1)
- this.initial_types.push(type);
- }
- this.effect_types = [];
- this.active_effect_types = [];
- this.effect_params = [];
- for (i = 0, len = m[8].length; i < len; i++)
- {
- this.effect_types.push({
- id: m[8][i][0],
- name: m[8][i][1],
- shaderindex: -1,
- active: true,
- index: i
- });
- this.effect_params.push(m[8][i][2].slice(0));
- }
- this.updateActiveEffects();
- this.rcTex = new cr.rect(0, 0, 1, 1);
- this.rcTex2 = new cr.rect(0, 0, 1, 1);
- this.persist_data = {};
- };
- Layout.prototype.saveObjectToPersist = function (inst)
- {
- var sidStr = inst.type.sid.toString();
- if (!this.persist_data.hasOwnProperty(sidStr))
- this.persist_data[sidStr] = [];
- var type_persist = this.persist_data[sidStr];
- type_persist.push(this.runtime.saveInstanceToJSON(inst));
- };
- Layout.prototype.hasOpaqueBottomLayer = function ()
- {
- var layer = this.layers[0];
- return !layer.transparent && layer.opacity === 1.0 && !layer.forceOwnTexture && layer.visible;
- };
- Layout.prototype.updateActiveEffects = function ()
- {
- this.active_effect_types.length = 0;
- var i, len, et;
- for (i = 0, len = this.effect_types.length; i < len; i++)
- {
- et = this.effect_types[i];
- if (et.active)
- this.active_effect_types.push(et);
- }
- };
- Layout.prototype.getEffectByName = function (name_)
- {
- var i, len, et;
- for (i = 0, len = this.effect_types.length; i < len; i++)
- {
- et = this.effect_types[i];
- if (et.name === name_)
- return et;
- }
- return null;
- };
- var created_instances = [];
- function sort_by_zindex(a, b)
- {
- return a.zindex - b.zindex;
- };
- var first_layout = true;
- Layout.prototype.startRunning = function ()
- {
- if (this.sheetname)
- {
- this.event_sheet = this.runtime.eventsheets[this.sheetname];
- ;
- this.event_sheet.updateDeepIncludes();
- }
- this.runtime.running_layout = this;
- this.scrollX = (this.runtime.original_width / 2);
- this.scrollY = (this.runtime.original_height / 2);
- var i, k, len, lenk, type, type_instances, inst, iid, t, s, p, q, type_data, layer;
- for (i = 0, len = this.runtime.types_by_index.length; i < len; i++)
- {
- type = this.runtime.types_by_index[i];
- if (type.is_family)
- continue; // instances are only transferred for their real type
- type_instances = type.instances;
- for (k = 0, lenk = type_instances.length; k < lenk; k++)
- {
- inst = type_instances[k];
- if (inst.layer)
- {
- var num = inst.layer.number;
- if (num >= this.layers.length)
- num = this.layers.length - 1;
- inst.layer = this.layers[num];
- if (inst.layer.instances.indexOf(inst) === -1)
- inst.layer.instances.push(inst);
- inst.layer.zindices_stale = true;
- }
- }
- }
- if (!first_layout)
- {
- for (i = 0, len = this.layers.length; i < len; ++i)
- {
- this.layers[i].instances.sort(sort_by_zindex);
- }
- }
- var layer;
- created_instances.length = 0;
- this.boundScrolling();
- for (i = 0, len = this.layers.length; i < len; i++)
- {
- layer = this.layers[i];
- layer.createInitialInstances(); // fills created_instances
- layer.updateViewport(null);
- }
- var uids_changed = false;
- if (!this.first_visit)
- {
- for (p in this.persist_data)
- {
- if (this.persist_data.hasOwnProperty(p))
- {
- type = this.runtime.getObjectTypeBySid(parseInt(p, 10));
- if (!type || type.is_family || !this.runtime.typeHasPersistBehavior(type))
- continue;
- type_data = this.persist_data[p];
- for (i = 0, len = type_data.length; i < len; i++)
- {
- layer = null;
- if (type.plugin.is_world)
- {
- layer = this.getLayerBySid(type_data[i]["w"]["l"]);
- if (!layer)
- continue;
- }
- inst = this.runtime.createInstanceFromInit(type.default_instance, layer, false, 0, 0, true);
- this.runtime.loadInstanceFromJSON(inst, type_data[i]);
- uids_changed = true;
- created_instances.push(inst);
- }
- type_data.length = 0;
- }
- }
- for (i = 0, len = this.layers.length; i < len; i++)
- {
- this.layers[i].instances.sort(sort_by_zindex);
- this.layers[i].zindices_stale = true; // in case of duplicates/holes
- }
- }
- if (uids_changed)
- {
- this.runtime.ClearDeathRow();
- this.runtime.refreshUidMap();
- }
- for (i = 0; i < created_instances.length; i++)
- {
- inst = created_instances[i];
- if (!inst.type.is_contained)
- continue;
- iid = inst.get_iid();
- for (k = 0, lenk = inst.type.container.length; k < lenk; k++)
- {
- t = inst.type.container[k];
- if (inst.type === t)
- continue;
- if (t.instances.length > iid)
- inst.siblings.push(t.instances[iid]);
- else
- {
- if (!t.default_instance)
- {
- }
- else
- {
- s = this.runtime.createInstanceFromInit(t.default_instance, inst.layer, true, inst.x, inst.y, true);
- this.runtime.ClearDeathRow();
- t.updateIIDs();
- inst.siblings.push(s);
- created_instances.push(s); // come back around and link up its own instances too
- }
- }
- }
- }
- for (i = 0, len = this.initial_nonworld.length; i < len; i++)
- {
- inst = this.runtime.createInstanceFromInit(this.initial_nonworld[i], null, true);
- ;
- }
- this.runtime.changelayout = null;
- this.runtime.ClearDeathRow();
- if (this.runtime.ctx && !this.runtime.isDomFree)
- {
- for (i = 0, len = this.runtime.types_by_index.length; i < len; i++)
- {
- t = this.runtime.types_by_index[i];
- if (t.is_family || !t.instances.length || !t.preloadCanvas2D)
- continue;
- t.preloadCanvas2D(this.runtime.ctx);
- }
- }
- /*
- if (this.runtime.glwrap)
- {
- console.log("Estimated VRAM at layout start: " + this.runtime.glwrap.textureCount() + " textures, approx. " + Math.round(this.runtime.glwrap.estimateVRAM() / 1024) + " kb");
- }
- */
- for (i = 0, len = created_instances.length; i < len; i++)
- {
- inst = created_instances[i];
- this.runtime.trigger(Object.getPrototypeOf(inst.type.plugin).cnds.OnCreated, inst);
- }
- created_instances.length = 0;
- this.runtime.trigger(cr.system_object.prototype.cnds.OnLayoutStart, null);
- this.first_visit = false;
- };
- Layout.prototype.createGlobalNonWorlds = function ()
- {
- var i, k, len, initial_inst, inst, type;
- for (i = 0, k = 0, len = this.initial_nonworld.length; i < len; i++)
- {
- initial_inst = this.initial_nonworld[i];
- type = this.runtime.types_by_index[initial_inst[1]];
- if (type.global)
- {
- if (!type.is_contained)
- {
- inst = this.runtime.createInstanceFromInit(initial_inst, null, true);
- }
- }
- else
- {
- this.initial_nonworld[k] = initial_inst;
- k++;
- }
- }
- this.initial_nonworld.length = k;
- };
- Layout.prototype.stopRunning = function ()
- {
- ;
- /*
- if (this.runtime.glwrap)
- {
- console.log("Estimated VRAM at layout end: " + this.runtime.glwrap.textureCount() + " textures, approx. " + Math.round(this.runtime.glwrap.estimateVRAM() / 1024) + " kb");
- }
- */
- this.runtime.trigger(cr.system_object.prototype.cnds.OnLayoutEnd, null);
- this.runtime.system.waits.length = 0;
- var i, leni, j, lenj;
- var layer_instances, inst, type;
- if (!this.first_visit)
- {
- for (i = 0, leni = this.layers.length; i < leni; i++)
- {
- this.layers[i].updateZIndices();
- layer_instances = this.layers[i].instances;
- for (j = 0, lenj = layer_instances.length; j < lenj; j++)
- {
- inst = layer_instances[j];
- if (!inst.type.global)
- {
- if (this.runtime.typeHasPersistBehavior(inst.type))
- this.saveObjectToPersist(inst);
- }
- }
- }
- }
- for (i = 0, leni = this.layers.length; i < leni; i++)
- {
- layer_instances = this.layers[i].instances;
- for (j = 0, lenj = layer_instances.length; j < lenj; j++)
- {
- inst = layer_instances[j];
- if (!inst.type.global)
- {
- this.runtime.DestroyInstance(inst);
- }
- }
- this.runtime.ClearDeathRow();
- layer_instances.length = 0;
- this.layers[i].zindices_stale = true;
- }
- for (i = 0, leni = this.runtime.types_by_index.length; i < leni; i++)
- {
- type = this.runtime.types_by_index[i];
- if (type.global || type.plugin.is_world || type.plugin.singleglobal || type.is_family)
- continue;
- for (j = 0, lenj = type.instances.length; j < lenj; j++)
- this.runtime.DestroyInstance(type.instances[j]);
- this.runtime.ClearDeathRow();
- }
- first_layout = false;
- };
- var temp_rect = new cr.rect(0, 0, 0, 0);
- Layout.prototype.recreateInitialObjects = function (type, x1, y1, x2, y2)
- {
- temp_rect.set(x1, y1, x2, y2);
- var i, len;
- for (i = 0, len = this.layers.length; i < len; i++)
- {
- this.layers[i].recreateInitialObjects(type, temp_rect);
- }
- };
- Layout.prototype.draw = function (ctx)
- {
- var layout_canvas;
- var layout_ctx = ctx;
- var ctx_changed = false;
- var render_offscreen = !this.runtime.fullscreenScalingQuality;
- if (render_offscreen)
- {
- if (!this.runtime.layout_canvas)
- {
- this.runtime.layout_canvas = document.createElement("canvas");
- layout_canvas = this.runtime.layout_canvas;
- layout_canvas.width = this.runtime.draw_width;
- layout_canvas.height = this.runtime.draw_height;
- this.runtime.layout_ctx = layout_canvas.getContext("2d");
- ctx_changed = true;
- }
- layout_canvas = this.runtime.layout_canvas;
- layout_ctx = this.runtime.layout_ctx;
- if (layout_canvas.width !== this.runtime.draw_width)
- {
- layout_canvas.width = this.runtime.draw_width;
- ctx_changed = true;
- }
- if (layout_canvas.height !== this.runtime.draw_height)
- {
- layout_canvas.height = this.runtime.draw_height;
- ctx_changed = true;
- }
- if (ctx_changed)
- {
- layout_ctx["webkitImageSmoothingEnabled"] = this.runtime.linearSampling;
- layout_ctx["mozImageSmoothingEnabled"] = this.runtime.linearSampling;
- layout_ctx["msImageSmoothingEnabled"] = this.runtime.linearSampling;
- layout_ctx["imageSmoothingEnabled"] = this.runtime.linearSampling;
- }
- }
- layout_ctx.globalAlpha = 1;
- layout_ctx.globalCompositeOperation = "source-over";
- if (this.runtime.alphaBackground && !this.hasOpaqueBottomLayer())
- layout_ctx.clearRect(0, 0, this.runtime.draw_width, this.runtime.draw_height);
- var i, len, l;
- for (i = 0, len = this.layers.length; i < len; i++)
- {
- l = this.layers[i];
- if (l.visible && l.opacity > 0 && l.blend_mode !== 11 && (l.instances.length || !l.transparent))
- l.draw(layout_ctx);
- else
- l.updateViewport(null); // even if not drawing, keep viewport up to date
- }
- if (render_offscreen)
- {
- ctx.drawImage(layout_canvas, 0, 0, this.runtime.width, this.runtime.height);
- }
- };
- Layout.prototype.drawGL = function (glw)
- {
- var render_to_texture = (this.active_effect_types.length > 0 ||
- this.runtime.uses_background_blending ||
- !this.runtime.fullscreenScalingQuality);
- if (render_to_texture)
- {
- if (!this.runtime.layout_tex)
- {
- this.runtime.layout_tex = glw.createEmptyTexture(this.runtime.draw_width, this.runtime.draw_height, this.runtime.linearSampling);
- }
- if (this.runtime.layout_tex.c2width !== this.runtime.draw_width || this.runtime.layout_tex.c2height !== this.runtime.draw_height)
- {
- glw.deleteTexture(this.runtime.layout_tex);
- this.runtime.layout_tex = glw.createEmptyTexture(this.runtime.draw_width, this.runtime.draw_height, this.runtime.linearSampling);
- }
- glw.setRenderingToTexture(this.runtime.layout_tex);
- if (!this.runtime.fullscreenScalingQuality)
- {
- glw.setSize(this.runtime.draw_width, this.runtime.draw_height);
- }
- }
- else
- {
- if (this.runtime.layout_tex)
- {
- glw.setRenderingToTexture(null);
- glw.deleteTexture(this.runtime.layout_tex);
- this.runtime.layout_tex = null;
- }
- }
- if (this.runtime.alphaBackground && !this.hasOpaqueBottomLayer())
- glw.clear(0, 0, 0, 0);
- var i, len, l;
- for (i = 0, len = this.layers.length; i < len; i++)
- {
- l = this.layers[i];
- if (l.visible && l.opacity > 0 && (l.instances.length || !l.transparent))
- l.drawGL(glw);
- else
- l.updateViewport(null); // even if not drawing, keep viewport up to date
- }
- if (render_to_texture)
- {
- if (this.active_effect_types.length === 0 ||
- (this.active_effect_types.length === 1 && this.runtime.fullscreenScalingQuality))
- {
- if (this.active_effect_types.length === 1)
- {
- var etindex = this.active_effect_types[0].index;
- glw.switchProgram(this.active_effect_types[0].shaderindex);
- glw.setProgramParameters(null, // backTex
- 1.0 / this.runtime.draw_width, // pixelWidth
- 1.0 / this.runtime.draw_height, // pixelHeight
- 0.0, 0.0, // destStart
- 1.0, 1.0, // destEnd
- this.scale, // layerScale
- this.angle, // layerAngle
- 0.0, 0.0, // viewOrigin
- this.runtime.draw_width / 2, this.runtime.draw_height / 2, // scrollPos
- this.effect_params[etindex]); // fx parameters
- if (glw.programIsAnimated(this.active_effect_types[0].shaderindex))
- this.runtime.redraw = true;
- }
- else
- glw.switchProgram(0);
- if (!this.runtime.fullscreenScalingQuality)
- {
- glw.setSize(this.runtime.width, this.runtime.height);
- }
- glw.setRenderingToTexture(null); // to backbuffer
- glw.setOpacity(1);
- glw.setTexture(this.runtime.layout_tex);
- glw.setAlphaBlend();
- glw.resetModelView();
- glw.updateModelView();
- var halfw = this.runtime.width / 2;
- var halfh = this.runtime.height / 2;
- glw.quad(-halfw, halfh, halfw, halfh, halfw, -halfh, -halfw, -halfh);
- glw.setTexture(null);
- }
- else
- {
- this.renderEffectChain(glw, null, null, null);
- }
- }
- };
- Layout.prototype.getRenderTarget = function()
- {
- return (this.active_effect_types.length > 0 ||
- this.runtime.uses_background_blending ||
- !this.runtime.fullscreenScalingQuality) ? this.runtime.layout_tex : null;
- };
- Layout.prototype.getMinLayerScale = function ()
- {
- var m = this.layers[0].getScale();
- var i, len, l;
- for (i = 1, len = this.layers.length; i < len; i++)
- {
- l = this.layers[i];
- if (l.parallaxX === 0 && l.parallaxY === 0)
- continue;
- if (l.getScale() < m)
- m = l.getScale();
- }
- return m;
- };
- Layout.prototype.scrollToX = function (x)
- {
- if (!this.unbounded_scrolling)
- {
- var widthBoundary = (this.runtime.draw_width * (1 / this.getMinLayerScale()) / 2);
- if (x > this.width - widthBoundary)
- x = this.width - widthBoundary;
- if (x < widthBoundary)
- x = widthBoundary;
- }
- if (this.scrollX !== x)
- {
- this.scrollX = x;
- this.runtime.redraw = true;
- }
- };
- Layout.prototype.scrollToY = function (y)
- {
- if (!this.unbounded_scrolling)
- {
- var heightBoundary = (this.runtime.draw_height * (1 / this.getMinLayerScale()) / 2);
- if (y > this.height - heightBoundary)
- y = this.height - heightBoundary;
- if (y < heightBoundary)
- y = heightBoundary;
- }
- if (this.scrollY !== y)
- {
- this.scrollY = y;
- this.runtime.redraw = true;
- }
- };
- Layout.prototype.boundScrolling = function ()
- {
- this.scrollToX(this.scrollX);
- this.scrollToY(this.scrollY);
- };
- Layout.prototype.renderEffectChain = function (glw, layer, inst, rendertarget)
- {
- var active_effect_types = inst ?
- inst.active_effect_types :
- layer ?
- layer.active_effect_types :
- this.active_effect_types;
- var layerScale = 1, layerAngle = 0, viewOriginLeft = 0, viewOriginTop = 0, viewOriginRight = this.runtime.draw_width, viewOriginBottom = this.runtime.draw_height;
- if (inst)
- {
- layerScale = inst.layer.getScale();
- layerAngle = inst.layer.getAngle();
- viewOriginLeft = inst.layer.viewLeft;
- viewOriginTop = inst.layer.viewTop;
- viewOriginRight = inst.layer.viewRight;
- viewOriginBottom = inst.layer.viewBottom;
- }
- else if (layer)
- {
- layerScale = layer.getScale();
- layerAngle = layer.getAngle();
- viewOriginLeft = layer.viewLeft;
- viewOriginTop = layer.viewTop;
- viewOriginRight = layer.viewRight;
- viewOriginBottom = layer.viewBottom;
- }
- var fx_tex = this.runtime.fx_tex;
- var i, len, last, temp, fx_index = 0, other_fx_index = 1;
- var y, h;
- var windowWidth = this.runtime.draw_width;
- var windowHeight = this.runtime.draw_height;
- var halfw = windowWidth / 2;
- var halfh = windowHeight / 2;
- var rcTex = layer ? layer.rcTex : this.rcTex;
- var rcTex2 = layer ? layer.rcTex2 : this.rcTex2;
- var screenleft = 0, clearleft = 0;
- var screentop = 0, cleartop = 0;
- var screenright = windowWidth, clearright = windowWidth;
- var screenbottom = windowHeight, clearbottom = windowHeight;
- var boxExtendHorizontal = 0;
- var boxExtendVertical = 0;
- var inst_layer_angle = inst ? inst.layer.getAngle() : 0;
- if (inst)
- {
- for (i = 0, len = active_effect_types.length; i < len; i++)
- {
- boxExtendHorizontal += glw.getProgramBoxExtendHorizontal(active_effect_types[i].shaderindex);
- boxExtendVertical += glw.getProgramBoxExtendVertical(active_effect_types[i].shaderindex);
- }
- var bbox = inst.bbox;
- screenleft = layer.layerToCanvas(bbox.left, bbox.top, true, true);
- screentop = layer.layerToCanvas(bbox.left, bbox.top, false, true);
- screenright = layer.layerToCanvas(bbox.right, bbox.bottom, true, true);
- screenbottom = layer.layerToCanvas(bbox.right, bbox.bottom, false, true);
- if (inst_layer_angle !== 0)
- {
- var screentrx = layer.layerToCanvas(bbox.right, bbox.top, true, true);
- var screentry = layer.layerToCanvas(bbox.right, bbox.top, false, true);
- var screenblx = layer.layerToCanvas(bbox.left, bbox.bottom, true, true);
- var screenbly = layer.layerToCanvas(bbox.left, bbox.bottom, false, true);
- temp = Math.min(screenleft, screenright, screentrx, screenblx);
- screenright = Math.max(screenleft, screenright, screentrx, screenblx);
- screenleft = temp;
- temp = Math.min(screentop, screenbottom, screentry, screenbly);
- screenbottom = Math.max(screentop, screenbottom, screentry, screenbly);
- screentop = temp;
- }
- screenleft -= boxExtendHorizontal;
- screentop -= boxExtendVertical;
- screenright += boxExtendHorizontal;
- screenbottom += boxExtendVertical;
- rcTex2.left = screenleft / windowWidth;
- rcTex2.top = 1 - screentop / windowHeight;
- rcTex2.right = screenright / windowWidth;
- rcTex2.bottom = 1 - screenbottom / windowHeight;
- clearleft = screenleft = cr.floor(screenleft);
- cleartop = screentop = cr.floor(screentop);
- clearright = screenright = cr.ceil(screenright);
- clearbottom = screenbottom = cr.ceil(screenbottom);
- clearleft -= boxExtendHorizontal;
- cleartop -= boxExtendVertical;
- clearright += boxExtendHorizontal;
- clearbottom += boxExtendVertical;
- if (screenleft < 0) screenleft = 0;
- if (screentop < 0) screentop = 0;
- if (screenright > windowWidth) screenright = windowWidth;
- if (screenbottom > windowHeight) screenbottom = windowHeight;
- if (clearleft < 0) clearleft = 0;
- if (cleartop < 0) cleartop = 0;
- if (clearright > windowWidth) clearright = windowWidth;
- if (clearbottom > windowHeight) clearbottom = windowHeight;
- rcTex.left = screenleft / windowWidth;
- rcTex.top = 1 - screentop / windowHeight;
- rcTex.right = screenright / windowWidth;
- rcTex.bottom = 1 - screenbottom / windowHeight;
- }
- else
- {
- rcTex.left = rcTex2.left = 0;
- rcTex.top = rcTex2.top = 0;
- rcTex.right = rcTex2.right = 1;
- rcTex.bottom = rcTex2.bottom = 1;
- }
- var pre_draw = (inst && (((inst.angle || inst_layer_angle) && glw.programUsesDest(active_effect_types[0].shaderindex)) || boxExtendHorizontal !== 0 || boxExtendVertical !== 0 || inst.opacity !== 1 || inst.type.plugin.must_predraw)) || (layer && !inst && layer.opacity !== 1);
- glw.setAlphaBlend();
- if (pre_draw)
- {
- if (!fx_tex[fx_index])
- {
- fx_tex[fx_index] = glw.createEmptyTexture(windowWidth, windowHeight, this.runtime.linearSampling);
- }
- if (fx_tex[fx_index].c2width !== windowWidth || fx_tex[fx_index].c2height !== windowHeight)
- {
- glw.deleteTexture(fx_tex[fx_index]);
- fx_tex[fx_index] = glw.createEmptyTexture(windowWidth, windowHeight, this.runtime.linearSampling);
- }
- glw.switchProgram(0);
- glw.setRenderingToTexture(fx_tex[fx_index]);
- h = clearbottom - cleartop;
- y = (windowHeight - cleartop) - h;
- glw.clearRect(clearleft, y, clearright - clearleft, h);
- if (inst)
- {
- inst.drawGL(glw);
- }
- else
- {
- glw.setTexture(this.runtime.layer_tex);
- glw.setOpacity(layer.opacity);
- glw.resetModelView();
- glw.translate(-halfw, -halfh);
- glw.updateModelView();
- glw.quadTex(screenleft, screenbottom, screenright, screenbottom, screenright, screentop, screenleft, screentop, rcTex);
- }
- rcTex2.left = rcTex2.top = 0;
- rcTex2.right = rcTex2.bottom = 1;
- if (inst)
- {
- temp = rcTex.top;
- rcTex.top = rcTex.bottom;
- rcTex.bottom = temp;
- }
- fx_index = 1;
- other_fx_index = 0;
- }
- glw.setOpacity(1);
- var last = active_effect_types.length - 1;
- var post_draw = glw.programUsesCrossSampling(active_effect_types[last].shaderindex) ||
- (!layer && !inst && !this.runtime.fullscreenScalingQuality);
- var etindex = 0;
- for (i = 0, len = active_effect_types.length; i < len; i++)
- {
- if (!fx_tex[fx_index])
- {
- fx_tex[fx_index] = glw.createEmptyTexture(windowWidth, windowHeight, this.runtime.linearSampling);
- }
- if (fx_tex[fx_index].c2width !== windowWidth || fx_tex[fx_index].c2height !== windowHeight)
- {
- glw.deleteTexture(fx_tex[fx_index]);
- fx_tex[fx_index] = glw.createEmptyTexture(windowWidth, windowHeight, this.runtime.linearSampling);
- }
- glw.switchProgram(active_effect_types[i].shaderindex);
- etindex = active_effect_types[i].index;
- if (glw.programIsAnimated(active_effect_types[i].shaderindex))
- this.runtime.redraw = true;
- if (i == 0 && !pre_draw)
- {
- glw.setRenderingToTexture(fx_tex[fx_index]);
- h = clearbottom - cleartop;
- y = (windowHeight - cleartop) - h;
- glw.clearRect(clearleft, y, clearright - clearleft, h);
- if (inst)
- {
- glw.setProgramParameters(rendertarget, // backTex
- 1.0 / inst.width, // pixelWidth
- 1.0 / inst.height, // pixelHeight
- rcTex2.left, rcTex2.top, // destStart
- rcTex2.right, rcTex2.bottom, // destEnd
- layerScale,
- layerAngle,
- viewOriginLeft, viewOriginTop,
- (viewOriginLeft + viewOriginRight) / 2, (viewOriginTop + viewOriginBottom) / 2,
- inst.effect_params[etindex]); // fx params
- inst.drawGL(glw);
- }
- else
- {
- glw.setProgramParameters(rendertarget, // backTex
- 1.0 / windowWidth, // pixelWidth
- 1.0 / windowHeight, // pixelHeight
- 0.0, 0.0, // destStart
- 1.0, 1.0, // destEnd
- layerScale,
- layerAngle,
- viewOriginLeft, viewOriginTop,
- (viewOriginLeft + viewOriginRight) / 2, (viewOriginTop + viewOriginBottom) / 2,
- layer ? // fx params
- layer.effect_params[etindex] :
- this.effect_params[etindex]);
- glw.setTexture(layer ? this.runtime.layer_tex : this.runtime.layout_tex);
- glw.resetModelView();
- glw.translate(-halfw, -halfh);
- glw.updateModelView();
- glw.quadTex(screenleft, screenbottom, screenright, screenbottom, screenright, screentop, screenleft, screentop, rcTex);
- }
- rcTex2.left = rcTex2.top = 0;
- rcTex2.right = rcTex2.bottom = 1;
- if (inst && !post_draw)
- {
- temp = screenbottom;
- screenbottom = screentop;
- screentop = temp;
- }
- }
- else
- {
- glw.setProgramParameters(rendertarget, // backTex
- 1.0 / windowWidth, // pixelWidth
- 1.0 / windowHeight, // pixelHeight
- rcTex2.left, rcTex2.top, // destStart
- rcTex2.right, rcTex2.bottom, // destEnd
- layerScale,
- layerAngle,
- viewOriginLeft, viewOriginTop,
- (viewOriginLeft + viewOriginRight) / 2, (viewOriginTop + viewOriginBottom) / 2,
- inst ? // fx params
- inst.effect_params[etindex] :
- layer ?
- layer.effect_params[etindex] :
- this.effect_params[etindex]);
- glw.setTexture(null);
- if (i === last && !post_draw)
- {
- if (inst)
- glw.setBlend(inst.srcBlend, inst.destBlend);
- else if (layer)
- glw.setBlend(layer.srcBlend, layer.destBlend);
- glw.setRenderingToTexture(rendertarget);
- }
- else
- {
- glw.setRenderingToTexture(fx_tex[fx_index]);
- h = clearbottom - cleartop;
- y = (windowHeight - cleartop) - h;
- glw.clearRect(clearleft, y, clearright - clearleft, h);
- }
- glw.setTexture(fx_tex[other_fx_index]);
- glw.resetModelView();
- glw.translate(-halfw, -halfh);
- glw.updateModelView();
- glw.quadTex(screenleft, screenbottom, screenright, screenbottom, screenright, screentop, screenleft, screentop, rcTex);
- if (i === last && !post_draw)
- glw.setTexture(null);
- }
- fx_index = (fx_index === 0 ? 1 : 0);
- other_fx_index = (fx_index === 0 ? 1 : 0); // will be opposite to fx_index since it was just assigned
- }
- if (post_draw)
- {
- glw.switchProgram(0);
- if (inst)
- glw.setBlend(inst.srcBlend, inst.destBlend);
- else if (layer)
- glw.setBlend(layer.srcBlend, layer.destBlend);
- else
- {
- if (!this.runtime.fullscreenScalingQuality)
- {
- glw.setSize(this.runtime.width, this.runtime.height);
- halfw = this.runtime.width / 2;
- halfh = this.runtime.height / 2;
- screenleft = 0;
- screentop = 0;
- screenright = this.runtime.width;
- screenbottom = this.runtime.height;
- }
- }
- glw.setRenderingToTexture(rendertarget);
- glw.setTexture(fx_tex[other_fx_index]);
- glw.resetModelView();
- glw.translate(-halfw, -halfh);
- glw.updateModelView();
- if (inst && active_effect_types.length === 1 && !pre_draw)
- glw.quadTex(screenleft, screentop, screenright, screentop, screenright, screenbottom, screenleft, screenbottom, rcTex);
- else
- glw.quadTex(screenleft, screenbottom, screenright, screenbottom, screenright, screentop, screenleft, screentop, rcTex);
- glw.setTexture(null);
- }
- };
- Layout.prototype.getLayerBySid = function (sid_)
- {
- var i, len;
- for (i = 0, len = this.layers.length; i < len; i++)
- {
- if (this.layers[i].sid === sid_)
- return this.layers[i];
- }
- return null;
- };
- Layout.prototype.saveToJSON = function ()
- {
- var i, len, layer, et;
- var o = {
- "sx": this.scrollX,
- "sy": this.scrollY,
- "s": this.scale,
- "a": this.angle,
- "w": this.width,
- "h": this.height,
- "fv": this.first_visit, // added r127
- "persist": this.persist_data,
- "fx": [],
- "layers": {}
- };
- for (i = 0, len = this.effect_types.length; i < len; i++)
- {
- et = this.effect_types[i];
- o["fx"].push({"name": et.name, "active": et.active, "params": this.effect_params[et.index] });
- }
- for (i = 0, len = this.layers.length; i < len; i++)
- {
- layer = this.layers[i];
- o["layers"][layer.sid.toString()] = layer.saveToJSON();
- }
- return o;
- };
- Layout.prototype.loadFromJSON = function (o)
- {
- var i, j, len, fx, p, layer;
- this.scrollX = o["sx"];
- this.scrollY = o["sy"];
- this.scale = o["s"];
- this.angle = o["a"];
- this.width = o["w"];
- this.height = o["h"];
- this.persist_data = o["persist"];
- if (typeof o["fv"] !== "undefined")
- this.first_visit = o["fv"];
- var ofx = o["fx"];
- for (i = 0, len = ofx.length; i < len; i++)
- {
- fx = this.getEffectByName(ofx[i]["name"]);
- if (!fx)
- continue; // must've gone missing
- fx.active = ofx[i]["active"];
- this.effect_params[fx.index] = ofx[i]["params"];
- }
- this.updateActiveEffects();
- var olayers = o["layers"];
- for (p in olayers)
- {
- if (olayers.hasOwnProperty(p))
- {
- layer = this.getLayerBySid(parseInt(p, 10));
- if (!layer)
- continue; // must've gone missing
- layer.loadFromJSON(olayers[p]);
- }
- }
- };
- cr.layout = Layout;
- function Layer(layout, m)
- {
- this.layout = layout;
- this.runtime = layout.runtime;
- this.instances = []; // running instances
- this.scale = 1.0;
- this.angle = 0;
- this.disableAngle = false;
- this.tmprect = new cr.rect(0, 0, 0, 0);
- this.tmpquad = new cr.quad();
- this.viewLeft = 0;
- this.viewRight = 0;
- this.viewTop = 0;
- this.viewBottom = 0;
- this.zindices_stale = false;
- this.zindices_stale_from = -1; // first index that has changed, or -1 if no bound
- this.name = m[0];
- this.index = m[1];
- this.sid = m[2];
- this.visible = m[3]; // initially visible
- this.background_color = m[4];
- this.transparent = m[5];
- this.parallaxX = m[6];
- this.parallaxY = m[7];
- this.opacity = m[8];
- this.forceOwnTexture = m[9];
- this.useRenderCells = m[10];
- this.zoomRate = m[11];
- this.blend_mode = m[12];
- this.effect_fallback = m[13];
- this.compositeOp = "source-over";
- this.srcBlend = 0;
- this.destBlend = 0;
- this.render_grid = null;
- this.last_render_list = alloc_arr();
- this.render_list_stale = true;
- this.last_render_cells = new cr.rect(0, 0, -1, -1);
- this.cur_render_cells = new cr.rect(0, 0, -1, -1);
- if (this.useRenderCells)
- {
- this.render_grid = new cr.RenderGrid(this.runtime.original_width, this.runtime.original_height);
- }
- this.render_offscreen = false;
- var im = m[14];
- var i, len;
- this.startup_initial_instances = []; // for restoring initial_instances after load
- this.initial_instances = [];
- this.created_globals = []; // global object UIDs already created - for save/load to avoid recreating
- for (i = 0, len = im.length; i < len; i++)
- {
- var inst = im[i];
- var type = this.runtime.types_by_index[inst[1]];
- ;
- if (!type.default_instance)
- {
- type.default_instance = inst;
- type.default_layerindex = this.index;
- }
- this.initial_instances.push(inst);
- if (this.layout.initial_types.indexOf(type) === -1)
- this.layout.initial_types.push(type);
- }
- cr.shallowAssignArray(this.startup_initial_instances, this.initial_instances);
- this.effect_types = [];
- this.active_effect_types = [];
- this.effect_params = [];
- for (i = 0, len = m[15].length; i < len; i++)
- {
- this.effect_types.push({
- id: m[15][i][0],
- name: m[15][i][1],
- shaderindex: -1,
- active: true,
- index: i
- });
- this.effect_params.push(m[15][i][2].slice(0));
- }
- this.updateActiveEffects();
- this.rcTex = new cr.rect(0, 0, 1, 1);
- this.rcTex2 = new cr.rect(0, 0, 1, 1);
- };
- Layer.prototype.updateActiveEffects = function ()
- {
- this.active_effect_types.length = 0;
- var i, len, et;
- for (i = 0, len = this.effect_types.length; i < len; i++)
- {
- et = this.effect_types[i];
- if (et.active)
- this.active_effect_types.push(et);
- }
- };
- Layer.prototype.getEffectByName = function (name_)
- {
- var i, len, et;
- for (i = 0, len = this.effect_types.length; i < len; i++)
- {
- et = this.effect_types[i];
- if (et.name === name_)
- return et;
- }
- return null;
- };
- Layer.prototype.createInitialInstances = function ()
- {
- var i, k, len, inst, initial_inst, type, keep, hasPersistBehavior;
- for (i = 0, k = 0, len = this.initial_instances.length; i < len; i++)
- {
- initial_inst = this.initial_instances[i];
- type = this.runtime.types_by_index[initial_inst[1]];
- ;
- hasPersistBehavior = this.runtime.typeHasPersistBehavior(type);
- keep = true;
- if (!hasPersistBehavior || this.layout.first_visit)
- {
- inst = this.runtime.createInstanceFromInit(initial_inst, this, true);
- ;
- created_instances.push(inst);
- if (inst.type.global)
- {
- keep = false;
- this.created_globals.push(inst.uid);
- }
- }
- if (keep)
- {
- this.initial_instances[k] = this.initial_instances[i];
- k++;
- }
- }
- this.initial_instances.length = k;
- this.runtime.ClearDeathRow(); // flushes creation row so IIDs will be correct
- if (!this.runtime.glwrap && this.effect_types.length) // no WebGL renderer and shaders used
- this.blend_mode = this.effect_fallback; // use fallback blend mode
- this.compositeOp = cr.effectToCompositeOp(this.blend_mode);
- if (this.runtime.gl)
- cr.setGLBlend(this, this.blend_mode, this.runtime.gl);
- this.render_list_stale = true;
- };
- Layer.prototype.recreateInitialObjects = function (only_type, rc)
- {
- var i, len, initial_inst, type, wm, x, y, inst, j, lenj, s;
- var types_by_index = this.runtime.types_by_index;
- var only_type_is_family = only_type.is_family;
- var only_type_members = only_type.members;
- for (i = 0, len = this.initial_instances.length; i < len; ++i)
- {
- initial_inst = this.initial_instances[i];
- wm = initial_inst[0];
- x = wm[0];
- y = wm[1];
- if (!rc.contains_pt(x, y))
- continue; // not in the given area
- type = types_by_index[initial_inst[1]];
- if (type !== only_type)
- {
- if (only_type_is_family)
- {
- if (only_type_members.indexOf(type) < 0)
- continue;
- }
- else
- continue; // only_type is not a family, and the initial inst type does not match
- }
- inst = this.runtime.createInstanceFromInit(initial_inst, this, false);
- this.runtime.isInOnDestroy++;
- this.runtime.trigger(Object.getPrototypeOf(type.plugin).cnds.OnCreated, inst);
- if (inst.is_contained)
- {
- for (j = 0, lenj = inst.siblings.length; j < lenj; j++)
- {
- s = inst.siblings[i];
- this.runtime.trigger(Object.getPrototypeOf(s.type.plugin).cnds.OnCreated, s);
- }
- }
- this.runtime.isInOnDestroy--;
- }
- };
- Layer.prototype.removeFromInstanceList = function (inst, remove_from_grid)
- {
- var index = cr.fastIndexOf(this.instances, inst);
- if (index < 0)
- return; // not found
- if (remove_from_grid && this.useRenderCells && inst.rendercells && inst.rendercells.right >= inst.rendercells.left)
- {
- inst.update_bbox(); // make sure actually in its current rendercells
- this.render_grid.update(inst, inst.rendercells, null); // no new range provided - remove only
- inst.rendercells.set(0, 0, -1, -1); // set to invalid state to indicate not inserted
- }
- if (index === this.instances.length - 1)
- this.instances.pop();
- else
- {
- cr.arrayRemove(this.instances, index);
- this.setZIndicesStaleFrom(index);
- }
- this.render_list_stale = true;
- };
- Layer.prototype.appendToInstanceList = function (inst, add_to_grid)
- {
- ;
- inst.zindex = this.instances.length;
- this.instances.push(inst);
- if (add_to_grid && this.useRenderCells && inst.rendercells)
- {
- inst.set_bbox_changed(); // will cause immediate update and new insertion to grid
- }
- this.render_list_stale = true;
- };
- Layer.prototype.prependToInstanceList = function (inst, add_to_grid)
- {
- ;
- this.instances.unshift(inst);
- this.setZIndicesStaleFrom(0);
- if (add_to_grid && this.useRenderCells && inst.rendercells)
- {
- inst.set_bbox_changed(); // will cause immediate update and new insertion to grid
- }
- };
- Layer.prototype.moveInstanceAdjacent = function (inst, other, isafter)
- {
- ;
- var myZ = inst.get_zindex();
- var insertZ = other.get_zindex();
- cr.arrayRemove(this.instances, myZ);
- if (myZ < insertZ)
- insertZ--;
- if (isafter)
- insertZ++;
- if (insertZ === this.instances.length)
- this.instances.push(inst);
- else
- this.instances.splice(insertZ, 0, inst);
- this.setZIndicesStaleFrom(myZ < insertZ ? myZ : insertZ);
- };
- Layer.prototype.setZIndicesStaleFrom = function (index)
- {
- if (this.zindices_stale_from === -1) // not yet set
- this.zindices_stale_from = index;
- else if (index < this.zindices_stale_from) // determine minimum z index affected
- this.zindices_stale_from = index;
- this.zindices_stale = true;
- this.render_list_stale = true;
- };
- Layer.prototype.updateZIndices = function ()
- {
- if (!this.zindices_stale)
- return;
- if (this.zindices_stale_from === -1)
- this.zindices_stale_from = 0;
- var i, len, inst;
- if (this.useRenderCells)
- {
- for (i = this.zindices_stale_from, len = this.instances.length; i < len; ++i)
- {
- inst = this.instances[i];
- inst.zindex = i;
- this.render_grid.markRangeChanged(inst.rendercells);
- }
- }
- else
- {
- for (i = this.zindices_stale_from, len = this.instances.length; i < len; ++i)
- {
- this.instances[i].zindex = i;
- }
- }
- this.zindices_stale = false;
- this.zindices_stale_from = -1;
- };
- Layer.prototype.getScale = function (include_aspect)
- {
- return this.getNormalScale() * (this.runtime.fullscreenScalingQuality || include_aspect ? this.runtime.aspect_scale : 1);
- };
- Layer.prototype.getNormalScale = function ()
- {
- return ((this.scale * this.layout.scale) - 1) * this.zoomRate + 1;
- };
- Layer.prototype.getAngle = function ()
- {
- if (this.disableAngle)
- return 0;
- return cr.clamp_angle(this.layout.angle + this.angle);
- };
- var arr_cache = [];
- function alloc_arr()
- {
- if (arr_cache.length)
- return arr_cache.pop();
- else
- return [];
- }
- function free_arr(a)
- {
- a.length = 0;
- arr_cache.push(a);
- };
- function mergeSortedZArrays(a, b, out)
- {
- var i = 0, j = 0, k = 0, lena = a.length, lenb = b.length, ai, bj;
- out.length = lena + lenb;
- for ( ; i < lena && j < lenb; ++k)
- {
- ai = a[i];
- bj = b[j];
- if (ai.zindex < bj.zindex)
- {
- out[k] = ai;
- ++i;
- }
- else
- {
- out[k] = bj;
- ++j;
- }
- }
- for ( ; i < lena; ++i, ++k)
- out[k] = a[i];
- for ( ; j < lenb; ++j, ++k)
- out[k] = b[j];
- };
- var next_arr = [];
- function mergeAllSortedZArrays_pass(arr, first_pass)
- {
- var i, len, arr1, arr2, out;
- for (i = 0, len = arr.length; i < len - 1; i += 2)
- {
- arr1 = arr[i];
- arr2 = arr[i+1];
- out = alloc_arr();
- mergeSortedZArrays(arr1, arr2, out);
- if (!first_pass)
- {
- free_arr(arr1);
- free_arr(arr2);
- }
- next_arr.push(out);
- }
- if (len % 2 === 1)
- {
- if (first_pass)
- {
- arr1 = alloc_arr();
- cr.shallowAssignArray(arr1, arr[len - 1]);
- next_arr.push(arr1);
- }
- else
- {
- next_arr.push(arr[len - 1]);
- }
- }
- cr.shallowAssignArray(arr, next_arr);
- next_arr.length = 0;
- };
- function mergeAllSortedZArrays(arr)
- {
- var first_pass = true;
- while (arr.length > 1)
- {
- mergeAllSortedZArrays_pass(arr, first_pass);
- first_pass = false;
- }
- return arr[0];
- };
- var render_arr = [];
- Layer.prototype.getRenderCellInstancesToDraw = function ()
- {
- ;
- this.updateZIndices();
- this.render_grid.queryRange(this.viewLeft, this.viewTop, this.viewRight, this.viewBottom, render_arr);
- if (!render_arr.length)
- return alloc_arr();
- if (render_arr.length === 1)
- {
- var a = alloc_arr();
- cr.shallowAssignArray(a, render_arr[0]);
- render_arr.length = 0;
- return a;
- }
- var draw_list = mergeAllSortedZArrays(render_arr);
- render_arr.length = 0;
- return draw_list;
- };
- Layer.prototype.draw = function (ctx)
- {
- this.render_offscreen = (this.forceOwnTexture || this.opacity !== 1.0 || this.blend_mode !== 0);
- var layer_canvas = this.runtime.canvas;
- var layer_ctx = ctx;
- var ctx_changed = false;
- if (this.render_offscreen)
- {
- if (!this.runtime.layer_canvas)
- {
- this.runtime.layer_canvas = document.createElement("canvas");
- ;
- layer_canvas = this.runtime.layer_canvas;
- layer_canvas.width = this.runtime.draw_width;
- layer_canvas.height = this.runtime.draw_height;
- this.runtime.layer_ctx = layer_canvas.getContext("2d");
- ;
- ctx_changed = true;
- }
- layer_canvas = this.runtime.layer_canvas;
- layer_ctx = this.runtime.layer_ctx;
- if (layer_canvas.width !== this.runtime.draw_width)
- {
- layer_canvas.width = this.runtime.draw_width;
- ctx_changed = true;
- }
- if (layer_canvas.height !== this.runtime.draw_height)
- {
- layer_canvas.height = this.runtime.draw_height;
- ctx_changed = true;
- }
- if (ctx_changed)
- {
- layer_ctx["webkitImageSmoothingEnabled"] = this.runtime.linearSampling;
- layer_ctx["mozImageSmoothingEnabled"] = this.runtime.linearSampling;
- layer_ctx["msImageSmoothingEnabled"] = this.runtime.linearSampling;
- layer_ctx["imageSmoothingEnabled"] = this.runtime.linearSampling;
- }
- if (this.transparent)
- layer_ctx.clearRect(0, 0, this.runtime.draw_width, this.runtime.draw_height);
- }
- layer_ctx.globalAlpha = 1;
- layer_ctx.globalCompositeOperation = "source-over";
- if (!this.transparent)
- {
- layer_ctx.fillStyle = "rgb(" + this.background_color[0] + "," + this.background_color[1] + "," + this.background_color[2] + ")";
- layer_ctx.fillRect(0, 0, this.runtime.draw_width, this.runtime.draw_height);
- }
- layer_ctx.save();
- this.disableAngle = true;
- var px = this.canvasToLayer(0, 0, true, true);
- var py = this.canvasToLayer(0, 0, false, true);
- this.disableAngle = false;
- if (this.runtime.pixel_rounding)
- {
- px = Math.round(px);
- py = Math.round(py);
- }
- this.rotateViewport(px, py, layer_ctx);
- var myscale = this.getScale();
- layer_ctx.scale(myscale, myscale);
- layer_ctx.translate(-px, -py);
- var instances_to_draw;
- if (this.useRenderCells)
- {
- this.cur_render_cells.left = this.render_grid.XToCell(this.viewLeft);
- this.cur_render_cells.top = this.render_grid.YToCell(this.viewTop);
- this.cur_render_cells.right = this.render_grid.XToCell(this.viewRight);
- this.cur_render_cells.bottom = this.render_grid.YToCell(this.viewBottom);
- if (this.render_list_stale || !this.cur_render_cells.equals(this.last_render_cells))
- {
- free_arr(this.last_render_list);
- instances_to_draw = this.getRenderCellInstancesToDraw();
- this.render_list_stale = false;
- this.last_render_cells.copy(this.cur_render_cells);
- }
- else
- instances_to_draw = this.last_render_list;
- }
- else
- instances_to_draw = this.instances;
- var i, len, inst, last_inst = null;
- for (i = 0, len = instances_to_draw.length; i < len; ++i)
- {
- inst = instances_to_draw[i];
- if (inst === last_inst)
- continue;
- this.drawInstance(inst, layer_ctx);
- last_inst = inst;
- }
- if (this.useRenderCells)
- this.last_render_list = instances_to_draw;
- layer_ctx.restore();
- if (this.render_offscreen)
- {
- ctx.globalCompositeOperation = this.compositeOp;
- ctx.globalAlpha = this.opacity;
- ctx.drawImage(layer_canvas, 0, 0);
- }
- };
- Layer.prototype.drawInstance = function(inst, layer_ctx)
- {
- if (!inst.visible || inst.width === 0 || inst.height === 0)
- return;
- inst.update_bbox();
- var bbox = inst.bbox;
- if (bbox.right < this.viewLeft || bbox.bottom < this.viewTop || bbox.left > this.viewRight || bbox.top > this.viewBottom)
- return;
- layer_ctx.globalCompositeOperation = inst.compositeOp;
- inst.draw(layer_ctx);
- };
- Layer.prototype.updateViewport = function (ctx)
- {
- this.disableAngle = true;
- var px = this.canvasToLayer(0, 0, true, true);
- var py = this.canvasToLayer(0, 0, false, true);
- this.disableAngle = false;
- if (this.runtime.pixel_rounding)
- {
- px = Math.round(px);
- py = Math.round(py);
- }
- this.rotateViewport(px, py, ctx);
- };
- Layer.prototype.rotateViewport = function (px, py, ctx)
- {
- var myscale = this.getScale();
- this.viewLeft = px;
- this.viewTop = py;
- this.viewRight = px + (this.runtime.draw_width * (1 / myscale));
- this.viewBottom = py + (this.runtime.draw_height * (1 / myscale));
- var myAngle = this.getAngle();
- if (myAngle !== 0)
- {
- if (ctx)
- {
- ctx.translate(this.runtime.draw_width / 2, this.runtime.draw_height / 2);
- ctx.rotate(-myAngle);
- ctx.translate(this.runtime.draw_width / -2, this.runtime.draw_height / -2);
- }
- this.tmprect.set(this.viewLeft, this.viewTop, this.viewRight, this.viewBottom);
- this.tmprect.offset((this.viewLeft + this.viewRight) / -2, (this.viewTop + this.viewBottom) / -2);
- this.tmpquad.set_from_rotated_rect(this.tmprect, myAngle);
- this.tmpquad.bounding_box(this.tmprect);
- this.tmprect.offset((this.viewLeft + this.viewRight) / 2, (this.viewTop + this.viewBottom) / 2);
- this.viewLeft = this.tmprect.left;
- this.viewTop = this.tmprect.top;
- this.viewRight = this.tmprect.right;
- this.viewBottom = this.tmprect.bottom;
- }
- }
- Layer.prototype.drawGL = function (glw)
- {
- var windowWidth = this.runtime.draw_width;
- var windowHeight = this.runtime.draw_height;
- var shaderindex = 0;
- var etindex = 0;
- this.render_offscreen = (this.forceOwnTexture || this.opacity !== 1.0 || this.active_effect_types.length > 0 || this.blend_mode !== 0);
- if (this.render_offscreen)
- {
- if (!this.runtime.layer_tex)
- {
- this.runtime.layer_tex = glw.createEmptyTexture(this.runtime.draw_width, this.runtime.draw_height, this.runtime.linearSampling);
- }
- if (this.runtime.layer_tex.c2width !== this.runtime.draw_width || this.runtime.layer_tex.c2height !== this.runtime.draw_height)
- {
- glw.deleteTexture(this.runtime.layer_tex);
- this.runtime.layer_tex = glw.createEmptyTexture(this.runtime.draw_width, this.runtime.draw_height, this.runtime.linearSampling);
- }
- glw.setRenderingToTexture(this.runtime.layer_tex);
- if (this.transparent)
- glw.clear(0, 0, 0, 0);
- }
- if (!this.transparent)
- {
- glw.clear(this.background_color[0] / 255, this.background_color[1] / 255, this.background_color[2] / 255, 1);
- }
- this.disableAngle = true;
- var px = this.canvasToLayer(0, 0, true, true);
- var py = this.canvasToLayer(0, 0, false, true);
- this.disableAngle = false;
- if (this.runtime.pixel_rounding)
- {
- px = Math.round(px);
- py = Math.round(py);
- }
- this.rotateViewport(px, py, null);
- var myscale = this.getScale();
- glw.resetModelView();
- glw.scale(myscale, myscale);
- glw.rotateZ(-this.getAngle());
- glw.translate((this.viewLeft + this.viewRight) / -2, (this.viewTop + this.viewBottom) / -2);
- glw.updateModelView();
- var instances_to_draw;
- if (this.useRenderCells)
- {
- this.cur_render_cells.left = this.render_grid.XToCell(this.viewLeft);
- this.cur_render_cells.top = this.render_grid.YToCell(this.viewTop);
- this.cur_render_cells.right = this.render_grid.XToCell(this.viewRight);
- this.cur_render_cells.bottom = this.render_grid.YToCell(this.viewBottom);
- if (this.render_list_stale || !this.cur_render_cells.equals(this.last_render_cells))
- {
- free_arr(this.last_render_list);
- instances_to_draw = this.getRenderCellInstancesToDraw();
- this.render_list_stale = false;
- this.last_render_cells.copy(this.cur_render_cells);
- }
- else
- instances_to_draw = this.last_render_list;
- }
- else
- instances_to_draw = this.instances;
- var i, len, inst, last_inst = null;
- for (i = 0, len = instances_to_draw.length; i < len; ++i)
- {
- inst = instances_to_draw[i];
- if (inst === last_inst)
- continue;
- this.drawInstanceGL(instances_to_draw[i], glw);
- last_inst = inst;
- }
- if (this.useRenderCells)
- this.last_render_list = instances_to_draw;
- if (this.render_offscreen)
- {
- shaderindex = this.active_effect_types.length ? this.active_effect_types[0].shaderindex : 0;
- etindex = this.active_effect_types.length ? this.active_effect_types[0].index : 0;
- if (this.active_effect_types.length === 0 || (this.active_effect_types.length === 1 &&
- !glw.programUsesCrossSampling(shaderindex) && this.opacity === 1))
- {
- if (this.active_effect_types.length === 1)
- {
- glw.switchProgram(shaderindex);
- glw.setProgramParameters(this.layout.getRenderTarget(), // backTex
- 1.0 / this.runtime.draw_width, // pixelWidth
- 1.0 / this.runtime.draw_height, // pixelHeight
- 0.0, 0.0, // destStart
- 1.0, 1.0, // destEnd
- myscale, // layerScale
- this.getAngle(),
- this.viewLeft, this.viewTop,
- (this.viewLeft + this.viewRight) / 2, (this.viewTop + this.viewBottom) / 2,
- this.effect_params[etindex]); // fx parameters
- if (glw.programIsAnimated(shaderindex))
- this.runtime.redraw = true;
- }
- else
- glw.switchProgram(0);
- glw.setRenderingToTexture(this.layout.getRenderTarget());
- glw.setOpacity(this.opacity);
- glw.setTexture(this.runtime.layer_tex);
- glw.setBlend(this.srcBlend, this.destBlend);
- glw.resetModelView();
- glw.updateModelView();
- var halfw = this.runtime.draw_width / 2;
- var halfh = this.runtime.draw_height / 2;
- glw.quad(-halfw, halfh, halfw, halfh, halfw, -halfh, -halfw, -halfh);
- glw.setTexture(null);
- }
- else
- {
- this.layout.renderEffectChain(glw, this, null, this.layout.getRenderTarget());
- }
- }
- };
- Layer.prototype.drawInstanceGL = function (inst, glw)
- {
- ;
- if (!inst.visible || inst.width === 0 || inst.height === 0)
- return;
- inst.update_bbox();
- var bbox = inst.bbox;
- if (bbox.right < this.viewLeft || bbox.bottom < this.viewTop || bbox.left > this.viewRight || bbox.top > this.viewBottom)
- return;
- if (inst.uses_shaders)
- {
- this.drawInstanceWithShadersGL(inst, glw);
- }
- else
- {
- glw.switchProgram(0); // un-set any previously set shader
- glw.setBlend(inst.srcBlend, inst.destBlend);
- inst.drawGL(glw);
- }
- };
- Layer.prototype.drawInstanceWithShadersGL = function (inst, glw)
- {
- var shaderindex = inst.active_effect_types[0].shaderindex;
- var etindex = inst.active_effect_types[0].index;
- var myscale = this.getScale();
- if (inst.active_effect_types.length === 1 && !glw.programUsesCrossSampling(shaderindex) &&
- !glw.programExtendsBox(shaderindex) && ((!inst.angle && !inst.layer.getAngle()) || !glw.programUsesDest(shaderindex)) &&
- inst.opacity === 1 && !inst.type.plugin.must_predraw)
- {
- glw.switchProgram(shaderindex);
- glw.setBlend(inst.srcBlend, inst.destBlend);
- if (glw.programIsAnimated(shaderindex))
- this.runtime.redraw = true;
- var destStartX = 0, destStartY = 0, destEndX = 0, destEndY = 0;
- if (glw.programUsesDest(shaderindex))
- {
- var bbox = inst.bbox;
- var screenleft = this.layerToCanvas(bbox.left, bbox.top, true, true);
- var screentop = this.layerToCanvas(bbox.left, bbox.top, false, true);
- var screenright = this.layerToCanvas(bbox.right, bbox.bottom, true, true);
- var screenbottom = this.layerToCanvas(bbox.right, bbox.bottom, false, true);
- destStartX = screenleft / windowWidth;
- destStartY = 1 - screentop / windowHeight;
- destEndX = screenright / windowWidth;
- destEndY = 1 - screenbottom / windowHeight;
- }
- glw.setProgramParameters(this.render_offscreen ? this.runtime.layer_tex : this.layout.getRenderTarget(), // backTex
- 1.0 / inst.width, // pixelWidth
- 1.0 / inst.height, // pixelHeight
- destStartX, destStartY,
- destEndX, destEndY,
- myscale,
- this.getAngle(),
- this.viewLeft, this.viewTop,
- (this.viewLeft + this.viewRight) / 2, (this.viewTop + this.viewBottom) / 2,
- inst.effect_params[etindex]);
- inst.drawGL(glw);
- }
- else
- {
- this.layout.renderEffectChain(glw, this, inst, this.render_offscreen ? this.runtime.layer_tex : this.layout.getRenderTarget());
- glw.resetModelView();
- glw.scale(myscale, myscale);
- glw.rotateZ(-this.getAngle());
- glw.translate((this.viewLeft + this.viewRight) / -2, (this.viewTop + this.viewBottom) / -2);
- glw.updateModelView();
- }
- };
- Layer.prototype.canvasToLayer = function (ptx, pty, getx, using_draw_area)
- {
- var multiplier = this.runtime.devicePixelRatio;
- if (this.runtime.isRetina)
- {
- ptx *= multiplier;
- pty *= multiplier;
- }
- var ox = this.runtime.parallax_x_origin;
- var oy = this.runtime.parallax_y_origin;
- var par_x = ((this.layout.scrollX - ox) * this.parallaxX) + ox;
- var par_y = ((this.layout.scrollY - oy) * this.parallaxY) + oy;
- var x = par_x;
- var y = par_y;
- var invScale = 1 / this.getScale(!using_draw_area);
- if (using_draw_area)
- {
- x -= (this.runtime.draw_width * invScale) / 2;
- y -= (this.runtime.draw_height * invScale) / 2;
- }
- else
- {
- x -= (this.runtime.width * invScale) / 2;
- y -= (this.runtime.height * invScale) / 2;
- }
- x += ptx * invScale;
- y += pty * invScale;
- var a = this.getAngle();
- if (a !== 0)
- {
- x -= par_x;
- y -= par_y;
- var cosa = Math.cos(a);
- var sina = Math.sin(a);
- var x_temp = (x * cosa) - (y * sina);
- y = (y * cosa) + (x * sina);
- x = x_temp;
- x += par_x;
- y += par_y;
- }
- return getx ? x : y;
- };
- Layer.prototype.layerToCanvas = function (ptx, pty, getx, using_draw_area)
- {
- var ox = this.runtime.parallax_x_origin;
- var oy = this.runtime.parallax_y_origin;
- var par_x = ((this.layout.scrollX - ox) * this.parallaxX) + ox;
- var par_y = ((this.layout.scrollY - oy) * this.parallaxY) + oy;
- var x = par_x;
- var y = par_y;
- var a = this.getAngle();
- if (a !== 0)
- {
- ptx -= par_x;
- pty -= par_y;
- var cosa = Math.cos(-a);
- var sina = Math.sin(-a);
- var x_temp = (ptx * cosa) - (pty * sina);
- pty = (pty * cosa) + (ptx * sina);
- ptx = x_temp;
- ptx += par_x;
- pty += par_y;
- }
- var invScale = 1 / this.getScale(!using_draw_area);
- if (using_draw_area)
- {
- x -= (this.runtime.draw_width * invScale) / 2;
- y -= (this.runtime.draw_height * invScale) / 2;
- }
- else
- {
- x -= (this.runtime.width * invScale) / 2;
- y -= (this.runtime.height * invScale) / 2;
- }
- x = (ptx - x) / invScale;
- y = (pty - y) / invScale;
- var multiplier = this.runtime.devicePixelRatio;
- if (this.runtime.isRetina && !using_draw_area)
- {
- x /= multiplier;
- y /= multiplier;
- }
- return getx ? x : y;
- };
- Layer.prototype.rotatePt = function (x_, y_, getx)
- {
- if (this.getAngle() === 0)
- return getx ? x_ : y_;
- var nx = this.layerToCanvas(x_, y_, true);
- var ny = this.layerToCanvas(x_, y_, false);
- this.disableAngle = true;
- var px = this.canvasToLayer(nx, ny, true);
- var py = this.canvasToLayer(nx, ny, true);
- this.disableAngle = false;
- return getx ? px : py;
- };
- Layer.prototype.saveToJSON = function ()
- {
- var i, len, et;
- var o = {
- "s": this.scale,
- "a": this.angle,
- "vl": this.viewLeft,
- "vt": this.viewTop,
- "vr": this.viewRight,
- "vb": this.viewBottom,
- "v": this.visible,
- "bc": this.background_color,
- "t": this.transparent,
- "px": this.parallaxX,
- "py": this.parallaxY,
- "o": this.opacity,
- "zr": this.zoomRate,
- "fx": [],
- "cg": this.created_globals, // added r197; list of global UIDs already created
- "instances": []
- };
- for (i = 0, len = this.effect_types.length; i < len; i++)
- {
- et = this.effect_types[i];
- o["fx"].push({"name": et.name, "active": et.active, "params": this.effect_params[et.index] });
- }
- return o;
- };
- Layer.prototype.loadFromJSON = function (o)
- {
- var i, j, len, p, inst, fx;
- this.scale = o["s"];
- this.angle = o["a"];
- this.viewLeft = o["vl"];
- this.viewTop = o["vt"];
- this.viewRight = o["vr"];
- this.viewBottom = o["vb"];
- this.visible = o["v"];
- this.background_color = o["bc"];
- this.transparent = o["t"];
- this.parallaxX = o["px"];
- this.parallaxY = o["py"];
- this.opacity = o["o"];
- this.zoomRate = o["zr"];
- this.created_globals = o["cg"] || []; // added r197
- cr.shallowAssignArray(this.initial_instances, this.startup_initial_instances);
- var temp_set = new cr.ObjectSet();
- for (i = 0, len = this.created_globals.length; i < len; ++i)
- temp_set.add(this.created_globals[i]);
- for (i = 0, j = 0, len = this.initial_instances.length; i < len; ++i)
- {
- if (!temp_set.contains(this.initial_instances[i][2])) // UID in element 2
- {
- this.initial_instances[j] = this.initial_instances[i];
- ++j;
- }
- }
- this.initial_instances.length = j;
- var ofx = o["fx"];
- for (i = 0, len = ofx.length; i < len; i++)
- {
- fx = this.getEffectByName(ofx[i]["name"]);
- if (!fx)
- continue; // must've gone missing
- fx.active = ofx[i]["active"];
- this.effect_params[fx.index] = ofx[i]["params"];
- }
- this.updateActiveEffects();
- this.instances.sort(sort_by_zindex);
- this.zindices_stale = true;
- };
- cr.layer = Layer;
- }());
- ;
- (function()
- {
- var allUniqueSolModifiers = [];
- function testSolsMatch(arr1, arr2)
- {
- var i, len = arr1.length;
- switch (len) {
- case 0:
- return true;
- case 1:
- return arr1[0] === arr2[0];
- case 2:
- return arr1[0] === arr2[0] && arr1[1] === arr2[1];
- default:
- for (i = 0; i < len; i++)
- {
- if (arr1[i] !== arr2[i])
- return false;
- }
- return true;
- }
- };
- function solArraySorter(t1, t2)
- {
- return t1.index - t2.index;
- };
- function findMatchingSolModifier(arr)
- {
- var i, len, u, temp, subarr;
- if (arr.length === 2)
- {
- if (arr[0].index > arr[1].index)
- {
- temp = arr[0];
- arr[0] = arr[1];
- arr[1] = temp;
- }
- }
- else if (arr.length > 2)
- arr.sort(solArraySorter); // so testSolsMatch compares in same order
- if (arr.length >= allUniqueSolModifiers.length)
- allUniqueSolModifiers.length = arr.length + 1;
- if (!allUniqueSolModifiers[arr.length])
- allUniqueSolModifiers[arr.length] = [];
- subarr = allUniqueSolModifiers[arr.length];
- for (i = 0, len = subarr.length; i < len; i++)
- {
- u = subarr[i];
- if (testSolsMatch(arr, u))
- return u;
- }
- subarr.push(arr);
- return arr;
- };
- function EventSheet(runtime, m)
- {
- this.runtime = runtime;
- this.triggers = {};
- this.fasttriggers = {};
- this.hasRun = false;
- this.includes = new cr.ObjectSet(); // all event sheets included by this sheet, at first-level indirection only
- this.deep_includes = []; // all includes from this sheet recursively, in trigger order
- this.already_included_sheets = []; // used while building deep_includes
- this.name = m[0];
- var em = m[1]; // events model
- this.events = []; // triggers won't make it to this array
- var i, len;
- for (i = 0, len = em.length; i < len; i++)
- this.init_event(em[i], null, this.events);
- };
- EventSheet.prototype.toString = function ()
- {
- return this.name;
- };
- EventSheet.prototype.init_event = function (m, parent, nontriggers)
- {
- switch (m[0]) {
- case 0: // event block
- {
- var block = new cr.eventblock(this, parent, m);
- cr.seal(block);
- if (block.orblock)
- {
- nontriggers.push(block);
- var i, len;
- for (i = 0, len = block.conditions.length; i < len; i++)
- {
- if (block.conditions[i].trigger)
- this.init_trigger(block, i);
- }
- }
- else
- {
- if (block.is_trigger())
- this.init_trigger(block, 0);
- else
- nontriggers.push(block);
- }
- break;
- }
- case 1: // variable
- {
- var v = new cr.eventvariable(this, parent, m);
- cr.seal(v);
- nontriggers.push(v);
- break;
- }
- case 2: // include
- {
- var inc = new cr.eventinclude(this, parent, m);
- cr.seal(inc);
- nontriggers.push(inc);
- break;
- }
- default:
- ;
- }
- };
- EventSheet.prototype.postInit = function ()
- {
- var i, len;
- for (i = 0, len = this.events.length; i < len; i++)
- {
- this.events[i].postInit(i < len - 1 && this.events[i + 1].is_else_block);
- }
- };
- EventSheet.prototype.updateDeepIncludes = function ()
- {
- cr.clearArray(this.deep_includes);
- cr.clearArray(this.already_included_sheets);
- this.addDeepIncludes(this);
- cr.clearArray(this.already_included_sheets);
- };
- EventSheet.prototype.addDeepIncludes = function (root_sheet)
- {
- var i, len, inc, sheet;
- var deep_includes = root_sheet.deep_includes;
- var already_included_sheets = root_sheet.already_included_sheets;
- var arr = this.includes.valuesRef();
- for (i = 0, len = arr.length; i < len; ++i)
- {
- inc = arr[i];
- sheet = inc.include_sheet;
- if (!inc.isActive() || root_sheet === sheet || already_included_sheets.indexOf(sheet) > -1)
- continue;
- already_included_sheets.push(sheet);
- sheet.addDeepIncludes(root_sheet);
- deep_includes.push(sheet);
- }
- };
- EventSheet.prototype.run = function (from_include)
- {
- if (!this.runtime.resuming_breakpoint)
- {
- this.hasRun = true;
- if (!from_include)
- this.runtime.isRunningEvents = true;
- }
- var i, len;
- for (i = 0, len = this.events.length; i < len; i++)
- {
- var ev = this.events[i];
- ev.run();
- this.runtime.clearSol(ev.solModifiers);
- if (this.runtime.hasPendingInstances)
- this.runtime.ClearDeathRow();
- }
- if (!from_include)
- this.runtime.isRunningEvents = false;
- };
- function isPerformanceSensitiveTrigger(method)
- {
- if (cr.plugins_.Sprite && method === cr.plugins_.Sprite.prototype.cnds.OnFrameChanged)
- {
- return true;
- }
- return false;
- };
- EventSheet.prototype.init_trigger = function (trig, index)
- {
- if (!trig.orblock)
- this.runtime.triggers_to_postinit.push(trig); // needs to be postInit'd later
- var i, len;
- var cnd = trig.conditions[index];
- var type_name;
- if (cnd.type)
- type_name = cnd.type.name;
- else
- type_name = "system";
- var fasttrigger = cnd.fasttrigger;
- var triggers = (fasttrigger ? this.fasttriggers : this.triggers);
- if (!triggers[type_name])
- triggers[type_name] = [];
- var obj_entry = triggers[type_name];
- var method = cnd.func;
- if (fasttrigger)
- {
- if (!cnd.parameters.length) // no parameters
- return;
- var firstparam = cnd.parameters[0];
- if (firstparam.type !== 1 || // not a string param
- firstparam.expression.type !== 2) // not a string literal node
- {
- return;
- }
- var fastevs;
- var firstvalue = firstparam.expression.value.toLowerCase();
- var i, len;
- for (i = 0, len = obj_entry.length; i < len; i++)
- {
- if (obj_entry[i].method == method)
- {
- fastevs = obj_entry[i].evs;
- if (!fastevs[firstvalue])
- fastevs[firstvalue] = [[trig, index]];
- else
- fastevs[firstvalue].push([trig, index]);
- return;
- }
- }
- fastevs = {};
- fastevs[firstvalue] = [[trig, index]];
- obj_entry.push({ method: method, evs: fastevs });
- }
- else
- {
- for (i = 0, len = obj_entry.length; i < len; i++)
- {
- if (obj_entry[i].method == method)
- {
- obj_entry[i].evs.push([trig, index]);
- return;
- }
- }
- if (isPerformanceSensitiveTrigger(method))
- obj_entry.unshift({ method: method, evs: [[trig, index]]});
- else
- obj_entry.push({ method: method, evs: [[trig, index]]});
- }
- };
- cr.eventsheet = EventSheet;
- function Selection(type)
- {
- this.type = type;
- this.instances = []; // subset of picked instances
- this.else_instances = []; // subset of unpicked instances
- this.select_all = true;
- };
- Selection.prototype.hasObjects = function ()
- {
- if (this.select_all)
- return this.type.instances.length;
- else
- return this.instances.length;
- };
- Selection.prototype.getObjects = function ()
- {
- if (this.select_all)
- return this.type.instances;
- else
- return this.instances;
- };
- /*
- Selection.prototype.ensure_picked = function (inst, skip_siblings)
- {
- var i, len;
- var orblock = inst.runtime.getCurrentEventStack().current_event.orblock;
- if (this.select_all)
- {
- this.select_all = false;
- if (orblock)
- {
- cr.shallowAssignArray(this.else_instances, inst.type.instances);
- cr.arrayFindRemove(this.else_instances, inst);
- }
- this.instances.length = 1;
- this.instances[0] = inst;
- }
- else
- {
- if (orblock)
- {
- i = this.else_instances.indexOf(inst);
- if (i !== -1)
- {
- this.instances.push(this.else_instances[i]);
- this.else_instances.splice(i, 1);
- }
- }
- else
- {
- if (this.instances.indexOf(inst) === -1)
- this.instances.push(inst);
- }
- }
- if (!skip_siblings)
- {
- }
- };
- */
- Selection.prototype.pick_one = function (inst)
- {
- if (!inst)
- return;
- if (inst.runtime.getCurrentEventStack().current_event.orblock)
- {
- if (this.select_all)
- {
- cr.clearArray(this.instances);
- cr.shallowAssignArray(this.else_instances, inst.type.instances);
- this.select_all = false;
- }
- var i = this.else_instances.indexOf(inst);
- if (i !== -1)
- {
- this.instances.push(this.else_instances[i]);
- this.else_instances.splice(i, 1);
- }
- }
- else
- {
- this.select_all = false;
- cr.clearArray(this.instances);
- this.instances[0] = inst;
- }
- };
- cr.selection = Selection;
- function EventBlock(sheet, parent, m)
- {
- this.sheet = sheet;
- this.parent = parent;
- this.runtime = sheet.runtime;
- this.solModifiers = [];
- this.solModifiersIncludingParents = [];
- this.solWriterAfterCnds = false; // block does not change SOL after running its conditions
- this.group = false; // is group of events
- this.initially_activated = false; // if a group, is active on startup
- this.toplevelevent = false; // is an event block parented only by a top-level group
- this.toplevelgroup = false; // is parented only by other groups or is top-level (i.e. not in a subevent)
- this.has_else_block = false; // is followed by else
- ;
- this.conditions = [];
- this.actions = [];
- this.subevents = [];
- this.group_name = "";
- this.group = false;
- this.initially_activated = false;
- this.group_active = false;
- this.contained_includes = null;
- if (m[1])
- {
- this.group_name = m[1][1].toLowerCase();
- this.group = true;
- this.initially_activated = !!m[1][0];
- this.contained_includes = [];
- this.group_active = this.initially_activated;
- this.runtime.allGroups.push(this);
- this.runtime.groups_by_name[this.group_name] = this;
- }
- this.orblock = m[2];
- this.sid = m[4];
- if (!this.group)
- this.runtime.blocksBySid[this.sid.toString()] = this;
- var i, len;
- var cm = m[5];
- for (i = 0, len = cm.length; i < len; i++)
- {
- var cnd = new cr.condition(this, cm[i]);
- cnd.index = i;
- cr.seal(cnd);
- this.conditions.push(cnd);
- /*
- if (cnd.is_logical())
- this.is_logical = true;
- if (cnd.type && !cnd.type.plugin.singleglobal && this.cndReferences.indexOf(cnd.type) === -1)
- this.cndReferences.push(cnd.type);
- */
- this.addSolModifier(cnd.type);
- }
- var am = m[6];
- for (i = 0, len = am.length; i < len; i++)
- {
- var act = new cr.action(this, am[i]);
- act.index = i;
- cr.seal(act);
- this.actions.push(act);
- }
- if (m.length === 8)
- {
- var em = m[7];
- for (i = 0, len = em.length; i < len; i++)
- this.sheet.init_event(em[i], this, this.subevents);
- }
- this.is_else_block = false;
- if (this.conditions.length)
- {
- this.is_else_block = (this.conditions[0].type == null && this.conditions[0].func == cr.system_object.prototype.cnds.Else);
- }
- };
- window["_c2hh_"] = "DE239334C48DAB94C32CB8CBD790EBFCDB31D26F";
- EventBlock.prototype.postInit = function (hasElse/*, prevBlock_*/)
- {
- var i, len;
- var p = this.parent;
- if (this.group)
- {
- this.toplevelgroup = true;
- while (p)
- {
- if (!p.group)
- {
- this.toplevelgroup = false;
- break;
- }
- p = p.parent;
- }
- }
- this.toplevelevent = !this.is_trigger() && (!this.parent || (this.parent.group && this.parent.toplevelgroup));
- this.has_else_block = !!hasElse;
- this.solModifiersIncludingParents = this.solModifiers.slice(0);
- p = this.parent;
- while (p)
- {
- for (i = 0, len = p.solModifiers.length; i < len; i++)
- this.addParentSolModifier(p.solModifiers[i]);
- p = p.parent;
- }
- this.solModifiers = findMatchingSolModifier(this.solModifiers);
- this.solModifiersIncludingParents = findMatchingSolModifier(this.solModifiersIncludingParents);
- var i, len/*, s*/;
- for (i = 0, len = this.conditions.length; i < len; i++)
- this.conditions[i].postInit();
- for (i = 0, len = this.actions.length; i < len; i++)
- this.actions[i].postInit();
- for (i = 0, len = this.subevents.length; i < len; i++)
- {
- this.subevents[i].postInit(i < len - 1 && this.subevents[i + 1].is_else_block);
- }
- /*
- if (this.is_else_block && this.prev_block)
- {
- for (i = 0, len = this.prev_block.solModifiers.length; i < len; i++)
- {
- s = this.prev_block.solModifiers[i];
- if (this.solModifiers.indexOf(s) === -1)
- this.solModifiers.push(s);
- }
- }
- */
- };
- EventBlock.prototype.setGroupActive = function (a)
- {
- if (this.group_active === !!a)
- return; // same state
- this.group_active = !!a;
- var i, len;
- for (i = 0, len = this.contained_includes.length; i < len; ++i)
- {
- this.contained_includes[i].updateActive();
- }
- if (len > 0 && this.runtime.running_layout.event_sheet)
- this.runtime.running_layout.event_sheet.updateDeepIncludes();
- };
- function addSolModifierToList(type, arr)
- {
- var i, len, t;
- if (!type)
- return;
- if (arr.indexOf(type) === -1)
- arr.push(type);
- if (type.is_contained)
- {
- for (i = 0, len = type.container.length; i < len; i++)
- {
- t = type.container[i];
- if (type === t)
- continue; // already handled
- if (arr.indexOf(t) === -1)
- arr.push(t);
- }
- }
- };
- EventBlock.prototype.addSolModifier = function (type)
- {
- addSolModifierToList(type, this.solModifiers);
- };
- EventBlock.prototype.addParentSolModifier = function (type)
- {
- addSolModifierToList(type, this.solModifiersIncludingParents);
- };
- EventBlock.prototype.setSolWriterAfterCnds = function ()
- {
- this.solWriterAfterCnds = true;
- if (this.parent)
- this.parent.setSolWriterAfterCnds();
- };
- EventBlock.prototype.is_trigger = function ()
- {
- if (!this.conditions.length) // no conditions
- return false;
- else
- return this.conditions[0].trigger;
- };
- EventBlock.prototype.run = function ()
- {
- var i, len, c, any_true = false, cnd_result;
- var runtime = this.runtime;
- var evinfo = this.runtime.getCurrentEventStack();
- evinfo.current_event = this;
- var conditions = this.conditions;
- if (!this.is_else_block)
- evinfo.else_branch_ran = false;
- if (this.orblock)
- {
- if (conditions.length === 0)
- any_true = true; // be sure to run if empty block
- evinfo.cndindex = 0
- for (len = conditions.length; evinfo.cndindex < len; evinfo.cndindex++)
- {
- c = conditions[evinfo.cndindex];
- if (c.trigger) // skip triggers when running OR block
- continue;
- cnd_result = c.run();
- if (cnd_result) // make sure all conditions run and run if any were true
- any_true = true;
- }
- evinfo.last_event_true = any_true;
- if (any_true)
- this.run_actions_and_subevents();
- }
- else
- {
- evinfo.cndindex = 0
- for (len = conditions.length; evinfo.cndindex < len; evinfo.cndindex++)
- {
- cnd_result = conditions[evinfo.cndindex].run();
- if (!cnd_result) // condition failed
- {
- evinfo.last_event_true = false;
- if (this.toplevelevent && runtime.hasPendingInstances)
- runtime.ClearDeathRow();
- return; // bail out now
- }
- }
- evinfo.last_event_true = true;
- this.run_actions_and_subevents();
- }
- this.end_run(evinfo);
- };
- EventBlock.prototype.end_run = function (evinfo)
- {
- if (evinfo.last_event_true && this.has_else_block)
- evinfo.else_branch_ran = true;
- if (this.toplevelevent && this.runtime.hasPendingInstances)
- this.runtime.ClearDeathRow();
- };
- EventBlock.prototype.run_orblocktrigger = function (index)
- {
- var evinfo = this.runtime.getCurrentEventStack();
- evinfo.current_event = this;
- if (this.conditions[index].run())
- {
- this.run_actions_and_subevents();
- this.runtime.getCurrentEventStack().last_event_true = true;
- }
- };
- EventBlock.prototype.run_actions_and_subevents = function ()
- {
- var evinfo = this.runtime.getCurrentEventStack();
- var len;
- for (evinfo.actindex = 0, len = this.actions.length; evinfo.actindex < len; evinfo.actindex++)
- {
- if (this.actions[evinfo.actindex].run())
- return;
- }
- this.run_subevents();
- };
- EventBlock.prototype.resume_actions_and_subevents = function ()
- {
- var evinfo = this.runtime.getCurrentEventStack();
- var len;
- for (len = this.actions.length; evinfo.actindex < len; evinfo.actindex++)
- {
- if (this.actions[evinfo.actindex].run())
- return;
- }
- this.run_subevents();
- };
- EventBlock.prototype.run_subevents = function ()
- {
- if (!this.subevents.length)
- return;
- var i, len, subev, pushpop/*, skipped_pop = false, pop_modifiers = null*/;
- var last = this.subevents.length - 1;
- this.runtime.pushEventStack(this);
- if (this.solWriterAfterCnds)
- {
- for (i = 0, len = this.subevents.length; i < len; i++)
- {
- subev = this.subevents[i];
- pushpop = (!this.toplevelgroup || (!this.group && i < last));
- if (pushpop)
- this.runtime.pushCopySol(subev.solModifiers);
- subev.run();
- if (pushpop)
- this.runtime.popSol(subev.solModifiers);
- else
- this.runtime.clearSol(subev.solModifiers);
- }
- }
- else
- {
- for (i = 0, len = this.subevents.length; i < len; i++)
- {
- this.subevents[i].run();
- }
- }
- this.runtime.popEventStack();
- };
- EventBlock.prototype.run_pretrigger = function ()
- {
- var evinfo = this.runtime.getCurrentEventStack();
- evinfo.current_event = this;
- var any_true = false;
- var i, len;
- for (evinfo.cndindex = 0, len = this.conditions.length; evinfo.cndindex < len; evinfo.cndindex++)
- {
- ;
- if (this.conditions[evinfo.cndindex].run())
- any_true = true;
- else if (!this.orblock) // condition failed (let OR blocks run all conditions anyway)
- return false; // bail out
- }
- return this.orblock ? any_true : true;
- };
- EventBlock.prototype.retrigger = function ()
- {
- this.runtime.execcount++;
- var prevcndindex = this.runtime.getCurrentEventStack().cndindex;
- var len;
- var evinfo = this.runtime.pushEventStack(this);
- if (!this.orblock)
- {
- for (evinfo.cndindex = prevcndindex + 1, len = this.conditions.length; evinfo.cndindex < len; evinfo.cndindex++)
- {
- if (!this.conditions[evinfo.cndindex].run()) // condition failed
- {
- this.runtime.popEventStack(); // moving up level of recursion
- return false; // bail out
- }
- }
- }
- this.run_actions_and_subevents();
- this.runtime.popEventStack();
- return true; // ran an iteration
- };
- EventBlock.prototype.isFirstConditionOfType = function (cnd)
- {
- var cndindex = cnd.index;
- if (cndindex === 0)
- return true;
- --cndindex;
- for ( ; cndindex >= 0; --cndindex)
- {
- if (this.conditions[cndindex].type === cnd.type)
- return false;
- }
- return true;
- };
- cr.eventblock = EventBlock;
- function Condition(block, m)
- {
- this.block = block;
- this.sheet = block.sheet;
- this.runtime = block.runtime;
- this.parameters = [];
- this.results = [];
- this.extra = {}; // for plugins to stow away some custom info
- this.index = -1;
- this.anyParamVariesPerInstance = false;
- this.func = this.runtime.GetObjectReference(m[1]);
- ;
- this.trigger = (m[3] > 0);
- this.fasttrigger = (m[3] === 2);
- this.looping = m[4];
- this.inverted = m[5];
- this.isstatic = m[6];
- this.sid = m[7];
- this.runtime.cndsBySid[this.sid.toString()] = this;
- if (m[0] === -1) // system object
- {
- this.type = null;
- this.run = this.run_system;
- this.behaviortype = null;
- this.beh_index = -1;
- }
- else
- {
- this.type = this.runtime.types_by_index[m[0]];
- ;
- if (this.isstatic)
- this.run = this.run_static;
- else
- this.run = this.run_object;
- if (m[2])
- {
- this.behaviortype = this.type.getBehaviorByName(m[2]);
- ;
- this.beh_index = this.type.getBehaviorIndexByName(m[2]);
- ;
- }
- else
- {
- this.behaviortype = null;
- this.beh_index = -1;
- }
- if (this.block.parent)
- this.block.parent.setSolWriterAfterCnds();
- }
- if (this.fasttrigger)
- this.run = this.run_true;
- if (m.length === 10)
- {
- var i, len;
- var em = m[9];
- for (i = 0, len = em.length; i < len; i++)
- {
- var param = new cr.parameter(this, em[i]);
- cr.seal(param);
- this.parameters.push(param);
- }
- this.results.length = em.length;
- }
- };
- Condition.prototype.postInit = function ()
- {
- var i, len, p;
- for (i = 0, len = this.parameters.length; i < len; i++)
- {
- p = this.parameters[i];
- p.postInit();
- if (p.variesPerInstance)
- this.anyParamVariesPerInstance = true;
- }
- };
- /*
- Condition.prototype.is_logical = function ()
- {
- return !this.type || this.type.plugin.singleglobal;
- };
- */
- Condition.prototype.run_true = function ()
- {
- return true;
- };
- Condition.prototype.run_system = function ()
- {
- var i, len;
- for (i = 0, len = this.parameters.length; i < len; i++)
- this.results[i] = this.parameters[i].get();
- return cr.xor(this.func.apply(this.runtime.system, this.results), this.inverted);
- };
- Condition.prototype.run_static = function ()
- {
- var i, len;
- for (i = 0, len = this.parameters.length; i < len; i++)
- this.results[i] = this.parameters[i].get();
- var ret = this.func.apply(this.behaviortype ? this.behaviortype : this.type, this.results);
- this.type.applySolToContainer();
- return ret;
- };
- Condition.prototype.run_object = function ()
- {
- var i, j, k, leni, lenj, p, ret, met, inst, s, sol2;
- var type = this.type;
- var sol = type.getCurrentSol();
- var is_orblock = this.block.orblock && !this.trigger; // triggers in OR blocks need to work normally
- var offset = 0;
- var is_contained = type.is_contained;
- var is_family = type.is_family;
- var family_index = type.family_index;
- var beh_index = this.beh_index;
- var is_beh = (beh_index > -1);
- var params_vary = this.anyParamVariesPerInstance;
- var parameters = this.parameters;
- var results = this.results;
- var inverted = this.inverted;
- var func = this.func;
- var arr, container;
- if (params_vary)
- {
- for (j = 0, lenj = parameters.length; j < lenj; ++j)
- {
- p = parameters[j];
- if (!p.variesPerInstance)
- results[j] = p.get(0);
- }
- }
- else
- {
- for (j = 0, lenj = parameters.length; j < lenj; ++j)
- results[j] = parameters[j].get(0);
- }
- if (sol.select_all) {
- cr.clearArray(sol.instances); // clear contents
- cr.clearArray(sol.else_instances);
- arr = type.instances;
- for (i = 0, leni = arr.length; i < leni; ++i)
- {
- inst = arr[i];
- ;
- if (params_vary)
- {
- for (j = 0, lenj = parameters.length; j < lenj; ++j)
- {
- p = parameters[j];
- if (p.variesPerInstance)
- results[j] = p.get(i); // default SOL index is current object
- }
- }
- if (is_beh)
- {
- offset = 0;
- if (is_family)
- {
- offset = inst.type.family_beh_map[family_index];
- }
- ret = func.apply(inst.behavior_insts[beh_index + offset], results);
- }
- else
- ret = func.apply(inst, results);
- met = cr.xor(ret, inverted);
- if (met)
- sol.instances.push(inst);
- else if (is_orblock) // in OR blocks, keep the instances not meeting the condition for subsequent testing
- sol.else_instances.push(inst);
- }
- if (type.finish)
- type.finish(true);
- sol.select_all = false;
- type.applySolToContainer();
- return sol.hasObjects();
- }
- else {
- k = 0;
- var using_else_instances = (is_orblock && !this.block.isFirstConditionOfType(this));
- arr = (using_else_instances ? sol.else_instances : sol.instances);
- var any_true = false;
- for (i = 0, leni = arr.length; i < leni; ++i)
- {
- inst = arr[i];
- ;
- if (params_vary)
- {
- for (j = 0, lenj = parameters.length; j < lenj; ++j)
- {
- p = parameters[j];
- if (p.variesPerInstance)
- results[j] = p.get(i); // default SOL index is current object
- }
- }
- if (is_beh)
- {
- offset = 0;
- if (is_family)
- {
- offset = inst.type.family_beh_map[family_index];
- }
- ret = func.apply(inst.behavior_insts[beh_index + offset], results);
- }
- else
- ret = func.apply(inst, results);
- if (cr.xor(ret, inverted))
- {
- any_true = true;
- if (using_else_instances)
- {
- sol.instances.push(inst);
- if (is_contained)
- {
- for (j = 0, lenj = inst.siblings.length; j < lenj; j++)
- {
- s = inst.siblings[j];
- s.type.getCurrentSol().instances.push(s);
- }
- }
- }
- else
- {
- arr[k] = inst;
- if (is_contained)
- {
- for (j = 0, lenj = inst.siblings.length; j < lenj; j++)
- {
- s = inst.siblings[j];
- s.type.getCurrentSol().instances[k] = s;
- }
- }
- k++;
- }
- }
- else
- {
- if (using_else_instances)
- {
- arr[k] = inst;
- if (is_contained)
- {
- for (j = 0, lenj = inst.siblings.length; j < lenj; j++)
- {
- s = inst.siblings[j];
- s.type.getCurrentSol().else_instances[k] = s;
- }
- }
- k++;
- }
- else if (is_orblock)
- {
- sol.else_instances.push(inst);
- if (is_contained)
- {
- for (j = 0, lenj = inst.siblings.length; j < lenj; j++)
- {
- s = inst.siblings[j];
- s.type.getCurrentSol().else_instances.push(s);
- }
- }
- }
- }
- }
- cr.truncateArray(arr, k);
- if (is_contained)
- {
- container = type.container;
- for (i = 0, leni = container.length; i < leni; i++)
- {
- sol2 = container[i].getCurrentSol();
- if (using_else_instances)
- cr.truncateArray(sol2.else_instances, k);
- else
- cr.truncateArray(sol2.instances, k);
- }
- }
- var pick_in_finish = any_true; // don't pick in finish() if we're only doing the logic test below
- if (using_else_instances && !any_true)
- {
- for (i = 0, leni = sol.instances.length; i < leni; i++)
- {
- inst = sol.instances[i];
- if (params_vary)
- {
- for (j = 0, lenj = parameters.length; j < lenj; j++)
- {
- p = parameters[j];
- if (p.variesPerInstance)
- results[j] = p.get(i);
- }
- }
- if (is_beh)
- ret = func.apply(inst.behavior_insts[beh_index], results);
- else
- ret = func.apply(inst, results);
- if (cr.xor(ret, inverted))
- {
- any_true = true;
- break; // got our flag, don't need to test any more
- }
- }
- }
- if (type.finish)
- type.finish(pick_in_finish || is_orblock);
- return is_orblock ? any_true : sol.hasObjects();
- }
- };
- cr.condition = Condition;
- function Action(block, m)
- {
- this.block = block;
- this.sheet = block.sheet;
- this.runtime = block.runtime;
- this.parameters = [];
- this.results = [];
- this.extra = {}; // for plugins to stow away some custom info
- this.index = -1;
- this.anyParamVariesPerInstance = false;
- this.func = this.runtime.GetObjectReference(m[1]);
- ;
- if (m[0] === -1) // system
- {
- this.type = null;
- this.run = this.run_system;
- this.behaviortype = null;
- this.beh_index = -1;
- }
- else
- {
- this.type = this.runtime.types_by_index[m[0]];
- ;
- this.run = this.run_object;
- if (m[2])
- {
- this.behaviortype = this.type.getBehaviorByName(m[2]);
- ;
- this.beh_index = this.type.getBehaviorIndexByName(m[2]);
- ;
- }
- else
- {
- this.behaviortype = null;
- this.beh_index = -1;
- }
- }
- this.sid = m[3];
- this.runtime.actsBySid[this.sid.toString()] = this;
- if (m.length === 6)
- {
- var i, len;
- var em = m[5];
- for (i = 0, len = em.length; i < len; i++)
- {
- var param = new cr.parameter(this, em[i]);
- cr.seal(param);
- this.parameters.push(param);
- }
- this.results.length = em.length;
- }
- };
- Action.prototype.postInit = function ()
- {
- var i, len, p;
- for (i = 0, len = this.parameters.length; i < len; i++)
- {
- p = this.parameters[i];
- p.postInit();
- if (p.variesPerInstance)
- this.anyParamVariesPerInstance = true;
- }
- };
- Action.prototype.run_system = function ()
- {
- var runtime = this.runtime;
- var i, len;
- var parameters = this.parameters;
- var results = this.results;
- for (i = 0, len = parameters.length; i < len; ++i)
- results[i] = parameters[i].get();
- return this.func.apply(runtime.system, results);
- };
- Action.prototype.run_object = function ()
- {
- var type = this.type;
- var beh_index = this.beh_index;
- var family_index = type.family_index;
- var params_vary = this.anyParamVariesPerInstance;
- var parameters = this.parameters;
- var results = this.results;
- var func = this.func;
- var instances = type.getCurrentSol().getObjects();
- var is_family = type.is_family;
- var is_beh = (beh_index > -1);
- var i, j, leni, lenj, p, inst, offset;
- if (params_vary)
- {
- for (j = 0, lenj = parameters.length; j < lenj; ++j)
- {
- p = parameters[j];
- if (!p.variesPerInstance)
- results[j] = p.get(0);
- }
- }
- else
- {
- for (j = 0, lenj = parameters.length; j < lenj; ++j)
- results[j] = parameters[j].get(0);
- }
- for (i = 0, leni = instances.length; i < leni; ++i)
- {
- inst = instances[i];
- if (params_vary)
- {
- for (j = 0, lenj = parameters.length; j < lenj; ++j)
- {
- p = parameters[j];
- if (p.variesPerInstance)
- results[j] = p.get(i); // pass i to use as default SOL index
- }
- }
- if (is_beh)
- {
- offset = 0;
- if (is_family)
- {
- offset = inst.type.family_beh_map[family_index];
- }
- func.apply(inst.behavior_insts[beh_index + offset], results);
- }
- else
- func.apply(inst, results);
- }
- return false;
- };
- cr.action = Action;
- var tempValues = [];
- var tempValuesPtr = -1;
- function pushTempValue()
- {
- tempValuesPtr++;
- if (tempValues.length === tempValuesPtr)
- tempValues.push(new cr.expvalue());
- return tempValues[tempValuesPtr];
- };
- function popTempValue()
- {
- tempValuesPtr--;
- };
- function Parameter(owner, m)
- {
- this.owner = owner;
- this.block = owner.block;
- this.sheet = owner.sheet;
- this.runtime = owner.runtime;
- this.type = m[0];
- this.expression = null;
- this.solindex = 0;
- this.get = null;
- this.combosel = 0;
- this.layout = null;
- this.key = 0;
- this.object = null;
- this.index = 0;
- this.varname = null;
- this.eventvar = null;
- this.fileinfo = null;
- this.subparams = null;
- this.variadicret = null;
- this.subparams = null;
- this.variadicret = null;
- this.variesPerInstance = false;
- var i, len, param;
- switch (m[0])
- {
- case 0: // number
- case 7: // any
- this.expression = new cr.expNode(this, m[1]);
- this.solindex = 0;
- this.get = this.get_exp;
- break;
- case 1: // string
- this.expression = new cr.expNode(this, m[1]);
- this.solindex = 0;
- this.get = this.get_exp_str;
- break;
- case 5: // layer
- this.expression = new cr.expNode(this, m[1]);
- this.solindex = 0;
- this.get = this.get_layer;
- break;
- case 3: // combo
- case 8: // cmp
- this.combosel = m[1];
- this.get = this.get_combosel;
- break;
- case 6: // layout
- this.layout = this.runtime.layouts[m[1]];
- ;
- this.get = this.get_layout;
- break;
- case 9: // keyb
- this.key = m[1];
- this.get = this.get_key;
- break;
- case 4: // object
- this.object = this.runtime.types_by_index[m[1]];
- ;
- this.get = this.get_object;
- this.block.addSolModifier(this.object);
- if (this.owner instanceof cr.action)
- this.block.setSolWriterAfterCnds();
- else if (this.block.parent)
- this.block.parent.setSolWriterAfterCnds();
- break;
- case 10: // instvar
- this.index = m[1];
- if (owner.type.is_family)
- {
- this.get = this.get_familyvar;
- this.variesPerInstance = true;
- }
- else
- this.get = this.get_instvar;
- break;
- case 11: // eventvar
- this.varname = m[1];
- this.eventvar = null;
- this.get = this.get_eventvar;
- break;
- case 2: // audiofile ["name", ismusic]
- case 12: // fileinfo "name"
- this.fileinfo = m[1];
- this.get = this.get_audiofile;
- break;
- case 13: // variadic
- this.get = this.get_variadic;
- this.subparams = [];
- this.variadicret = [];
- for (i = 1, len = m.length; i < len; i++)
- {
- param = new cr.parameter(this.owner, m[i]);
- cr.seal(param);
- this.subparams.push(param);
- this.variadicret.push(0);
- }
- break;
- default:
- ;
- }
- };
- Parameter.prototype.postInit = function ()
- {
- var i, len;
- if (this.type === 11) // eventvar
- {
- this.eventvar = this.runtime.getEventVariableByName(this.varname, this.block.parent);
- ;
- }
- else if (this.type === 13) // variadic, postInit all sub-params
- {
- for (i = 0, len = this.subparams.length; i < len; i++)
- this.subparams[i].postInit();
- }
- if (this.expression)
- this.expression.postInit();
- };
- Parameter.prototype.maybeVaryForType = function (t)
- {
- if (this.variesPerInstance)
- return; // already varies per instance, no need to check again
- if (!t)
- return; // never vary for system type
- if (!t.plugin.singleglobal)
- {
- this.variesPerInstance = true;
- return;
- }
- };
- Parameter.prototype.setVaries = function ()
- {
- this.variesPerInstance = true;
- };
- Parameter.prototype.get_exp = function (solindex)
- {
- this.solindex = solindex || 0; // default SOL index to use
- var temp = pushTempValue();
- this.expression.get(temp);
- popTempValue();
- return temp.data; // return actual JS value, not expvalue
- };
- Parameter.prototype.get_exp_str = function (solindex)
- {
- this.solindex = solindex || 0; // default SOL index to use
- var temp = pushTempValue();
- this.expression.get(temp);
- popTempValue();
- if (cr.is_string(temp.data))
- return temp.data;
- else
- return "";
- };
- Parameter.prototype.get_object = function ()
- {
- return this.object;
- };
- Parameter.prototype.get_combosel = function ()
- {
- return this.combosel;
- };
- Parameter.prototype.get_layer = function (solindex)
- {
- this.solindex = solindex || 0; // default SOL index to use
- var temp = pushTempValue();
- this.expression.get(temp);
- popTempValue();
- if (temp.is_number())
- return this.runtime.getLayerByNumber(temp.data);
- else
- return this.runtime.getLayerByName(temp.data);
- }
- Parameter.prototype.get_layout = function ()
- {
- return this.layout;
- };
- Parameter.prototype.get_key = function ()
- {
- return this.key;
- };
- Parameter.prototype.get_instvar = function ()
- {
- return this.index;
- };
- Parameter.prototype.get_familyvar = function (solindex_)
- {
- var solindex = solindex_ || 0;
- var familytype = this.owner.type;
- var realtype = null;
- var sol = familytype.getCurrentSol();
- var objs = sol.getObjects();
- if (objs.length)
- realtype = objs[solindex % objs.length].type;
- else if (sol.else_instances.length)
- realtype = sol.else_instances[solindex % sol.else_instances.length].type;
- else if (familytype.instances.length)
- realtype = familytype.instances[solindex % familytype.instances.length].type;
- else
- return 0;
- return this.index + realtype.family_var_map[familytype.family_index];
- };
- Parameter.prototype.get_eventvar = function ()
- {
- return this.eventvar;
- };
- Parameter.prototype.get_audiofile = function ()
- {
- return this.fileinfo;
- };
- Parameter.prototype.get_variadic = function ()
- {
- var i, len;
- for (i = 0, len = this.subparams.length; i < len; i++)
- {
- this.variadicret[i] = this.subparams[i].get();
- }
- return this.variadicret;
- };
- cr.parameter = Parameter;
- function EventVariable(sheet, parent, m)
- {
- this.sheet = sheet;
- this.parent = parent;
- this.runtime = sheet.runtime;
- this.solModifiers = [];
- this.name = m[1];
- this.vartype = m[2];
- this.initial = m[3];
- this.is_static = !!m[4];
- this.is_constant = !!m[5];
- this.sid = m[6];
- this.runtime.varsBySid[this.sid.toString()] = this;
- this.data = this.initial; // note: also stored in event stack frame for local nonstatic nonconst vars
- if (this.parent) // local var
- {
- if (this.is_static || this.is_constant)
- this.localIndex = -1;
- else
- this.localIndex = this.runtime.stackLocalCount++;
- this.runtime.all_local_vars.push(this);
- }
- else // global var
- {
- this.localIndex = -1;
- this.runtime.all_global_vars.push(this);
- }
- };
- EventVariable.prototype.postInit = function ()
- {
- this.solModifiers = findMatchingSolModifier(this.solModifiers);
- };
- EventVariable.prototype.setValue = function (x)
- {
- ;
- var lvs = this.runtime.getCurrentLocalVarStack();
- if (!this.parent || this.is_static || !lvs)
- this.data = x;
- else // local nonstatic variable: use event stack to keep value at this level of recursion
- {
- if (this.localIndex >= lvs.length)
- lvs.length = this.localIndex + 1;
- lvs[this.localIndex] = x;
- }
- };
- EventVariable.prototype.getValue = function ()
- {
- var lvs = this.runtime.getCurrentLocalVarStack();
- if (!this.parent || this.is_static || !lvs || this.is_constant)
- return this.data;
- else // local nonstatic variable
- {
- if (this.localIndex >= lvs.length)
- {
- ;
- return this.initial;
- }
- if (typeof lvs[this.localIndex] === "undefined")
- {
- ;
- return this.initial;
- }
- return lvs[this.localIndex];
- }
- };
- EventVariable.prototype.run = function ()
- {
- if (this.parent && !this.is_static && !this.is_constant)
- this.setValue(this.initial);
- };
- cr.eventvariable = EventVariable;
- function EventInclude(sheet, parent, m)
- {
- this.sheet = sheet;
- this.parent = parent;
- this.runtime = sheet.runtime;
- this.solModifiers = [];
- this.include_sheet = null; // determined in postInit
- this.include_sheet_name = m[1];
- this.active = true;
- };
- EventInclude.prototype.toString = function ()
- {
- return "include:" + this.include_sheet.toString();
- };
- EventInclude.prototype.postInit = function ()
- {
- this.include_sheet = this.runtime.eventsheets[this.include_sheet_name];
- ;
- ;
- this.sheet.includes.add(this);
- this.solModifiers = findMatchingSolModifier(this.solModifiers);
- var p = this.parent;
- while (p)
- {
- if (p.group)
- p.contained_includes.push(this);
- p = p.parent;
- }
- this.updateActive();
- };
- EventInclude.prototype.run = function ()
- {
- if (this.parent)
- this.runtime.pushCleanSol(this.runtime.types_by_index);
- if (!this.include_sheet.hasRun)
- this.include_sheet.run(true); // from include
- if (this.parent)
- this.runtime.popSol(this.runtime.types_by_index);
- };
- EventInclude.prototype.updateActive = function ()
- {
- var p = this.parent;
- while (p)
- {
- if (p.group && !p.group_active)
- {
- this.active = false;
- return;
- }
- p = p.parent;
- }
- this.active = true;
- };
- EventInclude.prototype.isActive = function ()
- {
- return this.active;
- };
- cr.eventinclude = EventInclude;
- function EventStackFrame()
- {
- this.temp_parents_arr = [];
- this.reset(null);
- cr.seal(this);
- };
- EventStackFrame.prototype.reset = function (cur_event)
- {
- this.current_event = cur_event;
- this.cndindex = 0;
- this.actindex = 0;
- cr.clearArray(this.temp_parents_arr);
- this.last_event_true = false;
- this.else_branch_ran = false;
- this.any_true_state = false;
- };
- EventStackFrame.prototype.isModifierAfterCnds = function ()
- {
- if (this.current_event.solWriterAfterCnds)
- return true;
- if (this.cndindex < this.current_event.conditions.length - 1)
- return !!this.current_event.solModifiers.length;
- return false;
- };
- cr.eventStackFrame = EventStackFrame;
- }());
- (function()
- {
- function ExpNode(owner_, m)
- {
- this.owner = owner_;
- this.runtime = owner_.runtime;
- this.type = m[0];
- ;
- this.get = [this.eval_int,
- this.eval_float,
- this.eval_string,
- this.eval_unaryminus,
- this.eval_add,
- this.eval_subtract,
- this.eval_multiply,
- this.eval_divide,
- this.eval_mod,
- this.eval_power,
- this.eval_and,
- this.eval_or,
- this.eval_equal,
- this.eval_notequal,
- this.eval_less,
- this.eval_lessequal,
- this.eval_greater,
- this.eval_greaterequal,
- this.eval_conditional,
- this.eval_system_exp,
- this.eval_object_exp,
- this.eval_instvar_exp,
- this.eval_behavior_exp,
- this.eval_eventvar_exp][this.type];
- var paramsModel = null;
- this.value = null;
- this.first = null;
- this.second = null;
- this.third = null;
- this.func = null;
- this.results = null;
- this.parameters = null;
- this.object_type = null;
- this.beh_index = -1;
- this.instance_expr = null;
- this.varindex = -1;
- this.behavior_type = null;
- this.varname = null;
- this.eventvar = null;
- this.return_string = false;
- switch (this.type) {
- case 0: // int
- case 1: // float
- case 2: // string
- this.value = m[1];
- break;
- case 3: // unaryminus
- this.first = new cr.expNode(owner_, m[1]);
- break;
- case 18: // conditional
- this.first = new cr.expNode(owner_, m[1]);
- this.second = new cr.expNode(owner_, m[2]);
- this.third = new cr.expNode(owner_, m[3]);
- break;
- case 19: // system_exp
- this.func = this.runtime.GetObjectReference(m[1]);
- ;
- if (this.func === cr.system_object.prototype.exps.random
- || this.func === cr.system_object.prototype.exps.choose)
- {
- this.owner.setVaries();
- }
- this.results = [];
- this.parameters = [];
- if (m.length === 3)
- {
- paramsModel = m[2];
- this.results.length = paramsModel.length + 1; // must also fit 'ret'
- }
- else
- this.results.length = 1; // to fit 'ret'
- break;
- case 20: // object_exp
- this.object_type = this.runtime.types_by_index[m[1]];
- ;
- this.beh_index = -1;
- this.func = this.runtime.GetObjectReference(m[2]);
- this.return_string = m[3];
- if (cr.plugins_.Function && this.func === cr.plugins_.Function.prototype.exps.Call)
- {
- this.owner.setVaries();
- }
- if (m[4])
- this.instance_expr = new cr.expNode(owner_, m[4]);
- else
- this.instance_expr = null;
- this.results = [];
- this.parameters = [];
- if (m.length === 6)
- {
- paramsModel = m[5];
- this.results.length = paramsModel.length + 1;
- }
- else
- this.results.length = 1; // to fit 'ret'
- break;
- case 21: // instvar_exp
- this.object_type = this.runtime.types_by_index[m[1]];
- ;
- this.return_string = m[2];
- if (m[3])
- this.instance_expr = new cr.expNode(owner_, m[3]);
- else
- this.instance_expr = null;
- this.varindex = m[4];
- break;
- case 22: // behavior_exp
- this.object_type = this.runtime.types_by_index[m[1]];
- ;
- this.behavior_type = this.object_type.getBehaviorByName(m[2]);
- ;
- this.beh_index = this.object_type.getBehaviorIndexByName(m[2]);
- this.func = this.runtime.GetObjectReference(m[3]);
- this.return_string = m[4];
- if (m[5])
- this.instance_expr = new cr.expNode(owner_, m[5]);
- else
- this.instance_expr = null;
- this.results = [];
- this.parameters = [];
- if (m.length === 7)
- {
- paramsModel = m[6];
- this.results.length = paramsModel.length + 1;
- }
- else
- this.results.length = 1; // to fit 'ret'
- break;
- case 23: // eventvar_exp
- this.varname = m[1];
- this.eventvar = null; // assigned in postInit
- break;
- }
- this.owner.maybeVaryForType(this.object_type);
- if (this.type >= 4 && this.type <= 17)
- {
- this.first = new cr.expNode(owner_, m[1]);
- this.second = new cr.expNode(owner_, m[2]);
- }
- if (paramsModel)
- {
- var i, len;
- for (i = 0, len = paramsModel.length; i < len; i++)
- this.parameters.push(new cr.expNode(owner_, paramsModel[i]));
- }
- cr.seal(this);
- };
- ExpNode.prototype.postInit = function ()
- {
- if (this.type === 23) // eventvar_exp
- {
- this.eventvar = this.owner.runtime.getEventVariableByName(this.varname, this.owner.block.parent);
- ;
- }
- if (this.first)
- this.first.postInit();
- if (this.second)
- this.second.postInit();
- if (this.third)
- this.third.postInit();
- if (this.instance_expr)
- this.instance_expr.postInit();
- if (this.parameters)
- {
- var i, len;
- for (i = 0, len = this.parameters.length; i < len; i++)
- this.parameters[i].postInit();
- }
- };
- var tempValues = [];
- var tempValuesPtr = -1;
- function pushTempValue()
- {
- ++tempValuesPtr;
- if (tempValues.length === tempValuesPtr)
- tempValues.push(new cr.expvalue());
- return tempValues[tempValuesPtr];
- };
- function popTempValue()
- {
- --tempValuesPtr;
- };
- function eval_params(parameters, results, temp)
- {
- var i, len;
- for (i = 0, len = parameters.length; i < len; ++i)
- {
- parameters[i].get(temp);
- results[i + 1] = temp.data; // passing actual javascript value as argument instead of expvalue
- }
- }
- ExpNode.prototype.eval_system_exp = function (ret)
- {
- var parameters = this.parameters;
- var results = this.results;
- results[0] = ret;
- var temp = pushTempValue();
- eval_params(parameters, results, temp);
- popTempValue();
- this.func.apply(this.runtime.system, results);
- };
- ExpNode.prototype.eval_object_exp = function (ret)
- {
- var object_type = this.object_type;
- var results = this.results;
- var parameters = this.parameters;
- var instance_expr = this.instance_expr;
- var func = this.func;
- var index = this.owner.solindex; // default to parameter's intended SOL index
- var sol = object_type.getCurrentSol();
- var instances = sol.getObjects();
- if (!instances.length)
- {
- if (sol.else_instances.length)
- instances = sol.else_instances;
- else
- {
- if (this.return_string)
- ret.set_string("");
- else
- ret.set_int(0);
- return;
- }
- }
- results[0] = ret;
- ret.object_class = object_type; // so expression can access family type if need be
- var temp = pushTempValue();
- eval_params(parameters, results, temp);
- if (instance_expr) {
- instance_expr.get(temp);
- if (temp.is_number()) {
- index = temp.data;
- instances = object_type.instances; // pick from all instances, not SOL
- }
- }
- popTempValue();
- var len = instances.length;
- if (index >= len || index <= -len)
- index %= len; // wraparound
- if (index < 0)
- index += len;
- var returned_val = func.apply(instances[index], results);
- ;
- };
- ExpNode.prototype.eval_behavior_exp = function (ret)
- {
- var object_type = this.object_type;
- var results = this.results;
- var parameters = this.parameters;
- var instance_expr = this.instance_expr;
- var beh_index = this.beh_index;
- var func = this.func;
- var index = this.owner.solindex; // default to parameter's intended SOL index
- var sol = object_type.getCurrentSol();
- var instances = sol.getObjects();
- if (!instances.length)
- {
- if (sol.else_instances.length)
- instances = sol.else_instances;
- else
- {
- if (this.return_string)
- ret.set_string("");
- else
- ret.set_int(0);
- return;
- }
- }
- results[0] = ret;
- ret.object_class = object_type; // so expression can access family type if need be
- var temp = pushTempValue();
- eval_params(parameters, results, temp);
- if (instance_expr) {
- instance_expr.get(temp);
- if (temp.is_number()) {
- index = temp.data;
- instances = object_type.instances; // pick from all instances, not SOL
- }
- }
- popTempValue();
- var len = instances.length;
- if (index >= len || index <= -len)
- index %= len; // wraparound
- if (index < 0)
- index += len;
- var inst = instances[index];
- var offset = 0;
- if (object_type.is_family)
- {
- offset = inst.type.family_beh_map[object_type.family_index];
- }
- var returned_val = func.apply(inst.behavior_insts[beh_index + offset], results);
- ;
- };
- ExpNode.prototype.eval_instvar_exp = function (ret)
- {
- var instance_expr = this.instance_expr;
- var object_type = this.object_type;
- var varindex = this.varindex;
- var index = this.owner.solindex; // default to parameter's intended SOL index
- var sol = object_type.getCurrentSol();
- var instances = sol.getObjects();
- if (!instances.length)
- {
- if (sol.else_instances.length)
- instances = sol.else_instances;
- else
- {
- if (this.return_string)
- ret.set_string("");
- else
- ret.set_int(0);
- return;
- }
- }
- if (instance_expr)
- {
- var temp = pushTempValue();
- instance_expr.get(temp);
- if (temp.is_number())
- {
- index = temp.data;
- var type_instances = object_type.instances;
- index %= type_instances.length; // wraparound
- if (index < 0) // offset
- index += type_instances.length;
- var to_ret = type_instances[index].instance_vars[varindex];
- if (cr.is_string(to_ret))
- ret.set_string(to_ret);
- else
- ret.set_float(to_ret);
- popTempValue();
- return; // done
- }
- popTempValue();
- }
- var len = instances.length;
- if (index >= len || index <= -len)
- index %= len; // wraparound
- if (index < 0)
- index += len;
- var inst = instances[index];
- var offset = 0;
- if (object_type.is_family)
- {
- offset = inst.type.family_var_map[object_type.family_index];
- }
- var to_ret = inst.instance_vars[varindex + offset];
- if (cr.is_string(to_ret))
- ret.set_string(to_ret);
- else
- ret.set_float(to_ret);
- };
- ExpNode.prototype.eval_int = function (ret)
- {
- ret.type = cr.exptype.Integer;
- ret.data = this.value;
- };
- ExpNode.prototype.eval_float = function (ret)
- {
- ret.type = cr.exptype.Float;
- ret.data = this.value;
- };
- ExpNode.prototype.eval_string = function (ret)
- {
- ret.type = cr.exptype.String;
- ret.data = this.value;
- };
- ExpNode.prototype.eval_unaryminus = function (ret)
- {
- this.first.get(ret); // retrieve operand
- if (ret.is_number())
- ret.data = -ret.data;
- };
- ExpNode.prototype.eval_add = function (ret)
- {
- this.first.get(ret); // left operand
- var temp = pushTempValue();
- this.second.get(temp); // right operand
- if (ret.is_number() && temp.is_number())
- {
- ret.data += temp.data; // both operands numbers: add
- if (temp.is_float())
- ret.make_float();
- }
- popTempValue();
- };
- ExpNode.prototype.eval_subtract = function (ret)
- {
- this.first.get(ret); // left operand
- var temp = pushTempValue();
- this.second.get(temp); // right operand
- if (ret.is_number() && temp.is_number())
- {
- ret.data -= temp.data; // both operands numbers: subtract
- if (temp.is_float())
- ret.make_float();
- }
- popTempValue();
- };
- ExpNode.prototype.eval_multiply = function (ret)
- {
- this.first.get(ret); // left operand
- var temp = pushTempValue();
- this.second.get(temp); // right operand
- if (ret.is_number() && temp.is_number())
- {
- ret.data *= temp.data; // both operands numbers: multiply
- if (temp.is_float())
- ret.make_float();
- }
- popTempValue();
- };
- ExpNode.prototype.eval_divide = function (ret)
- {
- this.first.get(ret); // left operand
- var temp = pushTempValue();
- this.second.get(temp); // right operand
- if (ret.is_number() && temp.is_number())
- {
- ret.data /= temp.data; // both operands numbers: divide
- ret.make_float();
- }
- popTempValue();
- };
- ExpNode.prototype.eval_mod = function (ret)
- {
- this.first.get(ret); // left operand
- var temp = pushTempValue();
- this.second.get(temp); // right operand
- if (ret.is_number() && temp.is_number())
- {
- ret.data %= temp.data; // both operands numbers: modulo
- if (temp.is_float())
- ret.make_float();
- }
- popTempValue();
- };
- ExpNode.prototype.eval_power = function (ret)
- {
- this.first.get(ret); // left operand
- var temp = pushTempValue();
- this.second.get(temp); // right operand
- if (ret.is_number() && temp.is_number())
- {
- ret.data = Math.pow(ret.data, temp.data); // both operands numbers: raise to power
- if (temp.is_float())
- ret.make_float();
- }
- popTempValue();
- };
- ExpNode.prototype.eval_and = function (ret)
- {
- this.first.get(ret); // left operand
- var temp = pushTempValue();
- this.second.get(temp); // right operand
- if (temp.is_string() || ret.is_string())
- this.eval_and_stringconcat(ret, temp);
- else
- this.eval_and_logical(ret, temp);
- popTempValue();
- };
- ExpNode.prototype.eval_and_stringconcat = function (ret, temp)
- {
- if (ret.is_string() && temp.is_string())
- this.eval_and_stringconcat_str_str(ret, temp);
- else
- this.eval_and_stringconcat_num(ret, temp);
- };
- ExpNode.prototype.eval_and_stringconcat_str_str = function (ret, temp)
- {
- ret.data += temp.data;
- };
- ExpNode.prototype.eval_and_stringconcat_num = function (ret, temp)
- {
- if (ret.is_string())
- {
- ret.data += (Math.round(temp.data * 1e10) / 1e10).toString();
- }
- else
- {
- ret.set_string(ret.data.toString() + temp.data);
- }
- };
- ExpNode.prototype.eval_and_logical = function (ret, temp)
- {
- ret.set_int(ret.data && temp.data ? 1 : 0);
- };
- ExpNode.prototype.eval_or = function (ret)
- {
- this.first.get(ret); // left operand
- var temp = pushTempValue();
- this.second.get(temp); // right operand
- if (ret.is_number() && temp.is_number())
- {
- if (ret.data || temp.data)
- ret.set_int(1);
- else
- ret.set_int(0);
- }
- popTempValue();
- };
- ExpNode.prototype.eval_conditional = function (ret)
- {
- this.first.get(ret); // condition operand
- if (ret.data) // is true
- this.second.get(ret); // evaluate second operand to ret
- else
- this.third.get(ret); // evaluate third operand to ret
- };
- ExpNode.prototype.eval_equal = function (ret)
- {
- this.first.get(ret); // left operand
- var temp = pushTempValue();
- this.second.get(temp); // right operand
- ret.set_int(ret.data === temp.data ? 1 : 0);
- popTempValue();
- };
- ExpNode.prototype.eval_notequal = function (ret)
- {
- this.first.get(ret); // left operand
- var temp = pushTempValue();
- this.second.get(temp); // right operand
- ret.set_int(ret.data !== temp.data ? 1 : 0);
- popTempValue();
- };
- ExpNode.prototype.eval_less = function (ret)
- {
- this.first.get(ret); // left operand
- var temp = pushTempValue();
- this.second.get(temp); // right operand
- ret.set_int(ret.data < temp.data ? 1 : 0);
- popTempValue();
- };
- ExpNode.prototype.eval_lessequal = function (ret)
- {
- this.first.get(ret); // left operand
- var temp = pushTempValue();
- this.second.get(temp); // right operand
- ret.set_int(ret.data <= temp.data ? 1 : 0);
- popTempValue();
- };
- ExpNode.prototype.eval_greater = function (ret)
- {
- this.first.get(ret); // left operand
- var temp = pushTempValue();
- this.second.get(temp); // right operand
- ret.set_int(ret.data > temp.data ? 1 : 0);
- popTempValue();
- };
- ExpNode.prototype.eval_greaterequal = function (ret)
- {
- this.first.get(ret); // left operand
- var temp = pushTempValue();
- this.second.get(temp); // right operand
- ret.set_int(ret.data >= temp.data ? 1 : 0);
- popTempValue();
- };
- ExpNode.prototype.eval_eventvar_exp = function (ret)
- {
- var val = this.eventvar.getValue();
- if (cr.is_number(val))
- ret.set_float(val);
- else
- ret.set_string(val);
- };
- cr.expNode = ExpNode;
- function ExpValue(type, data)
- {
- this.type = type || cr.exptype.Integer;
- this.data = data || 0;
- this.object_class = null;
- ;
- ;
- ;
- if (this.type == cr.exptype.Integer)
- this.data = Math.floor(this.data);
- cr.seal(this);
- };
- ExpValue.prototype.is_int = function ()
- {
- return this.type === cr.exptype.Integer;
- };
- ExpValue.prototype.is_float = function ()
- {
- return this.type === cr.exptype.Float;
- };
- ExpValue.prototype.is_number = function ()
- {
- return this.type === cr.exptype.Integer || this.type === cr.exptype.Float;
- };
- ExpValue.prototype.is_string = function ()
- {
- return this.type === cr.exptype.String;
- };
- ExpValue.prototype.make_int = function ()
- {
- if (!this.is_int())
- {
- if (this.is_float())
- this.data = Math.floor(this.data); // truncate float
- else if (this.is_string())
- this.data = parseInt(this.data, 10);
- this.type = cr.exptype.Integer;
- }
- };
- ExpValue.prototype.make_float = function ()
- {
- if (!this.is_float())
- {
- if (this.is_string())
- this.data = parseFloat(this.data);
- this.type = cr.exptype.Float;
- }
- };
- ExpValue.prototype.make_string = function ()
- {
- if (!this.is_string())
- {
- this.data = this.data.toString();
- this.type = cr.exptype.String;
- }
- };
- ExpValue.prototype.set_int = function (val)
- {
- ;
- this.type = cr.exptype.Integer;
- this.data = Math.floor(val);
- };
- ExpValue.prototype.set_float = function (val)
- {
- ;
- this.type = cr.exptype.Float;
- this.data = val;
- };
- ExpValue.prototype.set_string = function (val)
- {
- ;
- this.type = cr.exptype.String;
- this.data = val;
- };
- ExpValue.prototype.set_any = function (val)
- {
- if (cr.is_number(val))
- {
- this.type = cr.exptype.Float;
- this.data = val;
- }
- else if (cr.is_string(val))
- {
- this.type = cr.exptype.String;
- this.data = val.toString();
- }
- else
- {
- this.type = cr.exptype.Integer;
- this.data = 0;
- }
- };
- cr.expvalue = ExpValue;
- cr.exptype = {
- Integer: 0, // emulated; no native integer support in javascript
- Float: 1,
- String: 2
- };
- }());
- ;
- cr.system_object = function (runtime)
- {
- this.runtime = runtime;
- this.waits = [];
- };
- cr.system_object.prototype.saveToJSON = function ()
- {
- var o = {};
- var i, len, j, lenj, p, w, t, sobj;
- o["waits"] = [];
- var owaits = o["waits"];
- var waitobj;
- for (i = 0, len = this.waits.length; i < len; i++)
- {
- w = this.waits[i];
- waitobj = {
- "t": w.time,
- "st": w.signaltag,
- "s": w.signalled,
- "ev": w.ev.sid,
- "sm": [],
- "sols": {}
- };
- if (w.ev.actions[w.actindex])
- waitobj["act"] = w.ev.actions[w.actindex].sid;
- for (j = 0, lenj = w.solModifiers.length; j < lenj; j++)
- waitobj["sm"].push(w.solModifiers[j].sid);
- for (p in w.sols)
- {
- if (w.sols.hasOwnProperty(p))
- {
- t = this.runtime.types_by_index[parseInt(p, 10)];
- ;
- sobj = {
- "sa": w.sols[p].sa,
- "insts": []
- };
- for (j = 0, lenj = w.sols[p].insts.length; j < lenj; j++)
- sobj["insts"].push(w.sols[p].insts[j].uid);
- waitobj["sols"][t.sid.toString()] = sobj;
- }
- }
- owaits.push(waitobj);
- }
- return o;
- };
- cr.system_object.prototype.loadFromJSON = function (o)
- {
- var owaits = o["waits"];
- var i, len, j, lenj, p, w, addWait, e, aindex, t, savedsol, nusol, inst;
- cr.clearArray(this.waits);
- for (i = 0, len = owaits.length; i < len; i++)
- {
- w = owaits[i];
- e = this.runtime.blocksBySid[w["ev"].toString()];
- if (!e)
- continue; // event must've gone missing
- aindex = -1;
- for (j = 0, lenj = e.actions.length; j < lenj; j++)
- {
- if (e.actions[j].sid === w["act"])
- {
- aindex = j;
- break;
- }
- }
- if (aindex === -1)
- continue; // action must've gone missing
- addWait = {};
- addWait.sols = {};
- addWait.solModifiers = [];
- addWait.deleteme = false;
- addWait.time = w["t"];
- addWait.signaltag = w["st"] || "";
- addWait.signalled = !!w["s"];
- addWait.ev = e;
- addWait.actindex = aindex;
- for (j = 0, lenj = w["sm"].length; j < lenj; j++)
- {
- t = this.runtime.getObjectTypeBySid(w["sm"][j]);
- if (t)
- addWait.solModifiers.push(t);
- }
- for (p in w["sols"])
- {
- if (w["sols"].hasOwnProperty(p))
- {
- t = this.runtime.getObjectTypeBySid(parseInt(p, 10));
- if (!t)
- continue; // type must've been deleted
- savedsol = w["sols"][p];
- nusol = {
- sa: savedsol["sa"],
- insts: []
- };
- for (j = 0, lenj = savedsol["insts"].length; j < lenj; j++)
- {
- inst = this.runtime.getObjectByUID(savedsol["insts"][j]);
- if (inst)
- nusol.insts.push(inst);
- }
- addWait.sols[t.index.toString()] = nusol;
- }
- }
- this.waits.push(addWait);
- }
- };
- (function ()
- {
- var sysProto = cr.system_object.prototype;
- function SysCnds() {};
- SysCnds.prototype.EveryTick = function()
- {
- return true;
- };
- SysCnds.prototype.OnLayoutStart = function()
- {
- return true;
- };
- SysCnds.prototype.OnLayoutEnd = function()
- {
- return true;
- };
- SysCnds.prototype.Compare = function(x, cmp, y)
- {
- return cr.do_cmp(x, cmp, y);
- };
- SysCnds.prototype.CompareTime = function (cmp, t)
- {
- var elapsed = this.runtime.kahanTime.sum;
- if (cmp === 0)
- {
- var cnd = this.runtime.getCurrentCondition();
- if (!cnd.extra["CompareTime_executed"])
- {
- if (elapsed >= t)
- {
- cnd.extra["CompareTime_executed"] = true;
- return true;
- }
- }
- return false;
- }
- return cr.do_cmp(elapsed, cmp, t);
- };
- SysCnds.prototype.LayerVisible = function (layer)
- {
- if (!layer)
- return false;
- else
- return layer.visible;
- };
- SysCnds.prototype.LayerEmpty = function (layer)
- {
- if (!layer)
- return false;
- else
- return !layer.instances.length;
- };
- SysCnds.prototype.LayerCmpOpacity = function (layer, cmp, opacity_)
- {
- if (!layer)
- return false;
- return cr.do_cmp(layer.opacity * 100, cmp, opacity_);
- };
- SysCnds.prototype.Repeat = function (count)
- {
- var current_frame = this.runtime.getCurrentEventStack();
- var current_event = current_frame.current_event;
- var solModifierAfterCnds = current_frame.isModifierAfterCnds();
- var current_loop = this.runtime.pushLoopStack();
- var i;
- if (solModifierAfterCnds)
- {
- for (i = 0; i < count && !current_loop.stopped; i++)
- {
- this.runtime.pushCopySol(current_event.solModifiers);
- current_loop.index = i;
- current_event.retrigger();
- this.runtime.popSol(current_event.solModifiers);
- }
- }
- else
- {
- for (i = 0; i < count && !current_loop.stopped; i++)
- {
- current_loop.index = i;
- current_event.retrigger();
- }
- }
- this.runtime.popLoopStack();
- return false;
- };
- SysCnds.prototype.While = function (count)
- {
- var current_frame = this.runtime.getCurrentEventStack();
- var current_event = current_frame.current_event;
- var solModifierAfterCnds = current_frame.isModifierAfterCnds();
- var current_loop = this.runtime.pushLoopStack();
- var i;
- if (solModifierAfterCnds)
- {
- for (i = 0; !current_loop.stopped; i++)
- {
- this.runtime.pushCopySol(current_event.solModifiers);
- current_loop.index = i;
- if (!current_event.retrigger()) // one of the other conditions returned false
- current_loop.stopped = true; // break
- this.runtime.popSol(current_event.solModifiers);
- }
- }
- else
- {
- for (i = 0; !current_loop.stopped; i++)
- {
- current_loop.index = i;
- if (!current_event.retrigger())
- current_loop.stopped = true;
- }
- }
- this.runtime.popLoopStack();
- return false;
- };
- SysCnds.prototype.For = function (name, start, end)
- {
- var current_frame = this.runtime.getCurrentEventStack();
- var current_event = current_frame.current_event;
- var solModifierAfterCnds = current_frame.isModifierAfterCnds();
- var current_loop = this.runtime.pushLoopStack(name);
- var i;
- if (end < start)
- {
- if (solModifierAfterCnds)
- {
- for (i = start; i >= end && !current_loop.stopped; --i) // inclusive to end
- {
- this.runtime.pushCopySol(current_event.solModifiers);
- current_loop.index = i;
- current_event.retrigger();
- this.runtime.popSol(current_event.solModifiers);
- }
- }
- else
- {
- for (i = start; i >= end && !current_loop.stopped; --i) // inclusive to end
- {
- current_loop.index = i;
- current_event.retrigger();
- }
- }
- }
- else
- {
- if (solModifierAfterCnds)
- {
- for (i = start; i <= end && !current_loop.stopped; ++i) // inclusive to end
- {
- this.runtime.pushCopySol(current_event.solModifiers);
- current_loop.index = i;
- current_event.retrigger();
- this.runtime.popSol(current_event.solModifiers);
- }
- }
- else
- {
- for (i = start; i <= end && !current_loop.stopped; ++i) // inclusive to end
- {
- current_loop.index = i;
- current_event.retrigger();
- }
- }
- }
- this.runtime.popLoopStack();
- return false;
- };
- var foreach_instancestack = [];
- var foreach_instanceptr = -1;
- SysCnds.prototype.ForEach = function (obj)
- {
- var sol = obj.getCurrentSol();
- foreach_instanceptr++;
- if (foreach_instancestack.length === foreach_instanceptr)
- foreach_instancestack.push([]);
- var instances = foreach_instancestack[foreach_instanceptr];
- cr.shallowAssignArray(instances, sol.getObjects());
- var current_frame = this.runtime.getCurrentEventStack();
- var current_event = current_frame.current_event;
- var solModifierAfterCnds = current_frame.isModifierAfterCnds();
- var current_loop = this.runtime.pushLoopStack();
- var i, len, j, lenj, inst, s, sol2;
- var is_contained = obj.is_contained;
- if (solModifierAfterCnds)
- {
- for (i = 0, len = instances.length; i < len && !current_loop.stopped; i++)
- {
- this.runtime.pushCopySol(current_event.solModifiers);
- inst = instances[i];
- sol = obj.getCurrentSol();
- sol.select_all = false;
- cr.clearArray(sol.instances);
- sol.instances[0] = inst;
- if (is_contained)
- {
- for (j = 0, lenj = inst.siblings.length; j < lenj; j++)
- {
- s = inst.siblings[j];
- sol2 = s.type.getCurrentSol();
- sol2.select_all = false;
- cr.clearArray(sol2.instances);
- sol2.instances[0] = s;
- }
- }
- current_loop.index = i;
- current_event.retrigger();
- this.runtime.popSol(current_event.solModifiers);
- }
- }
- else
- {
- sol.select_all = false;
- cr.clearArray(sol.instances);
- for (i = 0, len = instances.length; i < len && !current_loop.stopped; i++)
- {
- inst = instances[i];
- sol.instances[0] = inst;
- if (is_contained)
- {
- for (j = 0, lenj = inst.siblings.length; j < lenj; j++)
- {
- s = inst.siblings[j];
- sol2 = s.type.getCurrentSol();
- sol2.select_all = false;
- cr.clearArray(sol2.instances);
- sol2.instances[0] = s;
- }
- }
- current_loop.index = i;
- current_event.retrigger();
- }
- }
- cr.clearArray(instances);
- this.runtime.popLoopStack();
- foreach_instanceptr--;
- return false;
- };
- function foreach_sortinstances(a, b)
- {
- var va = a.extra["c2_feo_val"];
- var vb = b.extra["c2_feo_val"];
- if (cr.is_number(va) && cr.is_number(vb))
- return va - vb;
- else
- {
- va = "" + va;
- vb = "" + vb;
- if (va < vb)
- return -1;
- else if (va > vb)
- return 1;
- else
- return 0;
- }
- };
- SysCnds.prototype.ForEachOrdered = function (obj, exp, order)
- {
- var sol = obj.getCurrentSol();
- foreach_instanceptr++;
- if (foreach_instancestack.length === foreach_instanceptr)
- foreach_instancestack.push([]);
- var instances = foreach_instancestack[foreach_instanceptr];
- cr.shallowAssignArray(instances, sol.getObjects());
- var current_frame = this.runtime.getCurrentEventStack();
- var current_event = current_frame.current_event;
- var current_condition = this.runtime.getCurrentCondition();
- var solModifierAfterCnds = current_frame.isModifierAfterCnds();
- var current_loop = this.runtime.pushLoopStack();
- var i, len, j, lenj, inst, s, sol2;
- for (i = 0, len = instances.length; i < len; i++)
- {
- instances[i].extra["c2_feo_val"] = current_condition.parameters[1].get(i);
- }
- instances.sort(foreach_sortinstances);
- if (order === 1)
- instances.reverse();
- var is_contained = obj.is_contained;
- if (solModifierAfterCnds)
- {
- for (i = 0, len = instances.length; i < len && !current_loop.stopped; i++)
- {
- this.runtime.pushCopySol(current_event.solModifiers);
- inst = instances[i];
- sol = obj.getCurrentSol();
- sol.select_all = false;
- cr.clearArray(sol.instances);
- sol.instances[0] = inst;
- if (is_contained)
- {
- for (j = 0, lenj = inst.siblings.length; j < lenj; j++)
- {
- s = inst.siblings[j];
- sol2 = s.type.getCurrentSol();
- sol2.select_all = false;
- cr.clearArray(sol2.instances);
- sol2.instances[0] = s;
- }
- }
- current_loop.index = i;
- current_event.retrigger();
- this.runtime.popSol(current_event.solModifiers);
- }
- }
- else
- {
- sol.select_all = false;
- cr.clearArray(sol.instances);
- for (i = 0, len = instances.length; i < len && !current_loop.stopped; i++)
- {
- inst = instances[i];
- sol.instances[0] = inst;
- if (is_contained)
- {
- for (j = 0, lenj = inst.siblings.length; j < lenj; j++)
- {
- s = inst.siblings[j];
- sol2 = s.type.getCurrentSol();
- sol2.select_all = false;
- cr.clearArray(sol2.instances);
- sol2.instances[0] = s;
- }
- }
- current_loop.index = i;
- current_event.retrigger();
- }
- }
- cr.clearArray(instances);
- this.runtime.popLoopStack();
- foreach_instanceptr--;
- return false;
- };
- SysCnds.prototype.PickByComparison = function (obj_, exp_, cmp_, val_)
- {
- var i, len, k, inst;
- if (!obj_)
- return;
- foreach_instanceptr++;
- if (foreach_instancestack.length === foreach_instanceptr)
- foreach_instancestack.push([]);
- var tmp_instances = foreach_instancestack[foreach_instanceptr];
- var sol = obj_.getCurrentSol();
- cr.shallowAssignArray(tmp_instances, sol.getObjects());
- if (sol.select_all)
- cr.clearArray(sol.else_instances);
- var current_condition = this.runtime.getCurrentCondition();
- for (i = 0, k = 0, len = tmp_instances.length; i < len; i++)
- {
- inst = tmp_instances[i];
- tmp_instances[k] = inst;
- exp_ = current_condition.parameters[1].get(i);
- val_ = current_condition.parameters[3].get(i);
- if (cr.do_cmp(exp_, cmp_, val_))
- {
- k++;
- }
- else
- {
- sol.else_instances.push(inst);
- }
- }
- cr.truncateArray(tmp_instances, k);
- sol.select_all = false;
- cr.shallowAssignArray(sol.instances, tmp_instances);
- cr.clearArray(tmp_instances);
- foreach_instanceptr--;
- obj_.applySolToContainer();
- return !!sol.instances.length;
- };
- SysCnds.prototype.PickByEvaluate = function (obj_, exp_)
- {
- var i, len, k, inst;
- if (!obj_)
- return;
- foreach_instanceptr++;
- if (foreach_instancestack.length === foreach_instanceptr)
- foreach_instancestack.push([]);
- var tmp_instances = foreach_instancestack[foreach_instanceptr];
- var sol = obj_.getCurrentSol();
- cr.shallowAssignArray(tmp_instances, sol.getObjects());
- if (sol.select_all)
- cr.clearArray(sol.else_instances);
- var current_condition = this.runtime.getCurrentCondition();
- for (i = 0, k = 0, len = tmp_instances.length; i < len; i++)
- {
- inst = tmp_instances[i];
- tmp_instances[k] = inst;
- exp_ = current_condition.parameters[1].get(i);
- if (exp_)
- {
- k++;
- }
- else
- {
- sol.else_instances.push(inst);
- }
- }
- cr.truncateArray(tmp_instances, k);
- sol.select_all = false;
- cr.shallowAssignArray(sol.instances, tmp_instances);
- cr.clearArray(tmp_instances);
- foreach_instanceptr--;
- obj_.applySolToContainer();
- return !!sol.instances.length;
- };
- SysCnds.prototype.TriggerOnce = function ()
- {
- var cndextra = this.runtime.getCurrentCondition().extra;
- if (typeof cndextra["TriggerOnce_lastTick"] === "undefined")
- cndextra["TriggerOnce_lastTick"] = -1;
- var last_tick = cndextra["TriggerOnce_lastTick"];
- var cur_tick = this.runtime.tickcount;
- cndextra["TriggerOnce_lastTick"] = cur_tick;
- return this.runtime.layout_first_tick || last_tick !== cur_tick - 1;
- };
- SysCnds.prototype.Every = function (seconds)
- {
- var cnd = this.runtime.getCurrentCondition();
- var last_time = cnd.extra["Every_lastTime"] || 0;
- var cur_time = this.runtime.kahanTime.sum;
- if (typeof cnd.extra["Every_seconds"] === "undefined")
- cnd.extra["Every_seconds"] = seconds;
- var this_seconds = cnd.extra["Every_seconds"];
- if (cur_time >= last_time + this_seconds)
- {
- cnd.extra["Every_lastTime"] = last_time + this_seconds;
- if (cur_time >= cnd.extra["Every_lastTime"] + 0.04)
- {
- cnd.extra["Every_lastTime"] = cur_time;
- }
- cnd.extra["Every_seconds"] = seconds;
- return true;
- }
- else if (cur_time < last_time - 0.1)
- {
- cnd.extra["Every_lastTime"] = cur_time;
- }
- return false;
- };
- SysCnds.prototype.PickNth = function (obj, index)
- {
- if (!obj)
- return false;
- var sol = obj.getCurrentSol();
- var instances = sol.getObjects();
- index = cr.floor(index);
- if (index < 0 || index >= instances.length)
- return false;
- var inst = instances[index];
- sol.pick_one(inst);
- obj.applySolToContainer();
- return true;
- };
- SysCnds.prototype.PickRandom = function (obj)
- {
- if (!obj)
- return false;
- var sol = obj.getCurrentSol();
- var instances = sol.getObjects();
- var index = cr.floor(Math.random() * instances.length);
- if (index >= instances.length)
- return false;
- var inst = instances[index];
- sol.pick_one(inst);
- obj.applySolToContainer();
- return true;
- };
- SysCnds.prototype.CompareVar = function (v, cmp, val)
- {
- return cr.do_cmp(v.getValue(), cmp, val);
- };
- SysCnds.prototype.IsGroupActive = function (group)
- {
- var g = this.runtime.groups_by_name[group.toLowerCase()];
- return g && g.group_active;
- };
- SysCnds.prototype.IsPreview = function ()
- {
- return typeof cr_is_preview !== "undefined";
- };
- SysCnds.prototype.PickAll = function (obj)
- {
- if (!obj)
- return false;
- if (!obj.instances.length)
- return false;
- var sol = obj.getCurrentSol();
- sol.select_all = true;
- obj.applySolToContainer();
- return true;
- };
- SysCnds.prototype.IsMobile = function ()
- {
- return this.runtime.isMobile;
- };
- SysCnds.prototype.CompareBetween = function (x, a, b)
- {
- return x >= a && x <= b;
- };
- SysCnds.prototype.Else = function ()
- {
- var current_frame = this.runtime.getCurrentEventStack();
- if (current_frame.else_branch_ran)
- return false; // another event in this else-if chain has run
- else
- return !current_frame.last_event_true;
- /*
- var current_frame = this.runtime.getCurrentEventStack();
- var current_event = current_frame.current_event;
- var prev_event = current_event.prev_block;
- if (!prev_event)
- return false;
- if (prev_event.is_logical)
- return !this.runtime.last_event_true;
- var i, len, j, lenj, s, sol, temp, inst, any_picked = false;
- for (i = 0, len = prev_event.cndReferences.length; i < len; i++)
- {
- s = prev_event.cndReferences[i];
- sol = s.getCurrentSol();
- if (sol.select_all || sol.instances.length === s.instances.length)
- {
- sol.select_all = false;
- sol.instances.length = 0;
- }
- else
- {
- if (sol.instances.length === 1 && sol.else_instances.length === 0 && s.instances.length >= 2)
- {
- inst = sol.instances[0];
- sol.instances.length = 0;
- for (j = 0, lenj = s.instances.length; j < lenj; j++)
- {
- if (s.instances[j] != inst)
- sol.instances.push(s.instances[j]);
- }
- any_picked = true;
- }
- else
- {
- temp = sol.instances;
- sol.instances = sol.else_instances;
- sol.else_instances = temp;
- any_picked = true;
- }
- }
- }
- return any_picked;
- */
- };
- SysCnds.prototype.OnLoadFinished = function ()
- {
- return true;
- };
- SysCnds.prototype.OnCanvasSnapshot = function ()
- {
- return true;
- };
- SysCnds.prototype.EffectsSupported = function ()
- {
- return !!this.runtime.glwrap;
- };
- SysCnds.prototype.OnSaveComplete = function ()
- {
- return true;
- };
- SysCnds.prototype.OnLoadComplete = function ()
- {
- return true;
- };
- SysCnds.prototype.OnLoadFailed = function ()
- {
- return true;
- };
- SysCnds.prototype.ObjectUIDExists = function (u)
- {
- return !!this.runtime.getObjectByUID(u);
- };
- SysCnds.prototype.IsOnPlatform = function (p)
- {
- var rt = this.runtime;
- switch (p) {
- case 0: // HTML5 website
- return !rt.isDomFree && !rt.isNodeWebkit && !rt.isCordova && !rt.isWinJS && !rt.isWindowsPhone8 && !rt.isBlackberry10 && !rt.isAmazonWebApp;
- case 1: // iOS
- return rt.isiOS;
- case 2: // Android
- return rt.isAndroid;
- case 3: // Windows 8
- return rt.isWindows8App;
- case 4: // Windows Phone 8
- return rt.isWindowsPhone8;
- case 5: // Blackberry 10
- return rt.isBlackberry10;
- case 6: // Tizen
- return rt.isTizen;
- case 7: // CocoonJS
- return rt.isCocoonJs;
- case 8: // Cordova
- return rt.isCordova;
- case 9: // Scirra Arcade
- return rt.isArcade;
- case 10: // node-webkit
- return rt.isNodeWebkit;
- case 11: // crosswalk
- return rt.isCrosswalk;
- case 12: // amazon webapp
- return rt.isAmazonWebApp;
- default: // should not be possible
- return false;
- }
- };
- var cacheRegex = null;
- var lastRegex = "";
- var lastFlags = "";
- function getRegex(regex_, flags_)
- {
- if (!cacheRegex || regex_ !== lastRegex || flags_ !== lastFlags)
- {
- cacheRegex = new RegExp(regex_, flags_);
- lastRegex = regex_;
- lastFlags = flags_;
- }
- cacheRegex.lastIndex = 0; // reset
- return cacheRegex;
- };
- SysCnds.prototype.RegexTest = function (str_, regex_, flags_)
- {
- var regex = getRegex(regex_, flags_);
- return regex.test(str_);
- };
- var tmp_arr = [];
- SysCnds.prototype.PickOverlappingPoint = function (obj_, x_, y_)
- {
- if (!obj_)
- return false;
- var sol = obj_.getCurrentSol();
- var instances = sol.getObjects();
- var current_event = this.runtime.getCurrentEventStack().current_event;
- var orblock = current_event.orblock;
- var cnd = this.runtime.getCurrentCondition();
- var i, len, inst, pick;
- if (sol.select_all)
- {
- cr.shallowAssignArray(tmp_arr, instances);
- cr.clearArray(sol.else_instances);
- sol.select_all = false;
- cr.clearArray(sol.instances);
- }
- else
- {
- if (orblock)
- {
- cr.shallowAssignArray(tmp_arr, sol.else_instances);
- cr.clearArray(sol.else_instances);
- }
- else
- {
- cr.shallowAssignArray(tmp_arr, instances);
- cr.clearArray(sol.instances);
- }
- }
- for (i = 0, len = tmp_arr.length; i < len; ++i)
- {
- inst = tmp_arr[i];
- inst.update_bbox();
- pick = cr.xor(inst.contains_pt(x_, y_), cnd.inverted);
- if (pick)
- sol.instances.push(inst);
- else
- sol.else_instances.push(inst);
- }
- obj_.applySolToContainer();
- return cr.xor(!!sol.instances.length, cnd.inverted);
- };
- SysCnds.prototype.IsNaN = function (n)
- {
- return !!isNaN(n);
- };
- SysCnds.prototype.AngleWithin = function (a1, within, a2)
- {
- return cr.angleDiff(cr.to_radians(a1), cr.to_radians(a2)) <= cr.to_radians(within);
- };
- SysCnds.prototype.IsClockwiseFrom = function (a1, a2)
- {
- return cr.angleClockwise(cr.to_radians(a1), cr.to_radians(a2));
- };
- SysCnds.prototype.IsBetweenAngles = function (a, la, ua)
- {
- var angle = cr.to_clamped_radians(a);
- var lower = cr.to_clamped_radians(la);
- var upper = cr.to_clamped_radians(ua);
- var obtuse = (!cr.angleClockwise(upper, lower));
- if (obtuse)
- return !(!cr.angleClockwise(angle, lower) && cr.angleClockwise(angle, upper));
- else
- return cr.angleClockwise(angle, lower) && !cr.angleClockwise(angle, upper);
- };
- SysCnds.prototype.IsValueType = function (x, t)
- {
- if (typeof x === "number")
- return t === 0;
- else // string
- return t === 1;
- };
- sysProto.cnds = new SysCnds();
- function SysActs() {};
- SysActs.prototype.GoToLayout = function (to)
- {
- if (this.runtime.isloading)
- return; // cannot change layout while loading on loader layout
- if (this.runtime.changelayout)
- return; // already changing to a different layout
- ;
- this.runtime.changelayout = to;
- };
- SysActs.prototype.NextPrevLayout = function (prev)
- {
- if (this.runtime.isloading)
- return; // cannot change layout while loading on loader layout
- if (this.runtime.changelayout)
- return; // already changing to a different layout
- var index = this.runtime.layouts_by_index.indexOf(this.runtime.running_layout);
- if (prev && index === 0)
- return; // cannot go to previous layout from first layout
- if (!prev && index === this.runtime.layouts_by_index.length - 1)
- return; // cannot go to next layout from last layout
- var to = this.runtime.layouts_by_index[index + (prev ? -1 : 1)];
- ;
- this.runtime.changelayout = to;
- };
- SysActs.prototype.CreateObject = function (obj, layer, x, y)
- {
- if (!layer || !obj)
- return;
- var inst = this.runtime.createInstance(obj, layer, x, y);
- if (!inst)
- return;
- this.runtime.isInOnDestroy++;
- var i, len, s;
- this.runtime.trigger(Object.getPrototypeOf(obj.plugin).cnds.OnCreated, inst);
- if (inst.is_contained)
- {
- for (i = 0, len = inst.siblings.length; i < len; i++)
- {
- s = inst.siblings[i];
- this.runtime.trigger(Object.getPrototypeOf(s.type.plugin).cnds.OnCreated, s);
- }
- }
- this.runtime.isInOnDestroy--;
- var sol = obj.getCurrentSol();
- sol.select_all = false;
- cr.clearArray(sol.instances);
- sol.instances[0] = inst;
- if (inst.is_contained)
- {
- for (i = 0, len = inst.siblings.length; i < len; i++)
- {
- s = inst.siblings[i];
- sol = s.type.getCurrentSol();
- sol.select_all = false;
- cr.clearArray(sol.instances);
- sol.instances[0] = s;
- }
- }
- };
- SysActs.prototype.SetLayerVisible = function (layer, visible_)
- {
- if (!layer)
- return;
- if (layer.visible !== visible_)
- {
- layer.visible = visible_;
- this.runtime.redraw = true;
- }
- };
- SysActs.prototype.SetLayerOpacity = function (layer, opacity_)
- {
- if (!layer)
- return;
- opacity_ = cr.clamp(opacity_ / 100, 0, 1);
- if (layer.opacity !== opacity_)
- {
- layer.opacity = opacity_;
- this.runtime.redraw = true;
- }
- };
- SysActs.prototype.SetLayerScaleRate = function (layer, sr)
- {
- if (!layer)
- return;
- if (layer.zoomRate !== sr)
- {
- layer.zoomRate = sr;
- this.runtime.redraw = true;
- }
- };
- SysActs.prototype.SetLayerForceOwnTexture = function (layer, f)
- {
- if (!layer)
- return;
- f = !!f;
- if (layer.forceOwnTexture !== f)
- {
- layer.forceOwnTexture = f;
- this.runtime.redraw = true;
- }
- };
- SysActs.prototype.SetLayoutScale = function (s)
- {
- if (!this.runtime.running_layout)
- return;
- if (this.runtime.running_layout.scale !== s)
- {
- this.runtime.running_layout.scale = s;
- this.runtime.running_layout.boundScrolling();
- this.runtime.redraw = true;
- }
- };
- SysActs.prototype.ScrollX = function(x)
- {
- this.runtime.running_layout.scrollToX(x);
- };
- SysActs.prototype.ScrollY = function(y)
- {
- this.runtime.running_layout.scrollToY(y);
- };
- SysActs.prototype.Scroll = function(x, y)
- {
- this.runtime.running_layout.scrollToX(x);
- this.runtime.running_layout.scrollToY(y);
- };
- SysActs.prototype.ScrollToObject = function(obj)
- {
- var inst = obj.getFirstPicked();
- if (inst)
- {
- this.runtime.running_layout.scrollToX(inst.x);
- this.runtime.running_layout.scrollToY(inst.y);
- }
- };
- SysActs.prototype.SetVar = function(v, x)
- {
- ;
- if (v.vartype === 0)
- {
- if (cr.is_number(x))
- v.setValue(x);
- else
- v.setValue(parseFloat(x));
- }
- else if (v.vartype === 1)
- v.setValue(x.toString());
- };
- SysActs.prototype.AddVar = function(v, x)
- {
- ;
- if (v.vartype === 0)
- {
- if (cr.is_number(x))
- v.setValue(v.getValue() + x);
- else
- v.setValue(v.getValue() + parseFloat(x));
- }
- else if (v.vartype === 1)
- v.setValue(v.getValue() + x.toString());
- };
- SysActs.prototype.SubVar = function(v, x)
- {
- ;
- if (v.vartype === 0)
- {
- if (cr.is_number(x))
- v.setValue(v.getValue() - x);
- else
- v.setValue(v.getValue() - parseFloat(x));
- }
- };
- SysActs.prototype.SetGroupActive = function (group, active)
- {
- var g = this.runtime.groups_by_name[group.toLowerCase()];
- if (!g)
- return;
- switch (active) {
- case 0:
- g.setGroupActive(false);
- break;
- case 1:
- g.setGroupActive(true);
- break;
- case 2:
- g.setGroupActive(!g.group_active);
- break;
- }
- };
- SysActs.prototype.SetTimescale = function (ts_)
- {
- var ts = ts_;
- if (ts < 0)
- ts = 0;
- this.runtime.timescale = ts;
- };
- SysActs.prototype.SetObjectTimescale = function (obj, ts_)
- {
- var ts = ts_;
- if (ts < 0)
- ts = 0;
- if (!obj)
- return;
- var sol = obj.getCurrentSol();
- var instances = sol.getObjects();
- var i, len;
- for (i = 0, len = instances.length; i < len; i++)
- {
- instances[i].my_timescale = ts;
- }
- };
- SysActs.prototype.RestoreObjectTimescale = function (obj)
- {
- if (!obj)
- return false;
- var sol = obj.getCurrentSol();
- var instances = sol.getObjects();
- var i, len;
- for (i = 0, len = instances.length; i < len; i++)
- {
- instances[i].my_timescale = -1.0;
- }
- };
- var waitobjrecycle = [];
- function allocWaitObject()
- {
- var w;
- if (waitobjrecycle.length)
- w = waitobjrecycle.pop();
- else
- {
- w = {};
- w.sols = {};
- w.solModifiers = [];
- }
- w.deleteme = false;
- return w;
- };
- function freeWaitObject(w)
- {
- cr.wipe(w.sols);
- cr.clearArray(w.solModifiers);
- waitobjrecycle.push(w);
- };
- var solstateobjects = [];
- function allocSolStateObject()
- {
- var s;
- if (solstateobjects.length)
- s = solstateobjects.pop();
- else
- {
- s = {};
- s.insts = [];
- }
- s.sa = false;
- return s;
- };
- function freeSolStateObject(s)
- {
- cr.clearArray(s.insts);
- solstateobjects.push(s);
- };
- SysActs.prototype.Wait = function (seconds)
- {
- if (seconds < 0)
- return;
- var i, len, s, t, ss;
- var evinfo = this.runtime.getCurrentEventStack();
- var waitobj = allocWaitObject();
- waitobj.time = this.runtime.kahanTime.sum + seconds;
- waitobj.signaltag = "";
- waitobj.signalled = false;
- waitobj.ev = evinfo.current_event;
- waitobj.actindex = evinfo.actindex + 1; // pointing at next action
- for (i = 0, len = this.runtime.types_by_index.length; i < len; i++)
- {
- t = this.runtime.types_by_index[i];
- s = t.getCurrentSol();
- if (s.select_all && evinfo.current_event.solModifiers.indexOf(t) === -1)
- continue;
- waitobj.solModifiers.push(t);
- ss = allocSolStateObject();
- ss.sa = s.select_all;
- cr.shallowAssignArray(ss.insts, s.instances);
- waitobj.sols[i.toString()] = ss;
- }
- this.waits.push(waitobj);
- return true;
- };
- SysActs.prototype.WaitForSignal = function (tag)
- {
- var i, len, s, t, ss;
- var evinfo = this.runtime.getCurrentEventStack();
- var waitobj = allocWaitObject();
- waitobj.time = -1;
- waitobj.signaltag = tag.toLowerCase();
- waitobj.signalled = false;
- waitobj.ev = evinfo.current_event;
- waitobj.actindex = evinfo.actindex + 1; // pointing at next action
- for (i = 0, len = this.runtime.types_by_index.length; i < len; i++)
- {
- t = this.runtime.types_by_index[i];
- s = t.getCurrentSol();
- if (s.select_all && evinfo.current_event.solModifiers.indexOf(t) === -1)
- continue;
- waitobj.solModifiers.push(t);
- ss = allocSolStateObject();
- ss.sa = s.select_all;
- cr.shallowAssignArray(ss.insts, s.instances);
- waitobj.sols[i.toString()] = ss;
- }
- this.waits.push(waitobj);
- return true;
- };
- SysActs.prototype.Signal = function (tag)
- {
- var lowertag = tag.toLowerCase();
- var i, len, w;
- for (i = 0, len = this.waits.length; i < len; ++i)
- {
- w = this.waits[i];
- if (w.time !== -1)
- continue; // timer wait, ignore
- if (w.signaltag === lowertag) // waiting for this signal
- w.signalled = true; // will run on next check
- }
- };
- SysActs.prototype.SetLayerScale = function (layer, scale)
- {
- if (!layer)
- return;
- if (layer.scale === scale)
- return;
- layer.scale = scale;
- this.runtime.redraw = true;
- };
- SysActs.prototype.ResetGlobals = function ()
- {
- var i, len, g;
- for (i = 0, len = this.runtime.all_global_vars.length; i < len; i++)
- {
- g = this.runtime.all_global_vars[i];
- g.data = g.initial;
- }
- };
- SysActs.prototype.SetLayoutAngle = function (a)
- {
- a = cr.to_radians(a);
- a = cr.clamp_angle(a);
- if (this.runtime.running_layout)
- {
- if (this.runtime.running_layout.angle !== a)
- {
- this.runtime.running_layout.angle = a;
- this.runtime.redraw = true;
- }
- }
- };
- SysActs.prototype.SetLayerAngle = function (layer, a)
- {
- if (!layer)
- return;
- a = cr.to_radians(a);
- a = cr.clamp_angle(a);
- if (layer.angle === a)
- return;
- layer.angle = a;
- this.runtime.redraw = true;
- };
- SysActs.prototype.SetLayerParallax = function (layer, px, py)
- {
- if (!layer)
- return;
- if (layer.parallaxX === px / 100 && layer.parallaxY === py / 100)
- return;
- layer.parallaxX = px / 100;
- layer.parallaxY = py / 100;
- if (layer.parallaxX !== 1 || layer.parallaxY !== 1)
- {
- var i, len, instances = layer.instances;
- for (i = 0, len = instances.length; i < len; ++i)
- {
- instances[i].type.any_instance_parallaxed = true;
- }
- }
- this.runtime.redraw = true;
- };
- SysActs.prototype.SetLayerBackground = function (layer, c)
- {
- if (!layer)
- return;
- var r = cr.GetRValue(c);
- var g = cr.GetGValue(c);
- var b = cr.GetBValue(c);
- if (layer.background_color[0] === r && layer.background_color[1] === g && layer.background_color[2] === b)
- return;
- layer.background_color[0] = r;
- layer.background_color[1] = g;
- layer.background_color[2] = b;
- this.runtime.redraw = true;
- };
- SysActs.prototype.SetLayerTransparent = function (layer, t)
- {
- if (!layer)
- return;
- if (!!t === !!layer.transparent)
- return;
- layer.transparent = !!t;
- this.runtime.redraw = true;
- };
- SysActs.prototype.SetLayerBlendMode = function (layer, bm)
- {
- if (!layer)
- return;
- if (layer.blend_mode === bm)
- return;
- layer.blend_mode = bm;
- layer.compositeOp = cr.effectToCompositeOp(layer.blend_mode);
- if (this.runtime.gl)
- cr.setGLBlend(layer, layer.blend_mode, this.runtime.gl);
- this.runtime.redraw = true;
- };
- SysActs.prototype.StopLoop = function ()
- {
- if (this.runtime.loop_stack_index < 0)
- return; // no loop currently running
- this.runtime.getCurrentLoop().stopped = true;
- };
- SysActs.prototype.GoToLayoutByName = function (layoutname)
- {
- if (this.runtime.isloading)
- return; // cannot change layout while loading on loader layout
- if (this.runtime.changelayout)
- return; // already changing to different layout
- ;
- var l;
- for (l in this.runtime.layouts)
- {
- if (this.runtime.layouts.hasOwnProperty(l) && cr.equals_nocase(l, layoutname))
- {
- this.runtime.changelayout = this.runtime.layouts[l];
- return;
- }
- }
- };
- SysActs.prototype.RestartLayout = function (layoutname)
- {
- if (this.runtime.isloading)
- return; // cannot restart loader layouts
- if (this.runtime.changelayout)
- return; // already changing to a different layout
- ;
- if (!this.runtime.running_layout)
- return;
- this.runtime.changelayout = this.runtime.running_layout;
- var i, len, g;
- for (i = 0, len = this.runtime.allGroups.length; i < len; i++)
- {
- g = this.runtime.allGroups[i];
- g.setGroupActive(g.initially_activated);
- }
- };
- SysActs.prototype.SnapshotCanvas = function (format_, quality_)
- {
- this.runtime.doCanvasSnapshot(format_ === 0 ? "image/png" : "image/jpeg", quality_ / 100);
- };
- SysActs.prototype.SetCanvasSize = function (w, h)
- {
- if (w <= 0 || h <= 0)
- return;
- var mode = this.runtime.fullscreen_mode;
- var isfullscreen = (document["mozFullScreen"] || document["webkitIsFullScreen"] || !!document["msFullscreenElement"] || document["fullScreen"] || this.runtime.isNodeFullscreen);
- if (isfullscreen && this.runtime.fullscreen_scaling > 0)
- mode = this.runtime.fullscreen_scaling;
- if (mode === 0)
- {
- this.runtime["setSize"](w, h, true);
- }
- else
- {
- this.runtime.original_width = w;
- this.runtime.original_height = h;
- this.runtime["setSize"](this.runtime.lastWindowWidth, this.runtime.lastWindowHeight, true);
- }
- };
- SysActs.prototype.SetLayoutEffectEnabled = function (enable_, effectname_)
- {
- if (!this.runtime.running_layout || !this.runtime.glwrap)
- return;
- var et = this.runtime.running_layout.getEffectByName(effectname_);
- if (!et)
- return; // effect name not found
- var enable = (enable_ === 1);
- if (et.active == enable)
- return; // no change
- et.active = enable;
- this.runtime.running_layout.updateActiveEffects();
- this.runtime.redraw = true;
- };
- SysActs.prototype.SetLayerEffectEnabled = function (layer, enable_, effectname_)
- {
- if (!layer || !this.runtime.glwrap)
- return;
- var et = layer.getEffectByName(effectname_);
- if (!et)
- return; // effect name not found
- var enable = (enable_ === 1);
- if (et.active == enable)
- return; // no change
- et.active = enable;
- layer.updateActiveEffects();
- this.runtime.redraw = true;
- };
- SysActs.prototype.SetLayoutEffectParam = function (effectname_, index_, value_)
- {
- if (!this.runtime.running_layout || !this.runtime.glwrap)
- return;
- var et = this.runtime.running_layout.getEffectByName(effectname_);
- if (!et)
- return; // effect name not found
- var params = this.runtime.running_layout.effect_params[et.index];
- index_ = Math.floor(index_);
- if (index_ < 0 || index_ >= params.length)
- return; // effect index out of bounds
- if (this.runtime.glwrap.getProgramParameterType(et.shaderindex, index_) === 1)
- value_ /= 100.0;
- if (params[index_] === value_)
- return; // no change
- params[index_] = value_;
- if (et.active)
- this.runtime.redraw = true;
- };
- SysActs.prototype.SetLayerEffectParam = function (layer, effectname_, index_, value_)
- {
- if (!layer || !this.runtime.glwrap)
- return;
- var et = layer.getEffectByName(effectname_);
- if (!et)
- return; // effect name not found
- var params = layer.effect_params[et.index];
- index_ = Math.floor(index_);
- if (index_ < 0 || index_ >= params.length)
- return; // effect index out of bounds
- if (this.runtime.glwrap.getProgramParameterType(et.shaderindex, index_) === 1)
- value_ /= 100.0;
- if (params[index_] === value_)
- return; // no change
- params[index_] = value_;
- if (et.active)
- this.runtime.redraw = true;
- };
- SysActs.prototype.SaveState = function (slot_)
- {
- this.runtime.saveToSlot = slot_;
- };
- SysActs.prototype.LoadState = function (slot_)
- {
- this.runtime.loadFromSlot = slot_;
- };
- SysActs.prototype.LoadStateJSON = function (jsonstr_)
- {
- this.runtime.loadFromJson = jsonstr_;
- };
- SysActs.prototype.SetHalfFramerateMode = function (set_)
- {
- this.runtime.halfFramerateMode = (set_ !== 0);
- };
- SysActs.prototype.SetFullscreenQuality = function (q)
- {
- var isfullscreen = (document["mozFullScreen"] || document["webkitIsFullScreen"] || !!document["msFullscreenElement"] || document["fullScreen"] || this.isNodeFullscreen);
- if (!isfullscreen && this.runtime.fullscreen_mode === 0)
- return;
- this.runtime.wantFullscreenScalingQuality = (q !== 0);
- this.runtime["setSize"](this.runtime.lastWindowWidth, this.runtime.lastWindowHeight, true);
- };
- SysActs.prototype.ResetPersisted = function ()
- {
- var i, len;
- for (i = 0, len = this.runtime.layouts_by_index.length; i < len; ++i)
- {
- this.runtime.layouts_by_index[i].persist_data = {};
- this.runtime.layouts_by_index[i].first_visit = true;
- }
- };
- SysActs.prototype.RecreateInitialObjects = function (obj, x1, y1, x2, y2)
- {
- if (!obj)
- return;
- this.runtime.running_layout.recreateInitialObjects(obj, x1, y1, x2, y2);
- };
- SysActs.prototype.SetPixelRounding = function (m)
- {
- this.runtime.pixel_rounding = (m !== 0);
- this.runtime.redraw = true;
- };
- sysProto.acts = new SysActs();
- function SysExps() {};
- SysExps.prototype["int"] = function(ret, x)
- {
- if (cr.is_string(x))
- {
- ret.set_int(parseInt(x, 10));
- if (isNaN(ret.data))
- ret.data = 0;
- }
- else
- ret.set_int(x);
- };
- SysExps.prototype["float"] = function(ret, x)
- {
- if (cr.is_string(x))
- {
- ret.set_float(parseFloat(x));
- if (isNaN(ret.data))
- ret.data = 0;
- }
- else
- ret.set_float(x);
- };
- SysExps.prototype.str = function(ret, x)
- {
- if (cr.is_string(x))
- ret.set_string(x);
- else
- ret.set_string(x.toString());
- };
- SysExps.prototype.len = function(ret, x)
- {
- ret.set_int(x.length || 0);
- };
- SysExps.prototype.random = function (ret, a, b)
- {
- if (b === undefined)
- {
- ret.set_float(Math.random() * a);
- }
- else
- {
- ret.set_float(Math.random() * (b - a) + a);
- }
- };
- SysExps.prototype.sqrt = function(ret, x)
- {
- ret.set_float(Math.sqrt(x));
- };
- SysExps.prototype.abs = function(ret, x)
- {
- ret.set_float(Math.abs(x));
- };
- SysExps.prototype.round = function(ret, x)
- {
- ret.set_int(Math.round(x));
- };
- SysExps.prototype.floor = function(ret, x)
- {
- ret.set_int(Math.floor(x));
- };
- SysExps.prototype.ceil = function(ret, x)
- {
- ret.set_int(Math.ceil(x));
- };
- SysExps.prototype.sin = function(ret, x)
- {
- ret.set_float(Math.sin(cr.to_radians(x)));
- };
- SysExps.prototype.cos = function(ret, x)
- {
- ret.set_float(Math.cos(cr.to_radians(x)));
- };
- SysExps.prototype.tan = function(ret, x)
- {
- ret.set_float(Math.tan(cr.to_radians(x)));
- };
- SysExps.prototype.asin = function(ret, x)
- {
- ret.set_float(cr.to_degrees(Math.asin(x)));
- };
- SysExps.prototype.acos = function(ret, x)
- {
- ret.set_float(cr.to_degrees(Math.acos(x)));
- };
- SysExps.prototype.atan = function(ret, x)
- {
- ret.set_float(cr.to_degrees(Math.atan(x)));
- };
- SysExps.prototype.exp = function(ret, x)
- {
- ret.set_float(Math.exp(x));
- };
- SysExps.prototype.ln = function(ret, x)
- {
- ret.set_float(Math.log(x));
- };
- SysExps.prototype.log10 = function(ret, x)
- {
- ret.set_float(Math.log(x) / Math.LN10);
- };
- SysExps.prototype.max = function(ret)
- {
- var max_ = arguments[1];
- if (typeof max_ !== "number")
- max_ = 0;
- var i, len, a;
- for (i = 2, len = arguments.length; i < len; i++)
- {
- a = arguments[i];
- if (typeof a !== "number")
- continue; // ignore non-numeric types
- if (max_ < a)
- max_ = a;
- }
- ret.set_float(max_);
- };
- SysExps.prototype.min = function(ret)
- {
- var min_ = arguments[1];
- if (typeof min_ !== "number")
- min_ = 0;
- var i, len, a;
- for (i = 2, len = arguments.length; i < len; i++)
- {
- a = arguments[i];
- if (typeof a !== "number")
- continue; // ignore non-numeric types
- if (min_ > a)
- min_ = a;
- }
- ret.set_float(min_);
- };
- SysExps.prototype.dt = function(ret)
- {
- ret.set_float(this.runtime.dt);
- };
- SysExps.prototype.timescale = function(ret)
- {
- ret.set_float(this.runtime.timescale);
- };
- SysExps.prototype.wallclocktime = function(ret)
- {
- ret.set_float((Date.now() - this.runtime.start_time) / 1000.0);
- };
- SysExps.prototype.time = function(ret)
- {
- ret.set_float(this.runtime.kahanTime.sum);
- };
- SysExps.prototype.tickcount = function(ret)
- {
- ret.set_int(this.runtime.tickcount);
- };
- SysExps.prototype.objectcount = function(ret)
- {
- ret.set_int(this.runtime.objectcount);
- };
- SysExps.prototype.fps = function(ret)
- {
- ret.set_int(this.runtime.fps);
- };
- SysExps.prototype.loopindex = function(ret, name_)
- {
- var loop, i, len;
- if (!this.runtime.loop_stack.length)
- {
- ret.set_int(0);
- return;
- }
- if (name_)
- {
- for (i = 0, len = this.runtime.loop_stack.length; i < len; i++)
- {
- loop = this.runtime.loop_stack[i];
- if (loop.name === name_)
- {
- ret.set_int(loop.index);
- return;
- }
- }
- ret.set_int(0);
- }
- else
- {
- loop = this.runtime.getCurrentLoop();
- ret.set_int(loop ? loop.index : -1);
- }
- };
- SysExps.prototype.distance = function(ret, x1, y1, x2, y2)
- {
- ret.set_float(cr.distanceTo(x1, y1, x2, y2));
- };
- SysExps.prototype.angle = function(ret, x1, y1, x2, y2)
- {
- ret.set_float(cr.to_degrees(cr.angleTo(x1, y1, x2, y2)));
- };
- SysExps.prototype.scrollx = function(ret)
- {
- ret.set_float(this.runtime.running_layout.scrollX);
- };
- SysExps.prototype.scrolly = function(ret)
- {
- ret.set_float(this.runtime.running_layout.scrollY);
- };
- SysExps.prototype.newline = function(ret)
- {
- ret.set_string("\n");
- };
- SysExps.prototype.lerp = function(ret, a, b, x)
- {
- ret.set_float(cr.lerp(a, b, x));
- };
- SysExps.prototype.qarp = function(ret, a, b, c, x)
- {
- ret.set_float(cr.qarp(a, b, c, x));
- };
- SysExps.prototype.cubic = function(ret, a, b, c, d, x)
- {
- ret.set_float(cr.cubic(a, b, c, d, x));
- };
- SysExps.prototype.cosp = function(ret, a, b, x)
- {
- ret.set_float(cr.cosp(a, b, x));
- };
- SysExps.prototype.windowwidth = function(ret)
- {
- ret.set_int(this.runtime.width);
- };
- SysExps.prototype.windowheight = function(ret)
- {
- ret.set_int(this.runtime.height);
- };
- SysExps.prototype.uppercase = function(ret, str)
- {
- ret.set_string(cr.is_string(str) ? str.toUpperCase() : "");
- };
- SysExps.prototype.lowercase = function(ret, str)
- {
- ret.set_string(cr.is_string(str) ? str.toLowerCase() : "");
- };
- SysExps.prototype.clamp = function(ret, x, l, u)
- {
- if (x < l)
- ret.set_float(l);
- else if (x > u)
- ret.set_float(u);
- else
- ret.set_float(x);
- };
- SysExps.prototype.layerscale = function (ret, layerparam)
- {
- var layer = this.runtime.getLayer(layerparam);
- if (!layer)
- ret.set_float(0);
- else
- ret.set_float(layer.scale);
- };
- SysExps.prototype.layeropacity = function (ret, layerparam)
- {
- var layer = this.runtime.getLayer(layerparam);
- if (!layer)
- ret.set_float(0);
- else
- ret.set_float(layer.opacity * 100);
- };
- SysExps.prototype.layerscalerate = function (ret, layerparam)
- {
- var layer = this.runtime.getLayer(layerparam);
- if (!layer)
- ret.set_float(0);
- else
- ret.set_float(layer.zoomRate);
- };
- SysExps.prototype.layerparallaxx = function (ret, layerparam)
- {
- var layer = this.runtime.getLayer(layerparam);
- if (!layer)
- ret.set_float(0);
- else
- ret.set_float(layer.parallaxX * 100);
- };
- SysExps.prototype.layerparallaxy = function (ret, layerparam)
- {
- var layer = this.runtime.getLayer(layerparam);
- if (!layer)
- ret.set_float(0);
- else
- ret.set_float(layer.parallaxY * 100);
- };
- SysExps.prototype.layerindex = function (ret, layerparam)
- {
- var layer = this.runtime.getLayer(layerparam);
- if (!layer)
- ret.set_int(-1);
- else
- ret.set_int(layer.index);
- };
- SysExps.prototype.layoutscale = function (ret)
- {
- if (this.runtime.running_layout)
- ret.set_float(this.runtime.running_layout.scale);
- else
- ret.set_float(0);
- };
- SysExps.prototype.layoutangle = function (ret)
- {
- ret.set_float(cr.to_degrees(this.runtime.running_layout.angle));
- };
- SysExps.prototype.layerangle = function (ret, layerparam)
- {
- var layer = this.runtime.getLayer(layerparam);
- if (!layer)
- ret.set_float(0);
- else
- ret.set_float(cr.to_degrees(layer.angle));
- };
- SysExps.prototype.layoutwidth = function (ret)
- {
- ret.set_int(this.runtime.running_layout.width);
- };
- SysExps.prototype.layoutheight = function (ret)
- {
- ret.set_int(this.runtime.running_layout.height);
- };
- SysExps.prototype.find = function (ret, text, searchstr)
- {
- if (cr.is_string(text) && cr.is_string(searchstr))
- ret.set_int(text.search(new RegExp(cr.regexp_escape(searchstr), "i")));
- else
- ret.set_int(-1);
- };
- SysExps.prototype.left = function (ret, text, n)
- {
- ret.set_string(cr.is_string(text) ? text.substr(0, n) : "");
- };
- SysExps.prototype.right = function (ret, text, n)
- {
- ret.set_string(cr.is_string(text) ? text.substr(text.length - n) : "");
- };
- SysExps.prototype.mid = function (ret, text, index_, length_)
- {
- ret.set_string(cr.is_string(text) ? text.substr(index_, length_) : "");
- };
- SysExps.prototype.tokenat = function (ret, text, index_, sep)
- {
- if (cr.is_string(text) && cr.is_string(sep))
- {
- var arr = text.split(sep);
- var i = cr.floor(index_);
- if (i < 0 || i >= arr.length)
- ret.set_string("");
- else
- ret.set_string(arr[i]);
- }
- else
- ret.set_string("");
- };
- SysExps.prototype.tokencount = function (ret, text, sep)
- {
- if (cr.is_string(text) && text.length)
- ret.set_int(text.split(sep).length);
- else
- ret.set_int(0);
- };
- SysExps.prototype.replace = function (ret, text, find_, replace_)
- {
- if (cr.is_string(text) && cr.is_string(find_) && cr.is_string(replace_))
- ret.set_string(text.replace(new RegExp(cr.regexp_escape(find_), "gi"), replace_));
- else
- ret.set_string(cr.is_string(text) ? text : "");
- };
- SysExps.prototype.trim = function (ret, text)
- {
- ret.set_string(cr.is_string(text) ? text.trim() : "");
- };
- SysExps.prototype.pi = function (ret)
- {
- ret.set_float(cr.PI);
- };
- SysExps.prototype.layoutname = function (ret)
- {
- if (this.runtime.running_layout)
- ret.set_string(this.runtime.running_layout.name);
- else
- ret.set_string("");
- };
- SysExps.prototype.renderer = function (ret)
- {
- ret.set_string(this.runtime.gl ? "webgl" : "canvas2d");
- };
- SysExps.prototype.rendererdetail = function (ret)
- {
- ret.set_string(this.runtime.glUnmaskedRenderer);
- };
- SysExps.prototype.anglediff = function (ret, a, b)
- {
- ret.set_float(cr.to_degrees(cr.angleDiff(cr.to_radians(a), cr.to_radians(b))));
- };
- SysExps.prototype.choose = function (ret)
- {
- var index = cr.floor(Math.random() * (arguments.length - 1));
- ret.set_any(arguments[index + 1]);
- };
- SysExps.prototype.rgb = function (ret, r, g, b)
- {
- ret.set_int(cr.RGB(r, g, b));
- };
- SysExps.prototype.projectversion = function (ret)
- {
- ret.set_string(this.runtime.versionstr);
- };
- SysExps.prototype.projectname = function (ret)
- {
- ret.set_string(this.runtime.projectName);
- };
- SysExps.prototype.anglelerp = function (ret, a, b, x)
- {
- a = cr.to_radians(a);
- b = cr.to_radians(b);
- var diff = cr.angleDiff(a, b);
- if (cr.angleClockwise(b, a))
- {
- ret.set_float(cr.to_clamped_degrees(a + diff * x));
- }
- else
- {
- ret.set_float(cr.to_clamped_degrees(a - diff * x));
- }
- };
- SysExps.prototype.anglerotate = function (ret, a, b, c)
- {
- a = cr.to_radians(a);
- b = cr.to_radians(b);
- c = cr.to_radians(c);
- ret.set_float(cr.to_clamped_degrees(cr.angleRotate(a, b, c)));
- };
- SysExps.prototype.zeropad = function (ret, n, d)
- {
- var s = (n < 0 ? "-" : "");
- if (n < 0) n = -n;
- var zeroes = d - n.toString().length;
- for (var i = 0; i < zeroes; i++)
- s += "0";
- ret.set_string(s + n.toString());
- };
- SysExps.prototype.cpuutilisation = function (ret)
- {
- ret.set_float(this.runtime.cpuutilisation / 1000);
- };
- SysExps.prototype.viewportleft = function (ret, layerparam)
- {
- var layer = this.runtime.getLayer(layerparam);
- ret.set_float(layer ? layer.viewLeft : 0);
- };
- SysExps.prototype.viewporttop = function (ret, layerparam)
- {
- var layer = this.runtime.getLayer(layerparam);
- ret.set_float(layer ? layer.viewTop : 0);
- };
- SysExps.prototype.viewportright = function (ret, layerparam)
- {
- var layer = this.runtime.getLayer(layerparam);
- ret.set_float(layer ? layer.viewRight : 0);
- };
- SysExps.prototype.viewportbottom = function (ret, layerparam)
- {
- var layer = this.runtime.getLayer(layerparam);
- ret.set_float(layer ? layer.viewBottom : 0);
- };
- SysExps.prototype.loadingprogress = function (ret)
- {
- ret.set_float(this.runtime.loadingprogress);
- };
- SysExps.prototype.unlerp = function(ret, a, b, y)
- {
- ret.set_float(cr.unlerp(a, b, y));
- };
- SysExps.prototype.canvassnapshot = function (ret)
- {
- ret.set_string(this.runtime.snapshotData);
- };
- SysExps.prototype.urlencode = function (ret, s)
- {
- ret.set_string(encodeURIComponent(s));
- };
- SysExps.prototype.urldecode = function (ret, s)
- {
- ret.set_string(decodeURIComponent(s));
- };
- SysExps.prototype.canvastolayerx = function (ret, layerparam, x, y)
- {
- var layer = this.runtime.getLayer(layerparam);
- ret.set_float(layer ? layer.canvasToLayer(x, y, true) : 0);
- };
- SysExps.prototype.canvastolayery = function (ret, layerparam, x, y)
- {
- var layer = this.runtime.getLayer(layerparam);
- ret.set_float(layer ? layer.canvasToLayer(x, y, false) : 0);
- };
- SysExps.prototype.layertocanvasx = function (ret, layerparam, x, y)
- {
- var layer = this.runtime.getLayer(layerparam);
- ret.set_float(layer ? layer.layerToCanvas(x, y, true) : 0);
- };
- SysExps.prototype.layertocanvasy = function (ret, layerparam, x, y)
- {
- var layer = this.runtime.getLayer(layerparam);
- ret.set_float(layer ? layer.layerToCanvas(x, y, false) : 0);
- };
- SysExps.prototype.savestatejson = function (ret)
- {
- ret.set_string(this.runtime.lastSaveJson);
- };
- SysExps.prototype.imagememoryusage = function (ret)
- {
- if (this.runtime.glwrap)
- ret.set_float(Math.round(100 * this.runtime.glwrap.estimateVRAM() / (1024 * 1024)) / 100);
- else
- ret.set_float(0);
- };
- SysExps.prototype.regexsearch = function (ret, str_, regex_, flags_)
- {
- var regex = getRegex(regex_, flags_);
- ret.set_int(str_ ? str_.search(regex) : -1);
- };
- SysExps.prototype.regexreplace = function (ret, str_, regex_, flags_, replace_)
- {
- var regex = getRegex(regex_, flags_);
- ret.set_string(str_ ? str_.replace(regex, replace_) : "");
- };
- var regexMatches = [];
- var lastMatchesStr = "";
- var lastMatchesRegex = "";
- var lastMatchesFlags = "";
- function updateRegexMatches(str_, regex_, flags_)
- {
- if (str_ === lastMatchesStr && regex_ === lastMatchesRegex && flags_ === lastMatchesFlags)
- return;
- var regex = getRegex(regex_, flags_);
- regexMatches = str_.match(regex);
- lastMatchesStr = str_;
- lastMatchesRegex = regex_;
- lastMatchesFlags = flags_;
- };
- SysExps.prototype.regexmatchcount = function (ret, str_, regex_, flags_)
- {
- var regex = getRegex(regex_, flags_);
- updateRegexMatches(str_, regex_, flags_);
- ret.set_int(regexMatches ? regexMatches.length : 0);
- };
- SysExps.prototype.regexmatchat = function (ret, str_, regex_, flags_, index_)
- {
- index_ = Math.floor(index_);
- var regex = getRegex(regex_, flags_);
- updateRegexMatches(str_, regex_, flags_);
- if (!regexMatches || index_ < 0 || index_ >= regexMatches.length)
- ret.set_string("");
- else
- ret.set_string(regexMatches[index_]);
- };
- SysExps.prototype.infinity = function (ret)
- {
- ret.set_float(Infinity);
- };
- SysExps.prototype.setbit = function (ret, n, b, v)
- {
- n = n | 0;
- b = b | 0;
- v = (v !== 0 ? 1 : 0);
- ret.set_int((n & ~(1 << b)) | (v << b));
- };
- SysExps.prototype.togglebit = function (ret, n, b)
- {
- n = n | 0;
- b = b | 0;
- ret.set_int(n ^ (1 << b));
- };
- SysExps.prototype.getbit = function (ret, n, b)
- {
- n = n | 0;
- b = b | 0;
- ret.set_int((n & (1 << b)) ? 1 : 0);
- };
- SysExps.prototype.originalwindowwidth = function (ret)
- {
- ret.set_int(this.runtime.original_width);
- };
- SysExps.prototype.originalwindowheight = function (ret)
- {
- ret.set_int(this.runtime.original_height);
- };
- sysProto.exps = new SysExps();
- sysProto.runWaits = function ()
- {
- var i, j, len, w, k, s, ss;
- var evinfo = this.runtime.getCurrentEventStack();
- for (i = 0, len = this.waits.length; i < len; i++)
- {
- w = this.waits[i];
- if (w.time === -1) // signalled wait
- {
- if (!w.signalled)
- continue; // not yet signalled
- }
- else // timer wait
- {
- if (w.time > this.runtime.kahanTime.sum)
- continue; // timer not yet expired
- }
- evinfo.current_event = w.ev;
- evinfo.actindex = w.actindex;
- evinfo.cndindex = 0;
- for (k in w.sols)
- {
- if (w.sols.hasOwnProperty(k))
- {
- s = this.runtime.types_by_index[parseInt(k, 10)].getCurrentSol();
- ss = w.sols[k];
- s.select_all = ss.sa;
- cr.shallowAssignArray(s.instances, ss.insts);
- freeSolStateObject(ss);
- }
- }
- w.ev.resume_actions_and_subevents();
- this.runtime.clearSol(w.solModifiers);
- w.deleteme = true;
- }
- for (i = 0, j = 0, len = this.waits.length; i < len; i++)
- {
- w = this.waits[i];
- this.waits[j] = w;
- if (w.deleteme)
- freeWaitObject(w);
- else
- j++;
- }
- cr.truncateArray(this.waits, j);
- };
- }());
- ;
- (function () {
- cr.add_common_aces = function (m, pluginProto)
- {
- var singleglobal_ = m[1];
- var position_aces = m[3];
- var size_aces = m[4];
- var angle_aces = m[5];
- var appearance_aces = m[6];
- var zorder_aces = m[7];
- var effects_aces = m[8];
- if (!pluginProto.cnds)
- pluginProto.cnds = {};
- if (!pluginProto.acts)
- pluginProto.acts = {};
- if (!pluginProto.exps)
- pluginProto.exps = {};
- var cnds = pluginProto.cnds;
- var acts = pluginProto.acts;
- var exps = pluginProto.exps;
- if (position_aces)
- {
- cnds.CompareX = function (cmp, x)
- {
- return cr.do_cmp(this.x, cmp, x);
- };
- cnds.CompareY = function (cmp, y)
- {
- return cr.do_cmp(this.y, cmp, y);
- };
- cnds.IsOnScreen = function ()
- {
- var layer = this.layer;
- this.update_bbox();
- var bbox = this.bbox;
- return !(bbox.right < layer.viewLeft || bbox.bottom < layer.viewTop || bbox.left > layer.viewRight || bbox.top > layer.viewBottom);
- };
- cnds.IsOutsideLayout = function ()
- {
- this.update_bbox();
- var bbox = this.bbox;
- var layout = this.runtime.running_layout;
- return (bbox.right < 0 || bbox.bottom < 0 || bbox.left > layout.width || bbox.top > layout.height);
- };
- cnds.PickDistance = function (which, x, y)
- {
- var sol = this.getCurrentSol();
- var instances = sol.getObjects();
- if (!instances.length)
- return false;
- var inst = instances[0];
- var pickme = inst;
- var dist = cr.distanceTo(inst.x, inst.y, x, y);
- var i, len, d;
- for (i = 1, len = instances.length; i < len; i++)
- {
- inst = instances[i];
- d = cr.distanceTo(inst.x, inst.y, x, y);
- if ((which === 0 && d < dist) || (which === 1 && d > dist))
- {
- dist = d;
- pickme = inst;
- }
- }
- sol.pick_one(pickme);
- return true;
- };
- acts.SetX = function (x)
- {
- if (this.x !== x)
- {
- this.x = x;
- this.set_bbox_changed();
- }
- };
- acts.SetY = function (y)
- {
- if (this.y !== y)
- {
- this.y = y;
- this.set_bbox_changed();
- }
- };
- acts.SetPos = function (x, y)
- {
- if (this.x !== x || this.y !== y)
- {
- this.x = x;
- this.y = y;
- this.set_bbox_changed();
- }
- };
- acts.SetPosToObject = function (obj, imgpt)
- {
- var inst = obj.getPairedInstance(this);
- if (!inst)
- return;
- var newx, newy;
- if (inst.getImagePoint)
- {
- newx = inst.getImagePoint(imgpt, true);
- newy = inst.getImagePoint(imgpt, false);
- }
- else
- {
- newx = inst.x;
- newy = inst.y;
- }
- if (this.x !== newx || this.y !== newy)
- {
- this.x = newx;
- this.y = newy;
- this.set_bbox_changed();
- }
- };
- acts.MoveForward = function (dist)
- {
- if (dist !== 0)
- {
- this.x += Math.cos(this.angle) * dist;
- this.y += Math.sin(this.angle) * dist;
- this.set_bbox_changed();
- }
- };
- acts.MoveAtAngle = function (a, dist)
- {
- if (dist !== 0)
- {
- this.x += Math.cos(cr.to_radians(a)) * dist;
- this.y += Math.sin(cr.to_radians(a)) * dist;
- this.set_bbox_changed();
- }
- };
- exps.X = function (ret)
- {
- ret.set_float(this.x);
- };
- exps.Y = function (ret)
- {
- ret.set_float(this.y);
- };
- exps.dt = function (ret)
- {
- ret.set_float(this.runtime.getDt(this));
- };
- }
- if (size_aces)
- {
- cnds.CompareWidth = function (cmp, w)
- {
- return cr.do_cmp(this.width, cmp, w);
- };
- cnds.CompareHeight = function (cmp, h)
- {
- return cr.do_cmp(this.height, cmp, h);
- };
- acts.SetWidth = function (w)
- {
- if (this.width !== w)
- {
- this.width = w;
- this.set_bbox_changed();
- }
- };
- acts.SetHeight = function (h)
- {
- if (this.height !== h)
- {
- this.height = h;
- this.set_bbox_changed();
- }
- };
- acts.SetSize = function (w, h)
- {
- if (this.width !== w || this.height !== h)
- {
- this.width = w;
- this.height = h;
- this.set_bbox_changed();
- }
- };
- exps.Width = function (ret)
- {
- ret.set_float(this.width);
- };
- exps.Height = function (ret)
- {
- ret.set_float(this.height);
- };
- exps.BBoxLeft = function (ret)
- {
- this.update_bbox();
- ret.set_float(this.bbox.left);
- };
- exps.BBoxTop = function (ret)
- {
- this.update_bbox();
- ret.set_float(this.bbox.top);
- };
- exps.BBoxRight = function (ret)
- {
- this.update_bbox();
- ret.set_float(this.bbox.right);
- };
- exps.BBoxBottom = function (ret)
- {
- this.update_bbox();
- ret.set_float(this.bbox.bottom);
- };
- }
- if (angle_aces)
- {
- cnds.AngleWithin = function (within, a)
- {
- return cr.angleDiff(this.angle, cr.to_radians(a)) <= cr.to_radians(within);
- };
- cnds.IsClockwiseFrom = function (a)
- {
- return cr.angleClockwise(this.angle, cr.to_radians(a));
- };
- cnds.IsBetweenAngles = function (a, b)
- {
- var lower = cr.to_clamped_radians(a);
- var upper = cr.to_clamped_radians(b);
- var angle = cr.clamp_angle(this.angle);
- var obtuse = (!cr.angleClockwise(upper, lower));
- if (obtuse)
- return !(!cr.angleClockwise(angle, lower) && cr.angleClockwise(angle, upper));
- else
- return cr.angleClockwise(angle, lower) && !cr.angleClockwise(angle, upper);
- };
- acts.SetAngle = function (a)
- {
- var newangle = cr.to_radians(cr.clamp_angle_degrees(a));
- if (isNaN(newangle))
- return;
- if (this.angle !== newangle)
- {
- this.angle = newangle;
- this.set_bbox_changed();
- }
- };
- acts.RotateClockwise = function (a)
- {
- if (a !== 0 && !isNaN(a))
- {
- this.angle += cr.to_radians(a);
- this.angle = cr.clamp_angle(this.angle);
- this.set_bbox_changed();
- }
- };
- acts.RotateCounterclockwise = function (a)
- {
- if (a !== 0 && !isNaN(a))
- {
- this.angle -= cr.to_radians(a);
- this.angle = cr.clamp_angle(this.angle);
- this.set_bbox_changed();
- }
- };
- acts.RotateTowardAngle = function (amt, target)
- {
- var newangle = cr.angleRotate(this.angle, cr.to_radians(target), cr.to_radians(amt));
- if (isNaN(newangle))
- return;
- if (this.angle !== newangle)
- {
- this.angle = newangle;
- this.set_bbox_changed();
- }
- };
- acts.RotateTowardPosition = function (amt, x, y)
- {
- var dx = x - this.x;
- var dy = y - this.y;
- var target = Math.atan2(dy, dx);
- var newangle = cr.angleRotate(this.angle, target, cr.to_radians(amt));
- if (isNaN(newangle))
- return;
- if (this.angle !== newangle)
- {
- this.angle = newangle;
- this.set_bbox_changed();
- }
- };
- acts.SetTowardPosition = function (x, y)
- {
- var dx = x - this.x;
- var dy = y - this.y;
- var newangle = Math.atan2(dy, dx);
- if (isNaN(newangle))
- return;
- if (this.angle !== newangle)
- {
- this.angle = newangle;
- this.set_bbox_changed();
- }
- };
- exps.Angle = function (ret)
- {
- ret.set_float(cr.to_clamped_degrees(this.angle));
- };
- }
- if (!singleglobal_)
- {
- cnds.CompareInstanceVar = function (iv, cmp, val)
- {
- return cr.do_cmp(this.instance_vars[iv], cmp, val);
- };
- cnds.IsBoolInstanceVarSet = function (iv)
- {
- return this.instance_vars[iv];
- };
- cnds.PickInstVarHiLow = function (which, iv)
- {
- var sol = this.getCurrentSol();
- var instances = sol.getObjects();
- if (!instances.length)
- return false;
- var inst = instances[0];
- var pickme = inst;
- var val = inst.instance_vars[iv];
- var i, len, v;
- for (i = 1, len = instances.length; i < len; i++)
- {
- inst = instances[i];
- v = inst.instance_vars[iv];
- if ((which === 0 && v < val) || (which === 1 && v > val))
- {
- val = v;
- pickme = inst;
- }
- }
- sol.pick_one(pickme);
- return true;
- };
- cnds.PickByUID = function (u)
- {
- var i, len, j, inst, families, instances, sol;
- var cnd = this.runtime.getCurrentCondition();
- if (cnd.inverted)
- {
- sol = this.getCurrentSol();
- if (sol.select_all)
- {
- sol.select_all = false;
- cr.clearArray(sol.instances);
- cr.clearArray(sol.else_instances);
- instances = this.instances;
- for (i = 0, len = instances.length; i < len; i++)
- {
- inst = instances[i];
- if (inst.uid === u)
- sol.else_instances.push(inst);
- else
- sol.instances.push(inst);
- }
- this.applySolToContainer();
- return !!sol.instances.length;
- }
- else
- {
- for (i = 0, j = 0, len = sol.instances.length; i < len; i++)
- {
- inst = sol.instances[i];
- sol.instances[j] = inst;
- if (inst.uid === u)
- {
- sol.else_instances.push(inst);
- }
- else
- j++;
- }
- cr.truncateArray(sol.instances, j);
- this.applySolToContainer();
- return !!sol.instances.length;
- }
- }
- else
- {
- inst = this.runtime.getObjectByUID(u);
- if (!inst)
- return false;
- sol = this.getCurrentSol();
- if (!sol.select_all && sol.instances.indexOf(inst) === -1)
- return false; // not picked
- if (this.is_family)
- {
- families = inst.type.families;
- for (i = 0, len = families.length; i < len; i++)
- {
- if (families[i] === this)
- {
- sol.pick_one(inst);
- this.applySolToContainer();
- return true;
- }
- }
- }
- else if (inst.type === this)
- {
- sol.pick_one(inst);
- this.applySolToContainer();
- return true;
- }
- return false;
- }
- };
- cnds.OnCreated = function ()
- {
- return true;
- };
- cnds.OnDestroyed = function ()
- {
- return true;
- };
- acts.SetInstanceVar = function (iv, val)
- {
- var myinstvars = this.instance_vars;
- if (cr.is_number(myinstvars[iv]))
- {
- if (cr.is_number(val))
- myinstvars[iv] = val;
- else
- myinstvars[iv] = parseFloat(val);
- }
- else if (cr.is_string(myinstvars[iv]))
- {
- if (cr.is_string(val))
- myinstvars[iv] = val;
- else
- myinstvars[iv] = val.toString();
- }
- else
- ;
- };
- acts.AddInstanceVar = function (iv, val)
- {
- var myinstvars = this.instance_vars;
- if (cr.is_number(myinstvars[iv]))
- {
- if (cr.is_number(val))
- myinstvars[iv] += val;
- else
- myinstvars[iv] += parseFloat(val);
- }
- else if (cr.is_string(myinstvars[iv]))
- {
- if (cr.is_string(val))
- myinstvars[iv] += val;
- else
- myinstvars[iv] += val.toString();
- }
- else
- ;
- };
- acts.SubInstanceVar = function (iv, val)
- {
- var myinstvars = this.instance_vars;
- if (cr.is_number(myinstvars[iv]))
- {
- if (cr.is_number(val))
- myinstvars[iv] -= val;
- else
- myinstvars[iv] -= parseFloat(val);
- }
- else
- ;
- };
- acts.SetBoolInstanceVar = function (iv, val)
- {
- this.instance_vars[iv] = val ? 1 : 0;
- };
- acts.ToggleBoolInstanceVar = function (iv)
- {
- this.instance_vars[iv] = 1 - this.instance_vars[iv];
- };
- acts.Destroy = function ()
- {
- this.runtime.DestroyInstance(this);
- };
- if (!acts.LoadFromJsonString)
- {
- acts.LoadFromJsonString = function (str_)
- {
- var o, i, len, binst;
- try {
- o = JSON.parse(str_);
- }
- catch (e) {
- return;
- }
- this.runtime.loadInstanceFromJSON(this, o, true);
- if (this.afterLoad)
- this.afterLoad();
- if (this.behavior_insts)
- {
- for (i = 0, len = this.behavior_insts.length; i < len; ++i)
- {
- binst = this.behavior_insts[i];
- if (binst.afterLoad)
- binst.afterLoad();
- }
- }
- };
- }
- exps.Count = function (ret)
- {
- var count = ret.object_class.instances.length;
- var i, len, inst;
- for (i = 0, len = this.runtime.createRow.length; i < len; i++)
- {
- inst = this.runtime.createRow[i];
- if (ret.object_class.is_family)
- {
- if (inst.type.families.indexOf(ret.object_class) >= 0)
- count++;
- }
- else
- {
- if (inst.type === ret.object_class)
- count++;
- }
- }
- ret.set_int(count);
- };
- exps.PickedCount = function (ret)
- {
- ret.set_int(ret.object_class.getCurrentSol().getObjects().length);
- };
- exps.UID = function (ret)
- {
- ret.set_int(this.uid);
- };
- exps.IID = function (ret)
- {
- ret.set_int(this.get_iid());
- };
- if (!exps.AsJSON)
- {
- exps.AsJSON = function (ret)
- {
- ret.set_string(JSON.stringify(this.runtime.saveInstanceToJSON(this, true)));
- };
- }
- }
- if (appearance_aces)
- {
- cnds.IsVisible = function ()
- {
- return this.visible;
- };
- acts.SetVisible = function (v)
- {
- if (!v !== !this.visible)
- {
- this.visible = v;
- this.runtime.redraw = true;
- }
- };
- cnds.CompareOpacity = function (cmp, x)
- {
- return cr.do_cmp(cr.round6dp(this.opacity * 100), cmp, x);
- };
- acts.SetOpacity = function (x)
- {
- var new_opacity = x / 100.0;
- if (new_opacity < 0)
- new_opacity = 0;
- else if (new_opacity > 1)
- new_opacity = 1;
- if (new_opacity !== this.opacity)
- {
- this.opacity = new_opacity;
- this.runtime.redraw = true;
- }
- };
- exps.Opacity = function (ret)
- {
- ret.set_float(cr.round6dp(this.opacity * 100.0));
- };
- }
- if (zorder_aces)
- {
- cnds.IsOnLayer = function (layer_)
- {
- if (!layer_)
- return false;
- return this.layer === layer_;
- };
- cnds.PickTopBottom = function (which_)
- {
- var sol = this.getCurrentSol();
- var instances = sol.getObjects();
- if (!instances.length)
- return false;
- var inst = instances[0];
- var pickme = inst;
- var i, len;
- for (i = 1, len = instances.length; i < len; i++)
- {
- inst = instances[i];
- if (which_ === 0)
- {
- if (inst.layer.index > pickme.layer.index || (inst.layer.index === pickme.layer.index && inst.get_zindex() > pickme.get_zindex()))
- {
- pickme = inst;
- }
- }
- else
- {
- if (inst.layer.index < pickme.layer.index || (inst.layer.index === pickme.layer.index && inst.get_zindex() < pickme.get_zindex()))
- {
- pickme = inst;
- }
- }
- }
- sol.pick_one(pickme);
- return true;
- };
- acts.MoveToTop = function ()
- {
- var layer = this.layer;
- var layer_instances = layer.instances;
- if (layer_instances.length && layer_instances[layer_instances.length - 1] === this)
- return; // is already at top
- layer.removeFromInstanceList(this, false);
- layer.appendToInstanceList(this, false);
- this.runtime.redraw = true;
- };
- acts.MoveToBottom = function ()
- {
- var layer = this.layer;
- var layer_instances = layer.instances;
- if (layer_instances.length && layer_instances[0] === this)
- return; // is already at bottom
- layer.removeFromInstanceList(this, false);
- layer.prependToInstanceList(this, false);
- this.runtime.redraw = true;
- };
- acts.MoveToLayer = function (layerMove)
- {
- if (!layerMove || layerMove == this.layer)
- return;
- this.layer.removeFromInstanceList(this, true);
- this.layer = layerMove;
- layerMove.appendToInstanceList(this, true);
- this.runtime.redraw = true;
- };
- acts.ZMoveToObject = function (where_, obj_)
- {
- var isafter = (where_ === 0);
- if (!obj_)
- return;
- var other = obj_.getFirstPicked(this);
- if (!other || other.uid === this.uid)
- return;
- if (this.layer.index !== other.layer.index)
- {
- this.layer.removeFromInstanceList(this, true);
- this.layer = other.layer;
- other.layer.appendToInstanceList(this, true);
- }
- this.layer.moveInstanceAdjacent(this, other, isafter);
- this.runtime.redraw = true;
- };
- exps.LayerNumber = function (ret)
- {
- ret.set_int(this.layer.number);
- };
- exps.LayerName = function (ret)
- {
- ret.set_string(this.layer.name);
- };
- exps.ZIndex = function (ret)
- {
- ret.set_int(this.get_zindex());
- };
- }
- if (effects_aces)
- {
- acts.SetEffectEnabled = function (enable_, effectname_)
- {
- if (!this.runtime.glwrap)
- return;
- var i = this.type.getEffectIndexByName(effectname_);
- if (i < 0)
- return; // effect name not found
- var enable = (enable_ === 1);
- if (this.active_effect_flags[i] === enable)
- return; // no change
- this.active_effect_flags[i] = enable;
- this.updateActiveEffects();
- this.runtime.redraw = true;
- };
- acts.SetEffectParam = function (effectname_, index_, value_)
- {
- if (!this.runtime.glwrap)
- return;
- var i = this.type.getEffectIndexByName(effectname_);
- if (i < 0)
- return; // effect name not found
- var et = this.type.effect_types[i];
- var params = this.effect_params[i];
- index_ = Math.floor(index_);
- if (index_ < 0 || index_ >= params.length)
- return; // effect index out of bounds
- if (this.runtime.glwrap.getProgramParameterType(et.shaderindex, index_) === 1)
- value_ /= 100.0;
- if (params[index_] === value_)
- return; // no change
- params[index_] = value_;
- if (et.active)
- this.runtime.redraw = true;
- };
- }
- };
- cr.set_bbox_changed = function ()
- {
- this.bbox_changed = true; // will recreate next time box requested
- this.cell_changed = true;
- this.type.any_cell_changed = true; // avoid unnecessary updateAllBBox() calls
- this.runtime.redraw = true; // assume runtime needs to redraw
- var i, len, callbacks = this.bbox_changed_callbacks;
- for (i = 0, len = callbacks.length; i < len; ++i)
- {
- callbacks[i](this);
- }
- if (this.layer.useRenderCells)
- this.update_bbox();
- };
- cr.add_bbox_changed_callback = function (f)
- {
- if (f)
- {
- this.bbox_changed_callbacks.push(f);
- }
- };
- cr.update_bbox = function ()
- {
- if (!this.bbox_changed)
- return; // bounding box not changed
- var bbox = this.bbox;
- var bquad = this.bquad;
- bbox.set(this.x, this.y, this.x + this.width, this.y + this.height);
- bbox.offset(-this.hotspotX * this.width, -this.hotspotY * this.height);
- if (!this.angle)
- {
- bquad.set_from_rect(bbox); // make bounding quad from box
- }
- else
- {
- bbox.offset(-this.x, -this.y); // translate to origin
- bquad.set_from_rotated_rect(bbox, this.angle); // rotate around origin
- bquad.offset(this.x, this.y); // translate back to original position
- bquad.bounding_box(bbox);
- }
- bbox.normalize();
- this.bbox_changed = false; // bounding box up to date
- this.update_render_cell();
- };
- var tmprc = new cr.rect(0, 0, 0, 0);
- cr.update_render_cell = function ()
- {
- if (!this.layer.useRenderCells)
- return;
- var mygrid = this.layer.render_grid;
- var bbox = this.bbox;
- tmprc.set(mygrid.XToCell(bbox.left), mygrid.YToCell(bbox.top), mygrid.XToCell(bbox.right), mygrid.YToCell(bbox.bottom));
- if (this.rendercells.equals(tmprc))
- return;
- if (this.rendercells.right < this.rendercells.left)
- mygrid.update(this, null, tmprc); // first insertion with invalid rect: don't provide old range
- else
- mygrid.update(this, this.rendercells, tmprc);
- this.rendercells.copy(tmprc);
- this.layer.render_list_stale = true;
- };
- cr.update_collision_cell = function ()
- {
- if (!this.cell_changed || !this.collisionsEnabled)
- return;
- this.update_bbox();
- var mygrid = this.type.collision_grid;
- var bbox = this.bbox;
- tmprc.set(mygrid.XToCell(bbox.left), mygrid.YToCell(bbox.top), mygrid.XToCell(bbox.right), mygrid.YToCell(bbox.bottom));
- if (this.collcells.equals(tmprc))
- return;
- if (this.collcells.right < this.collcells.left)
- mygrid.update(this, null, tmprc); // first insertion with invalid rect: don't provide old range
- else
- mygrid.update(this, this.collcells, tmprc);
- this.collcells.copy(tmprc);
- this.cell_changed = false;
- };
- cr.inst_contains_pt = function (x, y)
- {
- if (!this.bbox.contains_pt(x, y))
- return false;
- if (!this.bquad.contains_pt(x, y))
- return false;
- if (this.collision_poly && !this.collision_poly.is_empty())
- {
- this.collision_poly.cache_poly(this.width, this.height, this.angle);
- return this.collision_poly.contains_pt(x - this.x, y - this.y);
- }
- else
- return true;
- };
- cr.inst_get_iid = function ()
- {
- this.type.updateIIDs();
- return this.iid;
- };
- cr.inst_get_zindex = function ()
- {
- this.layer.updateZIndices();
- return this.zindex;
- };
- cr.inst_updateActiveEffects = function ()
- {
- cr.clearArray(this.active_effect_types);
- var i, len, et, inst;
- for (i = 0, len = this.active_effect_flags.length; i < len; i++)
- {
- if (this.active_effect_flags[i])
- this.active_effect_types.push(this.type.effect_types[i]);
- }
- this.uses_shaders = !!this.active_effect_types.length;
- };
- cr.inst_toString = function ()
- {
- return "Inst" + this.puid;
- };
- cr.type_getFirstPicked = function (frominst)
- {
- if (frominst && frominst.is_contained && frominst.type != this)
- {
- var i, len, s;
- for (i = 0, len = frominst.siblings.length; i < len; i++)
- {
- s = frominst.siblings[i];
- if (s.type == this)
- return s;
- }
- }
- var instances = this.getCurrentSol().getObjects();
- if (instances.length)
- return instances[0];
- else
- return null;
- };
- cr.type_getPairedInstance = function (inst)
- {
- var instances = this.getCurrentSol().getObjects();
- if (instances.length)
- return instances[inst.get_iid() % instances.length];
- else
- return null;
- };
- cr.type_updateIIDs = function ()
- {
- if (!this.stale_iids || this.is_family)
- return; // up to date or is family - don't want family to overwrite IIDs
- var i, len;
- for (i = 0, len = this.instances.length; i < len; i++)
- this.instances[i].iid = i;
- var next_iid = i;
- var createRow = this.runtime.createRow;
- for (i = 0, len = createRow.length; i < len; ++i)
- {
- if (createRow[i].type === this)
- createRow[i].iid = next_iid++;
- }
- this.stale_iids = false;
- };
- cr.type_getInstanceByIID = function (i)
- {
- if (i < this.instances.length)
- return this.instances[i];
- i -= this.instances.length;
- var createRow = this.runtime.createRow;
- var j, lenj;
- for (j = 0, lenj = createRow.length; j < lenj; ++j)
- {
- if (createRow[j].type === this)
- {
- if (i === 0)
- return createRow[j];
- --i;
- }
- }
- ;
- return null;
- };
- cr.type_getCurrentSol = function ()
- {
- return this.solstack[this.cur_sol];
- };
- cr.type_pushCleanSol = function ()
- {
- this.cur_sol++;
- if (this.cur_sol === this.solstack.length)
- this.solstack.push(new cr.selection(this));
- else
- this.solstack[this.cur_sol].select_all = true; // else clear next SOL
- };
- cr.type_pushCopySol = function ()
- {
- this.cur_sol++;
- if (this.cur_sol === this.solstack.length)
- this.solstack.push(new cr.selection(this));
- var clonesol = this.solstack[this.cur_sol];
- var prevsol = this.solstack[this.cur_sol - 1];
- if (prevsol.select_all)
- clonesol.select_all = true;
- else
- {
- clonesol.select_all = false;
- cr.shallowAssignArray(clonesol.instances, prevsol.instances);
- cr.shallowAssignArray(clonesol.else_instances, prevsol.else_instances);
- }
- };
- cr.type_popSol = function ()
- {
- ;
- this.cur_sol--;
- };
- cr.type_getBehaviorByName = function (behname)
- {
- var i, len, j, lenj, f, index = 0;
- if (!this.is_family)
- {
- for (i = 0, len = this.families.length; i < len; i++)
- {
- f = this.families[i];
- for (j = 0, lenj = f.behaviors.length; j < lenj; j++)
- {
- if (behname === f.behaviors[j].name)
- {
- this.extra["lastBehIndex"] = index;
- return f.behaviors[j];
- }
- index++;
- }
- }
- }
- for (i = 0, len = this.behaviors.length; i < len; i++) {
- if (behname === this.behaviors[i].name)
- {
- this.extra["lastBehIndex"] = index;
- return this.behaviors[i];
- }
- index++;
- }
- return null;
- };
- cr.type_getBehaviorIndexByName = function (behname)
- {
- var b = this.getBehaviorByName(behname);
- if (b)
- return this.extra["lastBehIndex"];
- else
- return -1;
- };
- cr.type_getEffectIndexByName = function (name_)
- {
- var i, len;
- for (i = 0, len = this.effect_types.length; i < len; i++)
- {
- if (this.effect_types[i].name === name_)
- return i;
- }
- return -1;
- };
- cr.type_applySolToContainer = function ()
- {
- if (!this.is_contained || this.is_family)
- return;
- var i, len, j, lenj, t, sol, sol2;
- this.updateIIDs();
- sol = this.getCurrentSol();
- var select_all = sol.select_all;
- var es = this.runtime.getCurrentEventStack();
- var orblock = es && es.current_event && es.current_event.orblock;
- for (i = 0, len = this.container.length; i < len; i++)
- {
- t = this.container[i];
- if (t === this)
- continue;
- t.updateIIDs();
- sol2 = t.getCurrentSol();
- sol2.select_all = select_all;
- if (!select_all)
- {
- cr.clearArray(sol2.instances);
- for (j = 0, lenj = sol.instances.length; j < lenj; ++j)
- sol2.instances[j] = t.getInstanceByIID(sol.instances[j].iid);
- if (orblock)
- {
- cr.clearArray(sol2.else_instances);
- for (j = 0, lenj = sol.else_instances.length; j < lenj; ++j)
- sol2.else_instances[j] = t.getInstanceByIID(sol.else_instances[j].iid);
- }
- }
- }
- };
- cr.type_toString = function ()
- {
- return "Type" + this.sid;
- };
- cr.do_cmp = function (x, cmp, y)
- {
- if (typeof x === "undefined" || typeof y === "undefined")
- return false;
- switch (cmp)
- {
- case 0: // equal
- return x === y;
- case 1: // not equal
- return x !== y;
- case 2: // less
- return x < y;
- case 3: // less/equal
- return x <= y;
- case 4: // greater
- return x > y;
- case 5: // greater/equal
- return x >= y;
- default:
- ;
- return false;
- }
- };
- })();
- cr.shaders = {};
- ;
- ;
- cr.plugins_.Arr = function(runtime)
- {
- this.runtime = runtime;
- };
- (function ()
- {
- var pluginProto = cr.plugins_.Arr.prototype;
- pluginProto.Type = function(plugin)
- {
- this.plugin = plugin;
- this.runtime = plugin.runtime;
- };
- var typeProto = pluginProto.Type.prototype;
- typeProto.onCreate = function()
- {
- };
- pluginProto.Instance = function(type)
- {
- this.type = type;
- this.runtime = type.runtime;
- };
- var instanceProto = pluginProto.Instance.prototype;
- var arrCache = [];
- function allocArray()
- {
- if (arrCache.length)
- return arrCache.pop();
- else
- return [];
- };
- if (!Array.isArray)
- {
- Array.isArray = function (vArg) {
- return Object.prototype.toString.call(vArg) === "[object Array]";
- };
- }
- function freeArray(a)
- {
- var i, len;
- for (i = 0, len = a.length; i < len; i++)
- {
- if (Array.isArray(a[i]))
- freeArray(a[i]);
- }
- cr.clearArray(a);
- arrCache.push(a);
- };
- instanceProto.onCreate = function()
- {
- this.cx = this.properties[0];
- this.cy = this.properties[1];
- this.cz = this.properties[2];
- if (!this.recycled)
- this.arr = allocArray();
- var a = this.arr;
- a.length = this.cx;
- var x, y, z;
- for (x = 0; x < this.cx; x++)
- {
- if (!a[x])
- a[x] = allocArray();
- a[x].length = this.cy;
- for (y = 0; y < this.cy; y++)
- {
- if (!a[x][y])
- a[x][y] = allocArray();
- a[x][y].length = this.cz;
- for (z = 0; z < this.cz; z++)
- a[x][y][z] = 0;
- }
- }
- this.forX = [];
- this.forY = [];
- this.forZ = [];
- this.forDepth = -1;
- };
- instanceProto.onDestroy = function ()
- {
- var x;
- for (x = 0; x < this.cx; x++)
- freeArray(this.arr[x]); // will recurse down and recycle other arrays
- cr.clearArray(this.arr);
- };
- instanceProto.at = function (x, y, z)
- {
- x = Math.floor(x);
- y = Math.floor(y);
- z = Math.floor(z);
- if (isNaN(x) || x < 0 || x > this.cx - 1)
- return 0;
- if (isNaN(y) || y < 0 || y > this.cy - 1)
- return 0;
- if (isNaN(z) || z < 0 || z > this.cz - 1)
- return 0;
- return this.arr[x][y][z];
- };
- instanceProto.set = function (x, y, z, val)
- {
- x = Math.floor(x);
- y = Math.floor(y);
- z = Math.floor(z);
- if (isNaN(x) || x < 0 || x > this.cx - 1)
- return;
- if (isNaN(y) || y < 0 || y > this.cy - 1)
- return;
- if (isNaN(z) || z < 0 || z > this.cz - 1)
- return;
- this.arr[x][y][z] = val;
- };
- instanceProto.getAsJSON = function ()
- {
- return JSON.stringify({
- "c2array": true,
- "size": [this.cx, this.cy, this.cz],
- "data": this.arr
- });
- };
- instanceProto.saveToJSON = function ()
- {
- return {
- "size": [this.cx, this.cy, this.cz],
- "data": this.arr
- };
- };
- instanceProto.loadFromJSON = function (o)
- {
- var sz = o["size"];
- this.cx = sz[0];
- this.cy = sz[1];
- this.cz = sz[2];
- this.arr = o["data"];
- };
- instanceProto.setSize = function (w, h, d)
- {
- if (w < 0) w = 0;
- if (h < 0) h = 0;
- if (d < 0) d = 0;
- if (this.cx === w && this.cy === h && this.cz === d)
- return; // no change
- this.cx = w;
- this.cy = h;
- this.cz = d;
- var x, y, z;
- var a = this.arr;
- a.length = w;
- for (x = 0; x < this.cx; x++)
- {
- if (cr.is_undefined(a[x]))
- a[x] = allocArray();
- a[x].length = h;
- for (y = 0; y < this.cy; y++)
- {
- if (cr.is_undefined(a[x][y]))
- a[x][y] = allocArray();
- a[x][y].length = d;
- for (z = 0; z < this.cz; z++)
- {
- if (cr.is_undefined(a[x][y][z]))
- a[x][y][z] = 0;
- }
- }
- }
- };
- instanceProto.getForX = function ()
- {
- if (this.forDepth >= 0 && this.forDepth < this.forX.length)
- return this.forX[this.forDepth];
- else
- return 0;
- };
- instanceProto.getForY = function ()
- {
- if (this.forDepth >= 0 && this.forDepth < this.forY.length)
- return this.forY[this.forDepth];
- else
- return 0;
- };
- instanceProto.getForZ = function ()
- {
- if (this.forDepth >= 0 && this.forDepth < this.forZ.length)
- return this.forZ[this.forDepth];
- else
- return 0;
- };
- function Cnds() {};
- Cnds.prototype.CompareX = function (x, cmp, val)
- {
- return cr.do_cmp(this.at(x, 0, 0), cmp, val);
- };
- Cnds.prototype.CompareXY = function (x, y, cmp, val)
- {
- return cr.do_cmp(this.at(x, y, 0), cmp, val);
- };
- Cnds.prototype.CompareXYZ = function (x, y, z, cmp, val)
- {
- return cr.do_cmp(this.at(x, y, z), cmp, val);
- };
- instanceProto.doForEachTrigger = function (current_event)
- {
- this.runtime.pushCopySol(current_event.solModifiers);
- current_event.retrigger();
- this.runtime.popSol(current_event.solModifiers);
- };
- Cnds.prototype.ArrForEach = function (dims)
- {
- var current_event = this.runtime.getCurrentEventStack().current_event;
- this.forDepth++;
- var forDepth = this.forDepth;
- if (forDepth === this.forX.length)
- {
- this.forX.push(0);
- this.forY.push(0);
- this.forZ.push(0);
- }
- else
- {
- this.forX[forDepth] = 0;
- this.forY[forDepth] = 0;
- this.forZ[forDepth] = 0;
- }
- switch (dims) {
- case 0:
- for (this.forX[forDepth] = 0; this.forX[forDepth] < this.cx; this.forX[forDepth]++)
- {
- for (this.forY[forDepth] = 0; this.forY[forDepth] < this.cy; this.forY[forDepth]++)
- {
- for (this.forZ[forDepth] = 0; this.forZ[forDepth] < this.cz; this.forZ[forDepth]++)
- {
- this.doForEachTrigger(current_event);
- }
- }
- }
- break;
- case 1:
- for (this.forX[forDepth] = 0; this.forX[forDepth] < this.cx; this.forX[forDepth]++)
- {
- for (this.forY[forDepth] = 0; this.forY[forDepth] < this.cy; this.forY[forDepth]++)
- {
- this.doForEachTrigger(current_event);
- }
- }
- break;
- case 2:
- for (this.forX[forDepth] = 0; this.forX[forDepth] < this.cx; this.forX[forDepth]++)
- {
- this.doForEachTrigger(current_event);
- }
- break;
- }
- this.forDepth--;
- return false;
- };
- Cnds.prototype.CompareCurrent = function (cmp, val)
- {
- return cr.do_cmp(this.at(this.getForX(), this.getForY(), this.getForZ()), cmp, val);
- };
- Cnds.prototype.Contains = function(val)
- {
- var x, y, z;
- for (x = 0; x < this.cx; x++)
- {
- for (y = 0; y < this.cy; y++)
- {
- for (z = 0; z < this.cz; z++)
- {
- if (this.arr[x][y][z] === val)
- return true;
- }
- }
- }
- return false;
- };
- Cnds.prototype.IsEmpty = function ()
- {
- return this.cx === 0 || this.cy === 0 || this.cz === 0;
- };
- Cnds.prototype.CompareSize = function (axis, cmp, value)
- {
- var s = 0;
- switch (axis) {
- case 0:
- s = this.cx;
- break;
- case 1:
- s = this.cy;
- break;
- case 2:
- s = this.cz;
- break;
- }
- return cr.do_cmp(s, cmp, value);
- };
- pluginProto.cnds = new Cnds();
- function Acts() {};
- Acts.prototype.Clear = function ()
- {
- var x, y, z;
- for (x = 0; x < this.cx; x++)
- for (y = 0; y < this.cy; y++)
- for (z = 0; z < this.cz; z++)
- this.arr[x][y][z] = 0;
- };
- Acts.prototype.SetSize = function (w, h, d)
- {
- this.setSize(w, h, d);
- };
- Acts.prototype.SetX = function (x, val)
- {
- this.set(x, 0, 0, val);
- };
- Acts.prototype.SetXY = function (x, y, val)
- {
- this.set(x, y, 0, val);
- };
- Acts.prototype.SetXYZ = function (x, y, z, val)
- {
- this.set(x, y, z, val);
- };
- Acts.prototype.Push = function (where, value, axis)
- {
- var x = 0, y = 0, z = 0;
- var a = this.arr;
- switch (axis) {
- case 0: // X axis
- if (where === 0) // back
- {
- x = a.length;
- a.push(allocArray());
- }
- else // front
- {
- x = 0;
- a.unshift(allocArray());
- }
- a[x].length = this.cy;
- for ( ; y < this.cy; y++)
- {
- a[x][y] = allocArray();
- a[x][y].length = this.cz;
- for (z = 0; z < this.cz; z++)
- a[x][y][z] = value;
- }
- this.cx++;
- break;
- case 1: // Y axis
- for ( ; x < this.cx; x++)
- {
- if (where === 0) // back
- {
- y = a[x].length;
- a[x].push(allocArray());
- }
- else // front
- {
- y = 0;
- a[x].unshift(allocArray());
- }
- a[x][y].length = this.cz;
- for (z = 0; z < this.cz; z++)
- a[x][y][z] = value;
- }
- this.cy++;
- break;
- case 2: // Z axis
- for ( ; x < this.cx; x++)
- {
- for (y = 0; y < this.cy; y++)
- {
- if (where === 0) // back
- {
- a[x][y].push(value);
- }
- else // front
- {
- a[x][y].unshift(value);
- }
- }
- }
- this.cz++;
- break;
- }
- };
- Acts.prototype.Pop = function (where, axis)
- {
- var x = 0, y = 0, z = 0;
- var a = this.arr;
- switch (axis) {
- case 0: // X axis
- if (this.cx === 0)
- break;
- if (where === 0) // back
- {
- freeArray(a.pop());
- }
- else // front
- {
- freeArray(a.shift());
- }
- this.cx--;
- break;
- case 1: // Y axis
- if (this.cy === 0)
- break;
- for ( ; x < this.cx; x++)
- {
- if (where === 0) // back
- {
- freeArray(a[x].pop());
- }
- else // front
- {
- freeArray(a[x].shift());
- }
- }
- this.cy--;
- break;
- case 2: // Z axis
- if (this.cz === 0)
- break;
- for ( ; x < this.cx; x++)
- {
- for (y = 0; y < this.cy; y++)
- {
- if (where === 0) // back
- {
- a[x][y].pop();
- }
- else // front
- {
- a[x][y].shift();
- }
- }
- }
- this.cz--;
- break;
- }
- };
- Acts.prototype.Reverse = function (axis)
- {
- var x = 0, y = 0, z = 0;
- var a = this.arr;
- if (this.cx === 0 || this.cy === 0 || this.cz === 0)
- return; // no point reversing empty array
- switch (axis) {
- case 0: // X axis
- a.reverse();
- break;
- case 1: // Y axis
- for ( ; x < this.cx; x++)
- a[x].reverse();
- break;
- case 2: // Z axis
- for ( ; x < this.cx; x++)
- for (y = 0; y < this.cy; y++)
- a[x][y].reverse();
- this.cz--;
- break;
- }
- };
- function compareValues(va, vb)
- {
- if (cr.is_number(va) && cr.is_number(vb))
- return va - vb;
- else
- {
- var sa = "" + va;
- var sb = "" + vb;
- if (sa < sb)
- return -1;
- else if (sa > sb)
- return 1;
- else
- return 0;
- }
- }
- Acts.prototype.Sort = function (axis)
- {
- var x = 0, y = 0, z = 0;
- var a = this.arr;
- if (this.cx === 0 || this.cy === 0 || this.cz === 0)
- return; // no point sorting empty array
- switch (axis) {
- case 0: // X axis
- a.sort(function (a, b) {
- return compareValues(a[0][0], b[0][0]);
- });
- break;
- case 1: // Y axis
- for ( ; x < this.cx; x++)
- {
- a[x].sort(function (a, b) {
- return compareValues(a[0], b[0]);
- });
- }
- break;
- case 2: // Z axis
- for ( ; x < this.cx; x++)
- {
- for (y = 0; y < this.cy; y++)
- {
- a[x][y].sort(compareValues);
- }
- }
- break;
- }
- };
- Acts.prototype.Delete = function (index, axis)
- {
- var x = 0, y = 0, z = 0;
- index = Math.floor(index);
- var a = this.arr;
- if (index < 0)
- return;
- switch (axis) {
- case 0: // X axis
- if (index >= this.cx)
- break;
- freeArray(a[index]);
- a.splice(index, 1);
- this.cx--;
- break;
- case 1: // Y axis
- if (index >= this.cy)
- break;
- for ( ; x < this.cx; x++)
- {
- freeArray(a[x][index]);
- a[x].splice(index, 1);
- }
- this.cy--;
- break;
- case 2: // Z axis
- if (index >= this.cz)
- break;
- for ( ; x < this.cx; x++)
- {
- for (y = 0; y < this.cy; y++)
- {
- a[x][y].splice(index, 1);
- }
- }
- this.cz--;
- break;
- }
- };
- Acts.prototype.Insert = function (value, index, axis)
- {
- var x = 0, y = 0, z = 0;
- index = Math.floor(index);
- var a = this.arr;
- if (index < 0)
- return;
- switch (axis) {
- case 0: // X axis
- if (index > this.cx)
- return;
- x = index;
- a.splice(x, 0, allocArray());
- a[x].length = this.cy;
- for ( ; y < this.cy; y++)
- {
- a[x][y] = allocArray();
- a[x][y].length = this.cz;
- for (z = 0; z < this.cz; z++)
- a[x][y][z] = value;
- }
- this.cx++;
- break;
- case 1: // Y axis
- if (index > this.cy)
- return;
- for ( ; x < this.cx; x++)
- {
- y = index;
- a[x].splice(y, 0, allocArray());
- a[x][y].length = this.cz;
- for (z = 0; z < this.cz; z++)
- a[x][y][z] = value;
- }
- this.cy++;
- break;
- case 2: // Z axis
- if (index > this.cz)
- return;
- for ( ; x < this.cx; x++)
- {
- for (y = 0; y < this.cy; y++)
- {
- a[x][y].splice(index, 0, value);
- }
- }
- this.cz++;
- break;
- }
- };
- Acts.prototype.JSONLoad = function (json_)
- {
- var o;
- try {
- o = JSON.parse(json_);
- }
- catch(e) { return; }
- if (!o["c2array"]) // presumably not a c2array object
- return;
- var sz = o["size"];
- this.cx = sz[0];
- this.cy = sz[1];
- this.cz = sz[2];
- this.arr = o["data"];
- };
- Acts.prototype.JSONDownload = function (filename)
- {
- var a = document.createElement("a");
- if (typeof a.download === "undefined")
- {
- var str = 'data:text/html,' + encodeURIComponent("<p><a download='" + filename + "' href=\"data:application/json,"
- + encodeURIComponent(this.getAsJSON())
- + "\">Download link</a></p>");
- window.open(str);
- }
- else
- {
- var body = document.getElementsByTagName("body")[0];
- a.textContent = filename;
- a.href = "data:application/json," + encodeURIComponent(this.getAsJSON());
- a.download = filename;
- body.appendChild(a);
- var clickEvent = document.createEvent("MouseEvent");
- clickEvent.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
- a.dispatchEvent(clickEvent);
- body.removeChild(a);
- }
- };
- pluginProto.acts = new Acts();
- function Exps() {};
- Exps.prototype.At = function (ret, x, y_, z_)
- {
- var y = y_ || 0;
- var z = z_ || 0;
- ret.set_any(this.at(x, y, z));
- };
- Exps.prototype.Width = function (ret)
- {
- ret.set_int(this.cx);
- };
- Exps.prototype.Height = function (ret)
- {
- ret.set_int(this.cy);
- };
- Exps.prototype.Depth = function (ret)
- {
- ret.set_int(this.cz);
- };
- Exps.prototype.CurX = function (ret)
- {
- ret.set_int(this.getForX());
- };
- Exps.prototype.CurY = function (ret)
- {
- ret.set_int(this.getForY());
- };
- Exps.prototype.CurZ = function (ret)
- {
- ret.set_int(this.getForZ());
- };
- Exps.prototype.CurValue = function (ret)
- {
- ret.set_any(this.at(this.getForX(), this.getForY(), this.getForZ()));
- };
- Exps.prototype.Front = function (ret)
- {
- ret.set_any(this.at(0, 0, 0));
- };
- Exps.prototype.Back = function (ret)
- {
- ret.set_any(this.at(this.cx - 1, 0, 0));
- };
- Exps.prototype.IndexOf = function (ret, v)
- {
- for (var i = 0; i < this.cx; i++)
- {
- if (this.arr[i][0][0] === v)
- {
- ret.set_int(i);
- return;
- }
- }
- ret.set_int(-1);
- };
- Exps.prototype.LastIndexOf = function (ret, v)
- {
- for (var i = this.cx - 1; i >= 0; i--)
- {
- if (this.arr[i][0][0] === v)
- {
- ret.set_int(i);
- return;
- }
- }
- ret.set_int(-1);
- };
- Exps.prototype.AsJSON = function (ret)
- {
- ret.set_string(this.getAsJSON());
- };
- pluginProto.exps = new Exps();
- }());
- ;
- ;
- cr.plugins_.Audio = function(runtime)
- {
- this.runtime = runtime;
- };
- (function ()
- {
- var pluginProto = cr.plugins_.Audio.prototype;
- pluginProto.Type = function(plugin)
- {
- this.plugin = plugin;
- this.runtime = plugin.runtime;
- };
- var typeProto = pluginProto.Type.prototype;
- typeProto.onCreate = function()
- {
- };
- var audRuntime = null;
- var audInst = null;
- var audTag = "";
- var appPath = ""; // for Cordova only
- var API_HTML5 = 0;
- var API_WEBAUDIO = 1;
- var API_CORDOVA = 2;
- var API_APPMOBI = 3;
- var api = API_HTML5;
- var context = null;
- var audioBuffers = []; // cache of buffers
- var audioInstances = []; // cache of instances
- var lastAudio = null;
- var useOgg = false; // determined at create time
- var timescale_mode = 0;
- var silent = false;
- var masterVolume = 1;
- var listenerX = 0;
- var listenerY = 0;
- var panningModel = 1; // HRTF
- var distanceModel = 1; // Inverse
- var refDistance = 10;
- var maxDistance = 10000;
- var rolloffFactor = 1;
- var micSource = null;
- var micTag = "";
- var isMusicWorkaround = false;
- var musicPlayNextTouch = [];
- function dbToLinear(x)
- {
- var v = dbToLinear_nocap(x);
- if (v < 0)
- v = 0;
- if (v > 1)
- v = 1;
- return v;
- };
- function linearToDb(x)
- {
- if (x < 0)
- x = 0;
- if (x > 1)
- x = 1;
- return linearToDb_nocap(x);
- };
- function dbToLinear_nocap(x)
- {
- return Math.pow(10, x / 20);
- };
- function linearToDb_nocap(x)
- {
- return (Math.log(x) / Math.log(10)) * 20;
- };
- var effects = {};
- function getDestinationForTag(tag)
- {
- tag = tag.toLowerCase();
- if (effects.hasOwnProperty(tag))
- {
- if (effects[tag].length)
- return effects[tag][0].getInputNode();
- }
- return context["destination"];
- };
- function createGain()
- {
- if (context["createGain"])
- return context["createGain"]();
- else
- return context["createGainNode"]();
- };
- function createDelay(d)
- {
- if (context["createDelay"])
- return context["createDelay"](d);
- else
- return context["createDelayNode"](d);
- };
- function startSource(s)
- {
- if (s["start"])
- s["start"](0);
- else
- s["noteOn"](0);
- };
- function startSourceAt(s, x, d)
- {
- if (s["start"])
- s["start"](0, x);
- else
- s["noteGrainOn"](0, x, d - x);
- };
- function stopSource(s)
- {
- try {
- if (s["stop"])
- s["stop"](0);
- else
- s["noteOff"](0);
- }
- catch (e) {}
- };
- function setAudioParam(ap, value, ramp, time)
- {
- if (!ap)
- return; // iOS is missing some parameters
- ap["cancelScheduledValues"](0);
- if (time === 0)
- {
- ap["value"] = value;
- return;
- }
- var curTime = context["currentTime"];
- time += curTime;
- switch (ramp) {
- case 0: // step
- ap["setValueAtTime"](value, time);
- break;
- case 1: // linear
- ap["setValueAtTime"](ap["value"], curTime); // to set what to ramp from
- ap["linearRampToValueAtTime"](value, time);
- break;
- case 2: // exponential
- ap["setValueAtTime"](ap["value"], curTime); // to set what to ramp from
- ap["exponentialRampToValueAtTime"](value, time);
- break;
- }
- };
- var filterTypes = ["lowpass", "highpass", "bandpass", "lowshelf", "highshelf", "peaking", "notch", "allpass"];
- function FilterEffect(type, freq, detune, q, gain, mix)
- {
- this.type = "filter";
- this.params = [type, freq, detune, q, gain, mix];
- this.inputNode = createGain();
- this.wetNode = createGain();
- this.wetNode["gain"]["value"] = mix;
- this.dryNode = createGain();
- this.dryNode["gain"]["value"] = 1 - mix;
- this.filterNode = context["createBiquadFilter"]();
- if (typeof this.filterNode["type"] === "number")
- this.filterNode["type"] = type;
- else
- this.filterNode["type"] = filterTypes[type];
- this.filterNode["frequency"]["value"] = freq;
- if (this.filterNode["detune"]) // iOS 6 doesn't have detune yet
- this.filterNode["detune"]["value"] = detune;
- this.filterNode["Q"]["value"] = q;
- this.filterNode["gain"]["value"] = gain;
- this.inputNode["connect"](this.filterNode);
- this.inputNode["connect"](this.dryNode);
- this.filterNode["connect"](this.wetNode);
- };
- FilterEffect.prototype.connectTo = function (node)
- {
- this.wetNode["disconnect"]();
- this.wetNode["connect"](node);
- this.dryNode["disconnect"]();
- this.dryNode["connect"](node);
- };
- FilterEffect.prototype.remove = function ()
- {
- this.inputNode["disconnect"]();
- this.filterNode["disconnect"]();
- this.wetNode["disconnect"]();
- this.dryNode["disconnect"]();
- };
- FilterEffect.prototype.getInputNode = function ()
- {
- return this.inputNode;
- };
- FilterEffect.prototype.setParam = function(param, value, ramp, time)
- {
- switch (param) {
- case 0: // mix
- value = value / 100;
- if (value < 0) value = 0;
- if (value > 1) value = 1;
- this.params[5] = value;
- setAudioParam(this.wetNode["gain"], value, ramp, time);
- setAudioParam(this.dryNode["gain"], 1 - value, ramp, time);
- break;
- case 1: // filter frequency
- this.params[1] = value;
- setAudioParam(this.filterNode["frequency"], value, ramp, time);
- break;
- case 2: // filter detune
- this.params[2] = value;
- setAudioParam(this.filterNode["detune"], value, ramp, time);
- break;
- case 3: // filter Q
- this.params[3] = value;
- setAudioParam(this.filterNode["Q"], value, ramp, time);
- break;
- case 4: // filter/delay gain (note value is in dB here)
- this.params[4] = value;
- setAudioParam(this.filterNode["gain"], value, ramp, time);
- break;
- }
- };
- function DelayEffect(delayTime, delayGain, mix)
- {
- this.type = "delay";
- this.params = [delayTime, delayGain, mix];
- this.inputNode = createGain();
- this.wetNode = createGain();
- this.wetNode["gain"]["value"] = mix;
- this.dryNode = createGain();
- this.dryNode["gain"]["value"] = 1 - mix;
- this.mainNode = createGain();
- this.delayNode = createDelay(delayTime);
- this.delayNode["delayTime"]["value"] = delayTime;
- this.delayGainNode = createGain();
- this.delayGainNode["gain"]["value"] = delayGain;
- this.inputNode["connect"](this.mainNode);
- this.inputNode["connect"](this.dryNode);
- this.mainNode["connect"](this.wetNode);
- this.mainNode["connect"](this.delayNode);
- this.delayNode["connect"](this.delayGainNode);
- this.delayGainNode["connect"](this.mainNode);
- };
- DelayEffect.prototype.connectTo = function (node)
- {
- this.wetNode["disconnect"]();
- this.wetNode["connect"](node);
- this.dryNode["disconnect"]();
- this.dryNode["connect"](node);
- };
- DelayEffect.prototype.remove = function ()
- {
- this.inputNode["disconnect"]();
- this.mainNode["disconnect"]();
- this.delayNode["disconnect"]();
- this.delayGainNode["disconnect"]();
- this.wetNode["disconnect"]();
- this.dryNode["disconnect"]();
- };
- DelayEffect.prototype.getInputNode = function ()
- {
- return this.inputNode;
- };
- DelayEffect.prototype.setParam = function(param, value, ramp, time)
- {
- switch (param) {
- case 0: // mix
- value = value / 100;
- if (value < 0) value = 0;
- if (value > 1) value = 1;
- this.params[2] = value;
- setAudioParam(this.wetNode["gain"], value, ramp, time);
- setAudioParam(this.dryNode["gain"], 1 - value, ramp, time);
- break;
- case 4: // filter/delay gain (note value is passed in dB but needs to be linear here)
- this.params[1] = dbToLinear(value);
- setAudioParam(this.delayGainNode["gain"], dbToLinear(value), ramp, time);
- break;
- case 5: // delay time
- this.params[0] = value;
- setAudioParam(this.delayNode["delayTime"], value, ramp, time);
- break;
- }
- };
- function ConvolveEffect(buffer, normalize, mix, src)
- {
- this.type = "convolve";
- this.params = [normalize, mix, src];
- this.inputNode = createGain();
- this.wetNode = createGain();
- this.wetNode["gain"]["value"] = mix;
- this.dryNode = createGain();
- this.dryNode["gain"]["value"] = 1 - mix;
- this.convolveNode = context["createConvolver"]();
- if (buffer)
- {
- this.convolveNode["normalize"] = normalize;
- this.convolveNode["buffer"] = buffer;
- }
- this.inputNode["connect"](this.convolveNode);
- this.inputNode["connect"](this.dryNode);
- this.convolveNode["connect"](this.wetNode);
- };
- ConvolveEffect.prototype.connectTo = function (node)
- {
- this.wetNode["disconnect"]();
- this.wetNode["connect"](node);
- this.dryNode["disconnect"]();
- this.dryNode["connect"](node);
- };
- ConvolveEffect.prototype.remove = function ()
- {
- this.inputNode["disconnect"]();
- this.convolveNode["disconnect"]();
- this.wetNode["disconnect"]();
- this.dryNode["disconnect"]();
- };
- ConvolveEffect.prototype.getInputNode = function ()
- {
- return this.inputNode;
- };
- ConvolveEffect.prototype.setParam = function(param, value, ramp, time)
- {
- switch (param) {
- case 0: // mix
- value = value / 100;
- if (value < 0) value = 0;
- if (value > 1) value = 1;
- this.params[1] = value;
- setAudioParam(this.wetNode["gain"], value, ramp, time);
- setAudioParam(this.dryNode["gain"], 1 - value, ramp, time);
- break;
- }
- };
- function FlangerEffect(delay, modulation, freq, feedback, mix)
- {
- this.type = "flanger";
- this.params = [delay, modulation, freq, feedback, mix];
- this.inputNode = createGain();
- this.dryNode = createGain();
- this.dryNode["gain"]["value"] = 1 - (mix / 2);
- this.wetNode = createGain();
- this.wetNode["gain"]["value"] = mix / 2;
- this.feedbackNode = createGain();
- this.feedbackNode["gain"]["value"] = feedback;
- this.delayNode = createDelay(delay + modulation);
- this.delayNode["delayTime"]["value"] = delay;
- this.oscNode = context["createOscillator"]();
- this.oscNode["frequency"]["value"] = freq;
- this.oscGainNode = createGain();
- this.oscGainNode["gain"]["value"] = modulation;
- this.inputNode["connect"](this.delayNode);
- this.inputNode["connect"](this.dryNode);
- this.delayNode["connect"](this.wetNode);
- this.delayNode["connect"](this.feedbackNode);
- this.feedbackNode["connect"](this.delayNode);
- this.oscNode["connect"](this.oscGainNode);
- this.oscGainNode["connect"](this.delayNode["delayTime"]);
- startSource(this.oscNode);
- };
- FlangerEffect.prototype.connectTo = function (node)
- {
- this.dryNode["disconnect"]();
- this.dryNode["connect"](node);
- this.wetNode["disconnect"]();
- this.wetNode["connect"](node);
- };
- FlangerEffect.prototype.remove = function ()
- {
- this.inputNode["disconnect"]();
- this.delayNode["disconnect"]();
- this.oscNode["disconnect"]();
- this.oscGainNode["disconnect"]();
- this.dryNode["disconnect"]();
- this.wetNode["disconnect"]();
- this.feedbackNode["disconnect"]();
- };
- FlangerEffect.prototype.getInputNode = function ()
- {
- return this.inputNode;
- };
- FlangerEffect.prototype.setParam = function(param, value, ramp, time)
- {
- switch (param) {
- case 0: // mix
- value = value / 100;
- if (value < 0) value = 0;
- if (value > 1) value = 1;
- this.params[4] = value;
- setAudioParam(this.wetNode["gain"], value / 2, ramp, time);
- setAudioParam(this.dryNode["gain"], 1 - (value / 2), ramp, time);
- break;
- case 6: // modulation
- this.params[1] = value / 1000;
- setAudioParam(this.oscGainNode["gain"], value / 1000, ramp, time);
- break;
- case 7: // modulation frequency
- this.params[2] = value;
- setAudioParam(this.oscNode["frequency"], value, ramp, time);
- break;
- case 8: // feedback
- this.params[3] = value / 100;
- setAudioParam(this.feedbackNode["gain"], value / 100, ramp, time);
- break;
- }
- };
- function PhaserEffect(freq, detune, q, modulation, modfreq, mix)
- {
- this.type = "phaser";
- this.params = [freq, detune, q, modulation, modfreq, mix];
- this.inputNode = createGain();
- this.dryNode = createGain();
- this.dryNode["gain"]["value"] = 1 - (mix / 2);
- this.wetNode = createGain();
- this.wetNode["gain"]["value"] = mix / 2;
- this.filterNode = context["createBiquadFilter"]();
- if (typeof this.filterNode["type"] === "number")
- this.filterNode["type"] = 7; // all-pass
- else
- this.filterNode["type"] = "allpass";
- this.filterNode["frequency"]["value"] = freq;
- if (this.filterNode["detune"]) // iOS 6 doesn't have detune yet
- this.filterNode["detune"]["value"] = detune;
- this.filterNode["Q"]["value"] = q;
- this.oscNode = context["createOscillator"]();
- this.oscNode["frequency"]["value"] = modfreq;
- this.oscGainNode = createGain();
- this.oscGainNode["gain"]["value"] = modulation;
- this.inputNode["connect"](this.filterNode);
- this.inputNode["connect"](this.dryNode);
- this.filterNode["connect"](this.wetNode);
- this.oscNode["connect"](this.oscGainNode);
- this.oscGainNode["connect"](this.filterNode["frequency"]);
- startSource(this.oscNode);
- };
- PhaserEffect.prototype.connectTo = function (node)
- {
- this.dryNode["disconnect"]();
- this.dryNode["connect"](node);
- this.wetNode["disconnect"]();
- this.wetNode["connect"](node);
- };
- PhaserEffect.prototype.remove = function ()
- {
- this.inputNode["disconnect"]();
- this.filterNode["disconnect"]();
- this.oscNode["disconnect"]();
- this.oscGainNode["disconnect"]();
- this.dryNode["disconnect"]();
- this.wetNode["disconnect"]();
- };
- PhaserEffect.prototype.getInputNode = function ()
- {
- return this.inputNode;
- };
- PhaserEffect.prototype.setParam = function(param, value, ramp, time)
- {
- switch (param) {
- case 0: // mix
- value = value / 100;
- if (value < 0) value = 0;
- if (value > 1) value = 1;
- this.params[5] = value;
- setAudioParam(this.wetNode["gain"], value / 2, ramp, time);
- setAudioParam(this.dryNode["gain"], 1 - (value / 2), ramp, time);
- break;
- case 1: // filter frequency
- this.params[0] = value;
- setAudioParam(this.filterNode["frequency"], value, ramp, time);
- break;
- case 2: // filter detune
- this.params[1] = value;
- setAudioParam(this.filterNode["detune"], value, ramp, time);
- break;
- case 3: // filter Q
- this.params[2] = value;
- setAudioParam(this.filterNode["Q"], value, ramp, time);
- break;
- case 6: // modulation
- this.params[3] = value;
- setAudioParam(this.oscGainNode["gain"], value, ramp, time);
- break;
- case 7: // modulation frequency
- this.params[4] = value;
- setAudioParam(this.oscNode["frequency"], value, ramp, time);
- break;
- }
- };
- function GainEffect(g)
- {
- this.type = "gain";
- this.params = [g];
- this.node = createGain();
- this.node["gain"]["value"] = g;
- };
- GainEffect.prototype.connectTo = function (node_)
- {
- this.node["disconnect"]();
- this.node["connect"](node_);
- };
- GainEffect.prototype.remove = function ()
- {
- this.node["disconnect"]();
- };
- GainEffect.prototype.getInputNode = function ()
- {
- return this.node;
- };
- GainEffect.prototype.setParam = function(param, value, ramp, time)
- {
- switch (param) {
- case 4: // gain
- this.params[0] = dbToLinear(value);
- setAudioParam(this.node["gain"], dbToLinear(value), ramp, time);
- break;
- }
- };
- function TremoloEffect(freq, mix)
- {
- this.type = "tremolo";
- this.params = [freq, mix];
- this.node = createGain();
- this.node["gain"]["value"] = 1 - (mix / 2);
- this.oscNode = context["createOscillator"]();
- this.oscNode["frequency"]["value"] = freq;
- this.oscGainNode = createGain();
- this.oscGainNode["gain"]["value"] = mix / 2;
- this.oscNode["connect"](this.oscGainNode);
- this.oscGainNode["connect"](this.node["gain"]);
- startSource(this.oscNode);
- };
- TremoloEffect.prototype.connectTo = function (node_)
- {
- this.node["disconnect"]();
- this.node["connect"](node_);
- };
- TremoloEffect.prototype.remove = function ()
- {
- this.oscNode["disconnect"]();
- this.oscGainNode["disconnect"]();
- this.node["disconnect"]();
- };
- TremoloEffect.prototype.getInputNode = function ()
- {
- return this.node;
- };
- TremoloEffect.prototype.setParam = function(param, value, ramp, time)
- {
- switch (param) {
- case 0: // mix
- value = value / 100;
- if (value < 0) value = 0;
- if (value > 1) value = 1;
- this.params[1] = value;
- setAudioParam(this.node["gain"]["value"], 1 - (value / 2), ramp, time);
- setAudioParam(this.oscGainNode["gain"]["value"], value / 2, ramp, time);
- break;
- case 7: // modulation frequency
- this.params[0] = value;
- setAudioParam(this.oscNode["frequency"], value, ramp, time);
- break;
- }
- };
- function RingModulatorEffect(freq, mix)
- {
- this.type = "ringmod";
- this.params = [freq, mix];
- this.inputNode = createGain();
- this.wetNode = createGain();
- this.wetNode["gain"]["value"] = mix;
- this.dryNode = createGain();
- this.dryNode["gain"]["value"] = 1 - mix;
- this.ringNode = createGain();
- this.ringNode["gain"]["value"] = 0;
- this.oscNode = context["createOscillator"]();
- this.oscNode["frequency"]["value"] = freq;
- this.oscNode["connect"](this.ringNode["gain"]);
- startSource(this.oscNode);
- this.inputNode["connect"](this.ringNode);
- this.inputNode["connect"](this.dryNode);
- this.ringNode["connect"](this.wetNode);
- };
- RingModulatorEffect.prototype.connectTo = function (node_)
- {
- this.wetNode["disconnect"]();
- this.wetNode["connect"](node_);
- this.dryNode["disconnect"]();
- this.dryNode["connect"](node_);
- };
- RingModulatorEffect.prototype.remove = function ()
- {
- this.oscNode["disconnect"]();
- this.ringNode["disconnect"]();
- this.inputNode["disconnect"]();
- this.wetNode["disconnect"]();
- this.dryNode["disconnect"]();
- };
- RingModulatorEffect.prototype.getInputNode = function ()
- {
- return this.inputNode;
- };
- RingModulatorEffect.prototype.setParam = function(param, value, ramp, time)
- {
- switch (param) {
- case 0: // mix
- value = value / 100;
- if (value < 0) value = 0;
- if (value > 1) value = 1;
- this.params[1] = value;
- setAudioParam(this.wetNode["gain"], value, ramp, time);
- setAudioParam(this.dryNode["gain"], 1 - value, ramp, time);
- break;
- case 7: // modulation frequency
- this.params[0] = value;
- setAudioParam(this.oscNode["frequency"], value, ramp, time);
- break;
- }
- };
- function DistortionEffect(threshold, headroom, drive, makeupgain, mix)
- {
- this.type = "distortion";
- this.params = [threshold, headroom, drive, makeupgain, mix];
- this.inputNode = createGain();
- this.preGain = createGain();
- this.postGain = createGain();
- this.setDrive(drive, dbToLinear_nocap(makeupgain));
- this.wetNode = createGain();
- this.wetNode["gain"]["value"] = mix;
- this.dryNode = createGain();
- this.dryNode["gain"]["value"] = 1 - mix;
- this.waveShaper = context["createWaveShaper"]();
- this.curve = new Float32Array(65536);
- this.generateColortouchCurve(threshold, headroom);
- this.waveShaper.curve = this.curve;
- this.inputNode["connect"](this.preGain);
- this.inputNode["connect"](this.dryNode);
- this.preGain["connect"](this.waveShaper);
- this.waveShaper["connect"](this.postGain);
- this.postGain["connect"](this.wetNode);
- };
- DistortionEffect.prototype.setDrive = function (drive, makeupgain)
- {
- if (drive < 0.01)
- drive = 0.01;
- this.preGain["gain"]["value"] = drive;
- this.postGain["gain"]["value"] = Math.pow(1 / drive, 0.6) * makeupgain;
- };
- function e4(x, k)
- {
- return 1.0 - Math.exp(-k * x);
- }
- DistortionEffect.prototype.shape = function (x, linearThreshold, linearHeadroom)
- {
- var maximum = 1.05 * linearHeadroom * linearThreshold;
- var kk = (maximum - linearThreshold);
- var sign = x < 0 ? -1 : +1;
- var absx = x < 0 ? -x : x;
- var shapedInput = absx < linearThreshold ? absx : linearThreshold + kk * e4(absx - linearThreshold, 1.0 / kk);
- shapedInput *= sign;
- return shapedInput;
- };
- DistortionEffect.prototype.generateColortouchCurve = function (threshold, headroom)
- {
- var linearThreshold = dbToLinear_nocap(threshold);
- var linearHeadroom = dbToLinear_nocap(headroom);
- var n = 65536;
- var n2 = n / 2;
- var x = 0;
- for (var i = 0; i < n2; ++i) {
- x = i / n2;
- x = this.shape(x, linearThreshold, linearHeadroom);
- this.curve[n2 + i] = x;
- this.curve[n2 - i - 1] = -x;
- }
- };
- DistortionEffect.prototype.connectTo = function (node)
- {
- this.wetNode["disconnect"]();
- this.wetNode["connect"](node);
- this.dryNode["disconnect"]();
- this.dryNode["connect"](node);
- };
- DistortionEffect.prototype.remove = function ()
- {
- this.inputNode["disconnect"]();
- this.preGain["disconnect"]();
- this.waveShaper["disconnect"]();
- this.postGain["disconnect"]();
- this.wetNode["disconnect"]();
- this.dryNode["disconnect"]();
- };
- DistortionEffect.prototype.getInputNode = function ()
- {
- return this.inputNode;
- };
- DistortionEffect.prototype.setParam = function(param, value, ramp, time)
- {
- switch (param) {
- case 0: // mix
- value = value / 100;
- if (value < 0) value = 0;
- if (value > 1) value = 1;
- this.params[4] = value;
- setAudioParam(this.wetNode["gain"], value, ramp, time);
- setAudioParam(this.dryNode["gain"], 1 - value, ramp, time);
- break;
- }
- };
- function CompressorEffect(threshold, knee, ratio, attack, release)
- {
- this.type = "compressor";
- this.params = [threshold, knee, ratio, attack, release];
- this.node = context["createDynamicsCompressor"]();
- try {
- this.node["threshold"]["value"] = threshold;
- this.node["knee"]["value"] = knee;
- this.node["ratio"]["value"] = ratio;
- this.node["attack"]["value"] = attack;
- this.node["release"]["value"] = release;
- }
- catch (e) {}
- };
- CompressorEffect.prototype.connectTo = function (node_)
- {
- this.node["disconnect"]();
- this.node["connect"](node_);
- };
- CompressorEffect.prototype.remove = function ()
- {
- this.node["disconnect"]();
- };
- CompressorEffect.prototype.getInputNode = function ()
- {
- return this.node;
- };
- CompressorEffect.prototype.setParam = function(param, value, ramp, time)
- {
- };
- function AnalyserEffect(fftSize, smoothing)
- {
- this.type = "analyser";
- this.params = [fftSize, smoothing];
- this.node = context["createAnalyser"]();
- this.node["fftSize"] = fftSize;
- this.node["smoothingTimeConstant"] = smoothing;
- this.freqBins = new Float32Array(this.node["frequencyBinCount"]);
- this.signal = new Uint8Array(fftSize);
- this.peak = 0;
- this.rms = 0;
- };
- AnalyserEffect.prototype.tick = function ()
- {
- this.node["getFloatFrequencyData"](this.freqBins);
- this.node["getByteTimeDomainData"](this.signal);
- var fftSize = this.node["fftSize"];
- var i = 0;
- this.peak = 0;
- var rmsSquaredSum = 0;
- var s = 0;
- for ( ; i < fftSize; i++)
- {
- s = (this.signal[i] - 128) / 128;
- if (s < 0)
- s = -s;
- if (this.peak < s)
- this.peak = s;
- rmsSquaredSum += s * s;
- }
- this.peak = linearToDb(this.peak);
- this.rms = linearToDb(Math.sqrt(rmsSquaredSum / fftSize));
- };
- AnalyserEffect.prototype.connectTo = function (node_)
- {
- this.node["disconnect"]();
- this.node["connect"](node_);
- };
- AnalyserEffect.prototype.remove = function ()
- {
- this.node["disconnect"]();
- };
- AnalyserEffect.prototype.getInputNode = function ()
- {
- return this.node;
- };
- AnalyserEffect.prototype.setParam = function(param, value, ramp, time)
- {
- };
- var OT_POS_SAMPLES = 4;
- function ObjectTracker()
- {
- this.obj = null;
- this.loadUid = 0;
- this.speeds = [];
- this.lastX = 0;
- this.lastY = 0;
- this.moveAngle = 0;
- };
- ObjectTracker.prototype.setObject = function (obj_)
- {
- this.obj = obj_;
- if (this.obj)
- {
- this.lastX = this.obj.x;
- this.lastY = this.obj.y;
- }
- cr.clearArray(this.speeds);
- };
- ObjectTracker.prototype.hasObject = function ()
- {
- return !!this.obj;
- };
- ObjectTracker.prototype.tick = function (dt)
- {
- if (!this.obj || dt === 0)
- return;
- this.moveAngle = cr.angleTo(this.lastX, this.lastY, this.obj.x, this.obj.y);
- var s = cr.distanceTo(this.lastX, this.lastY, this.obj.x, this.obj.y) / dt;
- if (this.speeds.length < OT_POS_SAMPLES)
- this.speeds.push(s);
- else
- {
- this.speeds.shift();
- this.speeds.push(s);
- }
- this.lastX = this.obj.x;
- this.lastY = this.obj.y;
- };
- ObjectTracker.prototype.getSpeed = function ()
- {
- if (!this.speeds.length)
- return 0;
- var i, len, sum = 0;
- for (i = 0, len = this.speeds.length; i < len; i++)
- {
- sum += this.speeds[i];
- }
- return sum / this.speeds.length;
- };
- ObjectTracker.prototype.getVelocityX = function ()
- {
- return Math.cos(this.moveAngle) * this.getSpeed();
- };
- ObjectTracker.prototype.getVelocityY = function ()
- {
- return Math.sin(this.moveAngle) * this.getSpeed();
- };
- var iOShadtouch = false; // has had touch input on iOS to work around web audio API muting
- function C2AudioBuffer(src_, is_music)
- {
- this.src = src_;
- this.myapi = api;
- this.is_music = is_music;
- this.added_end_listener = false;
- var self = this;
- this.outNode = null;
- this.mediaSourceNode = null;
- this.panWhenReady = []; // for web audio API positioned sounds
- this.seekWhenReady = 0;
- this.pauseWhenReady = false;
- this.supportWebAudioAPI = false;
- this.failedToLoad = false;
- this.wasEverReady = false; // if a buffer is ever marked as ready, it's permanently considered ready after then.
- if (api === API_WEBAUDIO && is_music)
- {
- this.myapi = API_HTML5;
- this.outNode = createGain();
- }
- this.bufferObject = null; // actual audio object
- this.audioData = null; // web audio api: ajax request result (compressed audio that needs decoding)
- var request;
- switch (this.myapi) {
- case API_HTML5:
- this.bufferObject = new Audio();
- this.bufferObject.crossOrigin = "anonymous";
- this.bufferObject.addEventListener("canplaythrough", function () {
- self.wasEverReady = true; // update loaded state so preload is considered complete
- });
- if (api === API_WEBAUDIO && context["createMediaElementSource"] && !/wiiu/i.test(navigator.userAgent))
- {
- this.supportWebAudioAPI = true; // can be routed through web audio api
- this.bufferObject.addEventListener("canplay", function ()
- {
- if (!self.mediaSourceNode) // protect against this event firing twice
- {
- self.mediaSourceNode = context["createMediaElementSource"](self.bufferObject);
- self.mediaSourceNode["connect"](self.outNode);
- }
- });
- }
- this.bufferObject.autoplay = false; // this is only a source buffer, not an instance
- this.bufferObject.preload = "auto";
- this.bufferObject.src = src_;
- break;
- case API_WEBAUDIO:
- request = new XMLHttpRequest();
- request.open("GET", src_, true);
- request.responseType = "arraybuffer";
- request.onload = function () {
- self.audioData = request.response;
- self.decodeAudioBuffer();
- };
- request.onerror = function () {
- self.failedToLoad = true;
- };
- request.send();
- break;
- case API_CORDOVA:
- this.bufferObject = true;
- break;
- case API_APPMOBI:
- this.bufferObject = true;
- break;
- }
- };
- C2AudioBuffer.prototype.decodeAudioBuffer = function ()
- {
- if (this.bufferObject || !this.audioData)
- return; // audio already decoded or AJAX request not yet complete
- var self = this;
- if (context["decodeAudioData"])
- {
- context["decodeAudioData"](this.audioData, function (buffer) {
- self.bufferObject = buffer;
- self.audioData = null; // clear AJAX response to allow GC and save memory, only need the bufferObject now
- var p, i, len, a;
- if (!cr.is_undefined(self.playTagWhenReady) && !silent)
- {
- if (self.panWhenReady.length)
- {
- for (i = 0, len = self.panWhenReady.length; i < len; i++)
- {
- p = self.panWhenReady[i];
- a = new C2AudioInstance(self, p.thistag);
- a.setPannerEnabled(true);
- if (typeof p.objUid !== "undefined")
- {
- p.obj = audRuntime.getObjectByUID(p.objUid);
- if (!p.obj)
- continue;
- }
- if (p.obj)
- {
- var px = cr.rotatePtAround(p.obj.x, p.obj.y, -p.obj.layer.getAngle(), listenerX, listenerY, true);
- var py = cr.rotatePtAround(p.obj.x, p.obj.y, -p.obj.layer.getAngle(), listenerX, listenerY, false);
- a.setPan(px, py, cr.to_degrees(p.obj.angle - p.obj.layer.getAngle()), p.ia, p.oa, p.og);
- a.setObject(p.obj);
- }
- else
- {
- a.setPan(p.x, p.y, p.a, p.ia, p.oa, p.og);
- }
- a.play(self.loopWhenReady, self.volumeWhenReady, self.seekWhenReady);
- if (self.pauseWhenReady)
- a.pause();
- audioInstances.push(a);
- }
- cr.clearArray(self.panWhenReady);
- }
- else
- {
- a = new C2AudioInstance(self, self.playTagWhenReady || ""); // sometimes playTagWhenReady is not set - TODO: why?
- a.play(self.loopWhenReady, self.volumeWhenReady, self.seekWhenReady);
- if (self.pauseWhenReady)
- a.pause();
- audioInstances.push(a);
- }
- }
- else if (!cr.is_undefined(self.convolveWhenReady))
- {
- var convolveNode = self.convolveWhenReady.convolveNode;
- convolveNode["normalize"] = self.normalizeWhenReady;
- convolveNode["buffer"] = buffer;
- }
- }, function (e) {
- self.failedToLoad = true;
- });
- }
- else
- {
- this.bufferObject = context["createBuffer"](this.audioData, false);
- this.audioData = null; // clear AJAX response to allow GC and save memory, only need the bufferObject now
- if (!cr.is_undefined(this.playTagWhenReady) && !silent)
- {
- var a = new C2AudioInstance(this, this.playTagWhenReady);
- a.play(this.loopWhenReady, this.volumeWhenReady, this.seekWhenReady);
- if (this.pauseWhenReady)
- a.pause();
- audioInstances.push(a);
- }
- else if (!cr.is_undefined(this.convolveWhenReady))
- {
- var convolveNode = this.convolveWhenReady.convolveNode;
- convolveNode["normalize"] = this.normalizeWhenReady;
- convolveNode["buffer"] = this.bufferObject;
- }
- }
- };
- C2AudioBuffer.prototype.isLoaded = function ()
- {
- switch (this.myapi) {
- case API_HTML5:
- var ret = this.bufferObject["readyState"] >= 4; // HAVE_ENOUGH_DATA
- if (ret)
- this.wasEverReady = true;
- return ret || this.wasEverReady;
- case API_WEBAUDIO:
- return !!this.audioData || !!this.bufferObject;
- case API_CORDOVA:
- return true;
- case API_APPMOBI:
- return true;
- }
- return false;
- };
- C2AudioBuffer.prototype.isLoadedAndDecoded = function ()
- {
- switch (this.myapi) {
- case API_HTML5:
- return this.isLoaded(); // no distinction between loaded and decoded in HTML5 audio, just rely on ready state
- case API_WEBAUDIO:
- return !!this.bufferObject;
- case API_CORDOVA:
- return true;
- case API_APPMOBI:
- return true;
- }
- return false;
- };
- C2AudioBuffer.prototype.hasFailedToLoad = function ()
- {
- switch (this.myapi) {
- case API_HTML5:
- return !!this.bufferObject["error"];
- case API_WEBAUDIO:
- return this.failedToLoad;
- }
- return false;
- };
- function C2AudioInstance(buffer_, tag_)
- {
- var self = this;
- this.tag = tag_;
- this.fresh = true;
- this.stopped = true;
- this.src = buffer_.src;
- this.buffer = buffer_;
- this.myapi = api;
- this.is_music = buffer_.is_music;
- this.playbackRate = 1;
- this.hasPlaybackEnded = true; // ended flag
- this.resume_me = false; // make sure resumes when leaving suspend
- this.is_paused = false;
- this.resume_position = 0; // for web audio api to resume from correct playback position
- this.looping = false;
- this.is_muted = false;
- this.is_silent = false;
- this.volume = 1;
- this.onended_handler = function ()
- {
- if (self.is_paused)
- return;
- if (this !== self.active_buffer)
- return;
- self.hasPlaybackEnded = true;
- self.stopped = true;
- audTag = self.tag;
- audRuntime.trigger(cr.plugins_.Audio.prototype.cnds.OnEnded, audInst);
- };
- this.active_buffer = null;
- this.isTimescaled = ((timescale_mode === 1 && !this.is_music) || timescale_mode === 2);
- this.mutevol = 1;
- this.startTime = (this.isTimescaled ? audRuntime.kahanTime.sum : audRuntime.wallTime.sum);
- this.gainNode = null;
- this.pannerNode = null;
- this.pannerEnabled = false;
- this.objectTracker = null;
- this.panX = 0;
- this.panY = 0;
- this.panAngle = 0;
- this.panConeInner = 0;
- this.panConeOuter = 0;
- this.panConeOuterGain = 0;
- this.instanceObject = null;
- var add_end_listener = false;
- if (this.myapi === API_WEBAUDIO && this.buffer.myapi === API_HTML5 && !this.buffer.supportWebAudioAPI)
- this.myapi = API_HTML5;
- switch (this.myapi) {
- case API_HTML5:
- if (this.is_music)
- {
- this.instanceObject = buffer_.bufferObject;
- add_end_listener = !buffer_.added_end_listener;
- buffer_.added_end_listener = true;
- }
- else
- {
- this.instanceObject = new Audio();
- this.instanceObject.crossOrigin = "anonymous";
- this.instanceObject.autoplay = false;
- this.instanceObject.src = buffer_.bufferObject.src;
- add_end_listener = true;
- }
- if (add_end_listener)
- {
- this.instanceObject.addEventListener('ended', function () {
- audTag = self.tag;
- self.stopped = true;
- audRuntime.trigger(cr.plugins_.Audio.prototype.cnds.OnEnded, audInst);
- });
- }
- break;
- case API_WEBAUDIO:
- this.gainNode = createGain();
- this.gainNode["connect"](getDestinationForTag(tag_));
- if (this.buffer.myapi === API_WEBAUDIO)
- {
- if (buffer_.bufferObject)
- {
- this.instanceObject = context["createBufferSource"]();
- this.instanceObject["buffer"] = buffer_.bufferObject;
- this.instanceObject["connect"](this.gainNode);
- }
- }
- else
- {
- this.instanceObject = this.buffer.bufferObject; // reference the audio element
- this.buffer.outNode["connect"](this.gainNode);
- if (!this.buffer.added_end_listener)
- {
- this.buffer.added_end_listener = true;
- this.buffer.bufferObject.addEventListener('ended', function () {
- audTag = self.tag;
- self.stopped = true;
- audRuntime.trigger(cr.plugins_.Audio.prototype.cnds.OnEnded, audInst);
- });
- }
- }
- break;
- case API_CORDOVA:
- this.instanceObject = new window["Media"](appPath + this.src, null, null, function (status) {
- if (status === window["Media"]["MEDIA_STOPPED"])
- {
- self.hasPlaybackEnded = true;
- self.stopped = true;
- audTag = self.tag;
- audRuntime.trigger(cr.plugins_.Audio.prototype.cnds.OnEnded, audInst);
- }
- });
- break;
- case API_APPMOBI:
- this.instanceObject = true;
- break;
- }
- };
- C2AudioInstance.prototype.hasEnded = function ()
- {
- var time;
- switch (this.myapi) {
- case API_HTML5:
- return this.instanceObject.ended;
- case API_WEBAUDIO:
- if (this.buffer.myapi === API_WEBAUDIO)
- {
- if (!this.fresh && !this.stopped && this.instanceObject["loop"])
- return false;
- if (this.is_paused)
- return false;
- return this.hasPlaybackEnded;
- }
- else
- return this.instanceObject.ended;
- case API_CORDOVA:
- return this.hasPlaybackEnded;
- case API_APPMOBI:
- true; // recycling an AppMobi sound does not matter because it will just do another throwaway playSound
- }
- return true;
- };
- C2AudioInstance.prototype.canBeRecycled = function ()
- {
- if (this.fresh || this.stopped)
- return true; // not yet used or is not playing
- return this.hasEnded();
- };
- C2AudioInstance.prototype.setPannerEnabled = function (enable_)
- {
- if (api !== API_WEBAUDIO)
- return;
- if (!this.pannerEnabled && enable_)
- {
- if (!this.gainNode)
- return;
- if (!this.pannerNode)
- {
- this.pannerNode = context["createPanner"]();
- if (typeof this.pannerNode["panningModel"] === "number")
- this.pannerNode["panningModel"] = panningModel;
- else
- this.pannerNode["panningModel"] = ["equalpower", "HRTF", "soundfield"][panningModel];
- if (typeof this.pannerNode["distanceModel"] === "number")
- this.pannerNode["distanceModel"] = distanceModel;
- else
- this.pannerNode["distanceModel"] = ["linear", "inverse", "exponential"][distanceModel];
- this.pannerNode["refDistance"] = refDistance;
- this.pannerNode["maxDistance"] = maxDistance;
- this.pannerNode["rolloffFactor"] = rolloffFactor;
- }
- this.gainNode["disconnect"]();
- this.gainNode["connect"](this.pannerNode);
- this.pannerNode["connect"](getDestinationForTag(this.tag));
- this.pannerEnabled = true;
- }
- else if (this.pannerEnabled && !enable_)
- {
- if (!this.gainNode)
- return;
- this.pannerNode["disconnect"]();
- this.gainNode["disconnect"]();
- this.gainNode["connect"](getDestinationForTag(this.tag));
- this.pannerEnabled = false;
- }
- };
- C2AudioInstance.prototype.setPan = function (x, y, angle, innerangle, outerangle, outergain)
- {
- if (!this.pannerEnabled || api !== API_WEBAUDIO)
- return;
- this.pannerNode["setPosition"](x, y, 0);
- this.pannerNode["setOrientation"](Math.cos(cr.to_radians(angle)), Math.sin(cr.to_radians(angle)), 0);
- this.pannerNode["coneInnerAngle"] = innerangle;
- this.pannerNode["coneOuterAngle"] = outerangle;
- this.pannerNode["coneOuterGain"] = outergain;
- this.panX = x;
- this.panY = y;
- this.panAngle = angle;
- this.panConeInner = innerangle;
- this.panConeOuter = outerangle;
- this.panConeOuterGain = outergain;
- };
- C2AudioInstance.prototype.setObject = function (o)
- {
- if (!this.pannerEnabled || api !== API_WEBAUDIO)
- return;
- if (!this.objectTracker)
- this.objectTracker = new ObjectTracker();
- this.objectTracker.setObject(o);
- };
- C2AudioInstance.prototype.tick = function (dt)
- {
- if (!this.pannerEnabled || api !== API_WEBAUDIO || !this.objectTracker || !this.objectTracker.hasObject() || !this.isPlaying())
- {
- return;
- }
- this.objectTracker.tick(dt);
- var inst = this.objectTracker.obj;
- var px = cr.rotatePtAround(inst.x, inst.y, -inst.layer.getAngle(), listenerX, listenerY, true);
- var py = cr.rotatePtAround(inst.x, inst.y, -inst.layer.getAngle(), listenerX, listenerY, false);
- this.pannerNode["setPosition"](px, py, 0);
- var a = 0;
- if (typeof this.objectTracker.obj.angle !== "undefined")
- {
- a = inst.angle - inst.layer.getAngle();
- this.pannerNode["setOrientation"](Math.cos(a), Math.sin(a), 0);
- }
- px = cr.rotatePtAround(this.objectTracker.getVelocityX(), this.objectTracker.getVelocityY(), -inst.layer.getAngle(), 0, 0, true);
- py = cr.rotatePtAround(this.objectTracker.getVelocityX(), this.objectTracker.getVelocityY(), -inst.layer.getAngle(), 0, 0, false);
- this.pannerNode["setVelocity"](px, py, 0);
- };
- C2AudioInstance.prototype.play = function (looping, vol, fromPosition)
- {
- var instobj = this.instanceObject;
- this.looping = looping;
- this.volume = vol;
- var seekPos = fromPosition || 0;
- switch (this.myapi) {
- case API_HTML5:
- if (instobj.playbackRate !== 1.0)
- instobj.playbackRate = 1.0;
- if (instobj.volume !== vol * masterVolume)
- instobj.volume = vol * masterVolume;
- if (instobj.loop !== looping)
- instobj.loop = looping;
- if (instobj.muted)
- instobj.muted = false;
- if (instobj.currentTime !== seekPos)
- {
- try {
- instobj.currentTime = seekPos;
- }
- catch (err)
- {
- ;
- }
- }
- if (this.is_music && isMusicWorkaround && !audRuntime.isInUserInputEvent)
- musicPlayNextTouch.push(this);
- else
- {
- try {
- this.instanceObject.play();
- }
- catch (e) { // sometimes throws on WP8.1... try not to kill the app
- if (console && console.log)
- console.log("[C2] WARNING: exception trying to play audio '" + this.buffer.src + "': ", e);
- }
- }
- break;
- case API_WEBAUDIO:
- this.muted = false;
- this.mutevol = 1;
- if (this.buffer.myapi === API_WEBAUDIO)
- {
- this.gainNode["gain"]["value"] = vol * masterVolume;
- if (!this.fresh)
- {
- this.instanceObject = context["createBufferSource"]();
- this.instanceObject["buffer"] = this.buffer.bufferObject;
- this.instanceObject["connect"](this.gainNode);
- }
- this.instanceObject["onended"] = this.onended_handler;
- this.active_buffer = this.instanceObject;
- this.instanceObject.loop = looping;
- this.hasPlaybackEnded = false;
- if (seekPos === 0)
- startSource(this.instanceObject);
- else
- startSourceAt(this.instanceObject, seekPos, this.getDuration());
- }
- else
- {
- if (instobj.playbackRate !== 1.0)
- instobj.playbackRate = 1.0;
- if (instobj.loop !== looping)
- instobj.loop = looping;
- instobj.volume = vol * masterVolume;
- if (instobj.currentTime !== seekPos)
- {
- try {
- instobj.currentTime = seekPos;
- }
- catch (err)
- {
- ;
- }
- }
- if (this.is_music && isMusicWorkaround && !audRuntime.isInUserInputEvent)
- musicPlayNextTouch.push(this);
- else
- instobj.play();
- }
- break;
- case API_CORDOVA:
- if ((!this.fresh && this.stopped) || seekPos !== 0)
- instobj["seekTo"](seekPos);
- instobj["play"]();
- this.hasPlaybackEnded = false;
- break;
- case API_APPMOBI:
- if (audRuntime.isDirectCanvas)
- AppMobi["context"]["playSound"](this.src, looping);
- else
- AppMobi["player"]["playSound"](this.src, looping);
- break;
- }
- this.playbackRate = 1;
- this.startTime = (this.isTimescaled ? audRuntime.kahanTime.sum : audRuntime.wallTime.sum) - seekPos;
- this.fresh = false;
- this.stopped = false;
- this.is_paused = false;
- };
- C2AudioInstance.prototype.stop = function ()
- {
- switch (this.myapi) {
- case API_HTML5:
- if (!this.instanceObject.paused)
- this.instanceObject.pause();
- break;
- case API_WEBAUDIO:
- if (this.buffer.myapi === API_WEBAUDIO)
- stopSource(this.instanceObject);
- else
- {
- if (!this.instanceObject.paused)
- this.instanceObject.pause();
- }
- break;
- case API_CORDOVA:
- this.instanceObject["stop"]();
- break;
- case API_APPMOBI:
- if (audRuntime.isDirectCanvas)
- AppMobi["context"]["stopSound"](this.src);
- break;
- }
- this.stopped = true;
- this.is_paused = false;
- };
- C2AudioInstance.prototype.pause = function ()
- {
- if (this.fresh || this.stopped || this.hasEnded() || this.is_paused)
- return;
- switch (this.myapi) {
- case API_HTML5:
- if (!this.instanceObject.paused)
- this.instanceObject.pause();
- break;
- case API_WEBAUDIO:
- if (this.buffer.myapi === API_WEBAUDIO)
- {
- this.resume_position = this.getPlaybackTime();
- if (this.looping)
- this.resume_position = this.resume_position % this.getDuration();
- this.is_paused = true;
- stopSource(this.instanceObject);
- }
- else
- {
- if (!this.instanceObject.paused)
- this.instanceObject.pause();
- }
- break;
- case API_CORDOVA:
- this.instanceObject["pause"]();
- break;
- case API_APPMOBI:
- if (audRuntime.isDirectCanvas)
- AppMobi["context"]["stopSound"](this.src);
- break;
- }
- this.is_paused = true;
- };
- C2AudioInstance.prototype.resume = function ()
- {
- if (this.fresh || this.stopped || this.hasEnded() || !this.is_paused)
- return;
- switch (this.myapi) {
- case API_HTML5:
- this.instanceObject.play();
- break;
- case API_WEBAUDIO:
- if (this.buffer.myapi === API_WEBAUDIO)
- {
- this.instanceObject = context["createBufferSource"]();
- this.instanceObject["buffer"] = this.buffer.bufferObject;
- this.instanceObject["connect"](this.gainNode);
- this.instanceObject["onended"] = this.onended_handler;
- this.active_buffer = this.instanceObject;
- this.instanceObject.loop = this.looping;
- this.gainNode["gain"]["value"] = masterVolume * this.volume * this.mutevol;
- this.startTime = (this.isTimescaled ? audRuntime.kahanTime.sum : audRuntime.wallTime.sum) - this.resume_position;
- startSourceAt(this.instanceObject, this.resume_position, this.getDuration());
- }
- else
- {
- this.instanceObject.play();
- }
- break;
- case API_CORDOVA:
- this.instanceObject["play"]();
- break;
- case API_APPMOBI:
- if (audRuntime.isDirectCanvas)
- AppMobi["context"]["resumeSound"](this.src);
- break;
- }
- this.is_paused = false;
- };
- C2AudioInstance.prototype.seek = function (pos)
- {
- if (this.fresh || this.stopped || this.hasEnded())
- return;
- switch (this.myapi) {
- case API_HTML5:
- try {
- this.instanceObject.currentTime = pos;
- }
- catch (e) {}
- break;
- case API_WEBAUDIO:
- if (this.buffer.myapi === API_WEBAUDIO)
- {
- if (this.is_paused)
- this.resume_position = pos;
- else
- {
- this.pause();
- this.resume_position = pos;
- this.resume();
- }
- }
- else
- {
- try {
- this.instanceObject.currentTime = pos;
- }
- catch (e) {}
- }
- break;
- case API_CORDOVA:
- break;
- case API_APPMOBI:
- if (audRuntime.isDirectCanvas)
- AppMobi["context"]["seekSound"](this.src, pos);
- break;
- }
- };
- C2AudioInstance.prototype.reconnect = function (toNode)
- {
- if (this.myapi !== API_WEBAUDIO)
- return;
- if (this.pannerEnabled)
- {
- this.pannerNode["disconnect"]();
- this.pannerNode["connect"](toNode);
- }
- else
- {
- this.gainNode["disconnect"]();
- this.gainNode["connect"](toNode);
- }
- };
- C2AudioInstance.prototype.getDuration = function ()
- {
- switch (this.myapi) {
- case API_HTML5:
- if (typeof this.instanceObject.duration !== "undefined")
- return this.instanceObject.duration;
- else
- return 0;
- case API_WEBAUDIO:
- return this.buffer.bufferObject["duration"];
- case API_CORDOVA:
- return this.instanceObject["getDuration"]();
- case API_APPMOBI:
- if (audRuntime.isDirectCanvas)
- return AppMobi["context"]["getDurationSound"](this.src);
- else
- return 0;
- }
- return 0;
- };
- C2AudioInstance.prototype.getPlaybackTime = function ()
- {
- var duration = this.getDuration();
- var ret = 0;
- switch (this.myapi) {
- case API_HTML5:
- if (typeof this.instanceObject.currentTime !== "undefined")
- ret = this.instanceObject.currentTime;
- break;
- case API_WEBAUDIO:
- if (this.buffer.myapi === API_WEBAUDIO)
- {
- if (this.is_paused)
- return this.resume_position;
- else
- ret = (this.isTimescaled ? audRuntime.kahanTime.sum : audRuntime.wallTime.sum) - this.startTime;
- }
- else if (typeof this.instanceObject.currentTime !== "undefined")
- ret = this.instanceObject.currentTime;
- break;
- case API_CORDOVA:
- break;
- case API_APPMOBI:
- if (audRuntime.isDirectCanvas)
- ret = AppMobi["context"]["getPlaybackTimeSound"](this.src);
- break;
- }
- if (!this.looping && ret > duration)
- ret = duration;
- return ret;
- };
- C2AudioInstance.prototype.isPlaying = function ()
- {
- return !this.is_paused && !this.fresh && !this.stopped && !this.hasEnded();
- };
- C2AudioInstance.prototype.setVolume = function (v)
- {
- this.volume = v;
- this.updateVolume();
- };
- C2AudioInstance.prototype.updateVolume = function ()
- {
- var volToSet = this.volume * masterVolume;
- if (!isFinite(volToSet))
- volToSet = 0; // HTMLMediaElement throws if setting non-finite volume
- switch (this.myapi) {
- case API_HTML5:
- if (typeof this.instanceObject.volume !== "undefined" && this.instanceObject.volume !== volToSet)
- this.instanceObject.volume = volToSet;
- break;
- case API_WEBAUDIO:
- if (this.buffer.myapi === API_WEBAUDIO)
- {
- this.gainNode["gain"]["value"] = volToSet * this.mutevol;
- }
- else
- {
- if (typeof this.instanceObject.volume !== "undefined" && this.instanceObject.volume !== volToSet)
- this.instanceObject.volume = volToSet;
- }
- break;
- case API_CORDOVA:
- break;
- case API_APPMOBI:
- break;
- }
- };
- C2AudioInstance.prototype.getVolume = function ()
- {
- return this.volume;
- };
- C2AudioInstance.prototype.doSetMuted = function (m)
- {
- switch (this.myapi) {
- case API_HTML5:
- if (this.instanceObject.muted !== !!m)
- this.instanceObject.muted = !!m;
- break;
- case API_WEBAUDIO:
- if (this.buffer.myapi === API_WEBAUDIO)
- {
- this.mutevol = (m ? 0 : 1);
- this.gainNode["gain"]["value"] = masterVolume * this.volume * this.mutevol;
- }
- else
- {
- if (this.instanceObject.muted !== !!m)
- this.instanceObject.muted = !!m;
- }
- break;
- case API_CORDOVA:
- break;
- case API_APPMOBI:
- break;
- }
- };
- C2AudioInstance.prototype.setMuted = function (m)
- {
- this.is_muted = !!m;
- this.doSetMuted(this.is_muted || this.is_silent);
- };
- C2AudioInstance.prototype.setSilent = function (m)
- {
- this.is_silent = !!m;
- this.doSetMuted(this.is_muted || this.is_silent);
- };
- C2AudioInstance.prototype.setLooping = function (l)
- {
- this.looping = l;
- switch (this.myapi) {
- case API_HTML5:
- if (this.instanceObject.loop !== !!l)
- this.instanceObject.loop = !!l;
- break;
- case API_WEBAUDIO:
- if (this.instanceObject.loop !== !!l)
- this.instanceObject.loop = !!l;
- break;
- case API_CORDOVA:
- break;
- case API_APPMOBI:
- if (audRuntime.isDirectCanvas)
- AppMobi["context"]["setLoopingSound"](this.src, l);
- break;
- }
- };
- C2AudioInstance.prototype.setPlaybackRate = function (r)
- {
- this.playbackRate = r;
- this.updatePlaybackRate();
- };
- C2AudioInstance.prototype.updatePlaybackRate = function ()
- {
- var r = this.playbackRate;
- if (this.isTimescaled)
- r *= audRuntime.timescale;
- switch (this.myapi) {
- case API_HTML5:
- if (this.instanceObject.playbackRate !== r)
- this.instanceObject.playbackRate = r;
- break;
- case API_WEBAUDIO:
- if (this.buffer.myapi === API_WEBAUDIO)
- {
- if (this.instanceObject["playbackRate"]["value"] !== r)
- this.instanceObject["playbackRate"]["value"] = r;
- }
- else
- {
- if (this.instanceObject.playbackRate !== r)
- this.instanceObject.playbackRate = r;
- }
- break;
- case API_CORDOVA:
- break;
- case API_APPMOBI:
- break;
- }
- };
- C2AudioInstance.prototype.setSuspended = function (s)
- {
- switch (this.myapi) {
- case API_HTML5:
- if (s)
- {
- if (this.isPlaying())
- {
- this.instanceObject["pause"]();
- this.resume_me = true;
- }
- else
- this.resume_me = false;
- }
- else
- {
- if (this.resume_me)
- this.instanceObject["play"]();
- }
- break;
- case API_WEBAUDIO:
- if (s)
- {
- if (this.isPlaying())
- {
- if (this.buffer.myapi === API_WEBAUDIO)
- {
- this.resume_position = this.getPlaybackTime();
- if (this.looping)
- this.resume_position = this.resume_position % this.getDuration();
- stopSource(this.instanceObject);
- }
- else
- this.instanceObject["pause"]();
- this.resume_me = true;
- }
- else
- this.resume_me = false;
- }
- else
- {
- if (this.resume_me)
- {
- if (this.buffer.myapi === API_WEBAUDIO)
- {
- this.instanceObject = context["createBufferSource"]();
- this.instanceObject["buffer"] = this.buffer.bufferObject;
- this.instanceObject["connect"](this.gainNode);
- this.instanceObject["onended"] = this.onended_handler;
- this.active_buffer = this.instanceObject;
- this.instanceObject.loop = this.looping;
- this.gainNode["gain"]["value"] = masterVolume * this.volume * this.mutevol;
- this.startTime = (this.isTimescaled ? audRuntime.kahanTime.sum : audRuntime.wallTime.sum) - this.resume_position;
- startSourceAt(this.instanceObject, this.resume_position, this.getDuration());
- }
- else
- {
- this.instanceObject["play"]();
- }
- }
- }
- break;
- case API_CORDOVA:
- if (s)
- {
- if (this.isPlaying())
- {
- this.instanceObject["pause"]();
- this.resume_me = true;
- }
- else
- this.resume_me = false;
- }
- else
- {
- if (this.resume_me)
- this.instanceObject["play"]();
- }
- break;
- case API_APPMOBI:
- break;
- }
- };
- pluginProto.Instance = function(type)
- {
- this.type = type;
- this.runtime = type.runtime;
- audRuntime = this.runtime;
- audInst = this;
- this.listenerTracker = null;
- this.listenerZ = -600;
- if ((this.runtime.isiOS || (this.runtime.isAndroid && (this.runtime.isChrome || this.runtime.isAndroidStockBrowser))) && !this.runtime.isCrosswalk && !this.runtime.isDomFree && !this.runtime.isAmazonWebApp)
- {
- isMusicWorkaround = true;
- }
- context = null;
- if (typeof AudioContext !== "undefined")
- {
- api = API_WEBAUDIO;
- context = new AudioContext();
- }
- else if (typeof webkitAudioContext !== "undefined")
- {
- api = API_WEBAUDIO;
- context = new webkitAudioContext();
- }
- if ((this.runtime.isiOS && api === API_WEBAUDIO) || isMusicWorkaround)
- {
- document.addEventListener("touchstart", function ()
- {
- var i, len, m;
- if (!iOShadtouch && context)
- {
- var buffer = context["createBuffer"](1, 1, 22050);
- var source = context["createBufferSource"]();
- source["buffer"] = buffer;
- source["connect"](context["destination"]);
- startSource(source);
- iOShadtouch = true;
- }
- if (isMusicWorkaround)
- {
- if (!silent)
- {
- for (i = 0, len = musicPlayNextTouch.length; i < len; ++i)
- {
- m = musicPlayNextTouch[i];
- if (!m.stopped && !m.is_paused)
- m.instanceObject.play();
- }
- }
- cr.clearArray(musicPlayNextTouch);
- }
- }, true);
- }
- if (api !== API_WEBAUDIO)
- {
- if (this.runtime.isCordova && typeof window["Media"] !== "undefined")
- api = API_CORDOVA;
- else if (this.runtime.isAppMobi)
- api = API_APPMOBI;
- }
- if (api === API_CORDOVA)
- {
- appPath = location.href;
- var i = appPath.lastIndexOf("/");
- if (i > -1)
- appPath = appPath.substr(0, i + 1);
- appPath = appPath.replace("file://", "");
- }
- if (this.runtime.isSafari && this.runtime.isWindows && typeof Audio === "undefined")
- {
- alert("It looks like you're using Safari for Windows without Quicktime. Audio cannot be played until Quicktime is installed.");
- this.runtime.DestroyInstance(this);
- }
- else
- {
- if (this.runtime.isDirectCanvas)
- useOgg = this.runtime.isAndroid; // AAC on iOS, OGG on Android
- else
- {
- try {
- useOgg = !!(new Audio().canPlayType('audio/ogg; codecs="vorbis"'));
- }
- catch (e)
- {
- useOgg = false;
- }
- }
- switch (api) {
- case API_HTML5:
- ;
- break;
- case API_WEBAUDIO:
- ;
- break;
- case API_CORDOVA:
- ;
- break;
- case API_APPMOBI:
- ;
- break;
- default:
- ;
- }
- this.runtime.tickMe(this);
- }
- };
- var instanceProto = pluginProto.Instance.prototype;
- instanceProto.onCreate = function ()
- {
- this.runtime.audioInstance = this;
- timescale_mode = this.properties[0]; // 0 = off, 1 = sounds only, 2 = all
- this.saveload = this.properties[1]; // 0 = all, 1 = sounds only, 2 = music only, 3 = none
- this.playinbackground = (this.properties[2] !== 0);
- panningModel = this.properties[3]; // 0 = equalpower, 1 = hrtf, 3 = soundfield
- distanceModel = this.properties[4]; // 0 = linear, 1 = inverse, 2 = exponential
- this.listenerZ = -this.properties[5];
- refDistance = this.properties[6];
- maxDistance = this.properties[7];
- rolloffFactor = this.properties[8];
- this.listenerTracker = new ObjectTracker();
- var draw_width = (this.runtime.draw_width || this.runtime.width);
- var draw_height = (this.runtime.draw_height || this.runtime.height);
- if (api === API_WEBAUDIO)
- {
- if (typeof context["listener"]["dopplerFactor"] !== "undefined")
- context["listener"]["dopplerFactor"] = 0;
- context["listener"]["setPosition"](draw_width / 2, draw_height / 2, this.listenerZ);
- context["listener"]["setOrientation"](0, 0, 1, 0, -1, 0);
- window["c2OnAudioMicStream"] = function (localMediaStream, tag)
- {
- if (micSource)
- micSource["disconnect"]();
- micTag = tag.toLowerCase();
- micSource = context["createMediaStreamSource"](localMediaStream);
- micSource["connect"](getDestinationForTag(micTag));
- };
- }
- this.runtime.addSuspendCallback(function(s)
- {
- audInst.onSuspend(s);
- });
- var self = this;
- this.runtime.addDestroyCallback(function (inst)
- {
- self.onInstanceDestroyed(inst);
- });
- };
- instanceProto.onInstanceDestroyed = function (inst)
- {
- var i, len, a;
- for (i = 0, len = audioInstances.length; i < len; i++)
- {
- a = audioInstances[i];
- if (a.objectTracker)
- {
- if (a.objectTracker.obj === inst)
- {
- a.objectTracker.obj = null;
- if (a.pannerEnabled && a.isPlaying() && a.looping)
- a.stop();
- }
- }
- }
- if (this.listenerTracker.obj === inst)
- this.listenerTracker.obj = null;
- };
- instanceProto.saveToJSON = function ()
- {
- var o = {
- "silent": silent,
- "masterVolume": masterVolume,
- "listenerZ": this.listenerZ,
- "listenerUid": this.listenerTracker.hasObject() ? this.listenerTracker.obj.uid : -1,
- "playing": [],
- "effects": {}
- };
- var playingarr = o["playing"];
- var i, len, a, d, p, panobj, playbackTime;
- for (i = 0, len = audioInstances.length; i < len; i++)
- {
- a = audioInstances[i];
- if (!a.isPlaying())
- continue; // no need to save stopped sounds
- if (this.saveload === 3) // not saving/loading any sounds/music
- continue;
- if (a.is_music && this.saveload === 1) // not saving/loading music
- continue;
- if (!a.is_music && this.saveload === 2) // not saving/loading sound
- continue;
- playbackTime = a.getPlaybackTime();
- if (a.looping)
- playbackTime = playbackTime % a.getDuration();
- d = {
- "tag": a.tag,
- "buffersrc": a.buffer.src,
- "is_music": a.is_music,
- "playbackTime": playbackTime,
- "volume": a.volume,
- "looping": a.looping,
- "muted": a.is_muted,
- "playbackRate": a.playbackRate,
- "paused": a.is_paused,
- "resume_position": a.resume_position
- };
- if (a.pannerEnabled)
- {
- d["pan"] = {};
- panobj = d["pan"];
- if (a.objectTracker && a.objectTracker.hasObject())
- {
- panobj["objUid"] = a.objectTracker.obj.uid;
- }
- else
- {
- panobj["x"] = a.panX;
- panobj["y"] = a.panY;
- panobj["a"] = a.panAngle;
- }
- panobj["ia"] = a.panConeInner;
- panobj["oa"] = a.panConeOuter;
- panobj["og"] = a.panConeOuterGain;
- }
- playingarr.push(d);
- }
- var fxobj = o["effects"];
- var fxarr;
- for (p in effects)
- {
- if (effects.hasOwnProperty(p))
- {
- fxarr = [];
- for (i = 0, len = effects[p].length; i < len; i++)
- {
- fxarr.push({ "type": effects[p][i].type, "params": effects[p][i].params });
- }
- fxobj[p] = fxarr;
- }
- }
- return o;
- };
- var objectTrackerUidsToLoad = [];
- instanceProto.loadFromJSON = function (o)
- {
- var setSilent = o["silent"];
- masterVolume = o["masterVolume"];
- this.listenerZ = o["listenerZ"];
- this.listenerTracker.setObject(null);
- var listenerUid = o["listenerUid"];
- if (listenerUid !== -1)
- {
- this.listenerTracker.loadUid = listenerUid;
- objectTrackerUidsToLoad.push(this.listenerTracker);
- }
- var playingarr = o["playing"];
- var i, len, d, src, is_music, tag, playbackTime, looping, vol, b, a, p, pan, panObjUid;
- if (this.saveload !== 3)
- {
- for (i = 0, len = audioInstances.length; i < len; i++)
- {
- a = audioInstances[i];
- if (a.is_music && this.saveload === 1)
- continue; // only saving/loading sound: leave music playing
- if (!a.is_music && this.saveload === 2)
- continue; // only saving/loading music: leave sound playing
- a.stop();
- }
- }
- var fxarr, fxtype, fxparams, fx;
- for (p in effects)
- {
- if (effects.hasOwnProperty(p))
- {
- for (i = 0, len = effects[p].length; i < len; i++)
- effects[p][i].remove();
- }
- }
- cr.wipe(effects);
- for (p in o["effects"])
- {
- if (o["effects"].hasOwnProperty(p))
- {
- fxarr = o["effects"][p];
- for (i = 0, len = fxarr.length; i < len; i++)
- {
- fxtype = fxarr[i]["type"];
- fxparams = fxarr[i]["params"];
- switch (fxtype) {
- case "filter":
- addEffectForTag(p, new FilterEffect(fxparams[0], fxparams[1], fxparams[2], fxparams[3], fxparams[4], fxparams[5]));
- break;
- case "delay":
- addEffectForTag(p, new DelayEffect(fxparams[0], fxparams[1], fxparams[2]));
- break;
- case "convolve":
- src = fxparams[2];
- b = this.getAudioBuffer(src, false);
- if (b.bufferObject)
- {
- fx = new ConvolveEffect(b.bufferObject, fxparams[0], fxparams[1], src);
- }
- else
- {
- fx = new ConvolveEffect(null, fxparams[0], fxparams[1], src);
- b.normalizeWhenReady = fxparams[0];
- b.convolveWhenReady = fx;
- }
- addEffectForTag(p, fx);
- break;
- case "flanger":
- addEffectForTag(p, new FlangerEffect(fxparams[0], fxparams[1], fxparams[2], fxparams[3], fxparams[4]));
- break;
- case "phaser":
- addEffectForTag(p, new PhaserEffect(fxparams[0], fxparams[1], fxparams[2], fxparams[3], fxparams[4], fxparams[5]));
- break;
- case "gain":
- addEffectForTag(p, new GainEffect(fxparams[0]));
- break;
- case "tremolo":
- addEffectForTag(p, new TremoloEffect(fxparams[0], fxparams[1]));
- break;
- case "ringmod":
- addEffectForTag(p, new RingModulatorEffect(fxparams[0], fxparams[1]));
- break;
- case "distortion":
- addEffectForTag(p, new DistortionEffect(fxparams[0], fxparams[1], fxparams[2], fxparams[3], fxparams[4]));
- break;
- case "compressor":
- addEffectForTag(p, new CompressorEffect(fxparams[0], fxparams[1], fxparams[2], fxparams[3], fxparams[4]));
- break;
- case "analyser":
- addEffectForTag(p, new AnalyserEffect(fxparams[0], fxparams[1]));
- break;
- }
- }
- }
- }
- for (i = 0, len = playingarr.length; i < len; i++)
- {
- if (this.saveload === 3) // not saving/loading any sounds/music
- continue;
- d = playingarr[i];
- src = d["buffersrc"];
- is_music = d["is_music"];
- tag = d["tag"];
- playbackTime = d["playbackTime"];
- looping = d["looping"];
- vol = d["volume"];
- pan = d["pan"];
- panObjUid = (pan && pan.hasOwnProperty("objUid")) ? pan["objUid"] : -1;
- if (is_music && this.saveload === 1) // not saving/loading music
- continue;
- if (!is_music && this.saveload === 2) // not saving/loading sound
- continue;
- a = this.getAudioInstance(src, tag, is_music, looping, vol);
- if (!a)
- {
- b = this.getAudioBuffer(src, is_music);
- b.seekWhenReady = playbackTime;
- b.pauseWhenReady = d["paused"];
- if (pan)
- {
- if (panObjUid !== -1)
- {
- b.panWhenReady.push({ objUid: panObjUid, ia: pan["ia"], oa: pan["oa"], og: pan["og"], thistag: tag });
- }
- else
- {
- b.panWhenReady.push({ x: pan["x"], y: pan["y"], a: pan["a"], ia: pan["ia"], oa: pan["oa"], og: pan["og"], thistag: tag });
- }
- }
- continue;
- }
- a.resume_position = d["resume_position"];
- a.setPannerEnabled(!!pan);
- a.play(looping, vol, playbackTime);
- a.updatePlaybackRate();
- a.updateVolume();
- a.doSetMuted(a.is_muted || a.is_silent);
- if (d["paused"])
- a.pause();
- if (d["muted"])
- a.setMuted(true);
- a.doSetMuted(a.is_muted || a.is_silent);
- if (pan)
- {
- if (panObjUid !== -1)
- {
- a.objectTracker = a.objectTracker || new ObjectTracker();
- a.objectTracker.loadUid = panObjUid;
- objectTrackerUidsToLoad.push(a.objectTracker);
- }
- else
- {
- a.setPan(pan["x"], pan["y"], pan["a"], pan["ia"], pan["oa"], pan["og"]);
- }
- }
- }
- if (setSilent && !silent) // setting silent
- {
- for (i = 0, len = audioInstances.length; i < len; i++)
- audioInstances[i].setSilent(true);
- silent = true;
- }
- else if (!setSilent && silent) // setting not silent
- {
- for (i = 0, len = audioInstances.length; i < len; i++)
- audioInstances[i].setSilent(false);
- silent = false;
- }
- };
- instanceProto.afterLoad = function ()
- {
- var i, len, ot, inst;
- for (i = 0, len = objectTrackerUidsToLoad.length; i < len; i++)
- {
- ot = objectTrackerUidsToLoad[i];
- inst = this.runtime.getObjectByUID(ot.loadUid);
- ot.setObject(inst);
- ot.loadUid = -1;
- if (inst)
- {
- listenerX = inst.x;
- listenerY = inst.y;
- }
- }
- cr.clearArray(objectTrackerUidsToLoad);
- };
- instanceProto.onSuspend = function (s)
- {
- if (this.playinbackground)
- return;
- if (!s && context && context["resume"])
- context["resume"]();
- var i, len;
- for (i = 0, len = audioInstances.length; i < len; i++)
- audioInstances[i].setSuspended(s);
- if (s && context && context["suspend"])
- context["suspend"]();
- };
- instanceProto.tick = function ()
- {
- var dt = this.runtime.dt;
- var i, len, a;
- for (i = 0, len = audioInstances.length; i < len; i++)
- {
- a = audioInstances[i];
- a.tick(dt);
- if (timescale_mode !== 0)
- a.updatePlaybackRate();
- }
- var p, arr, f;
- for (p in effects)
- {
- if (effects.hasOwnProperty(p))
- {
- arr = effects[p];
- for (i = 0, len = arr.length; i < len; i++)
- {
- f = arr[i];
- if (f.tick)
- f.tick();
- }
- }
- }
- if (api === API_WEBAUDIO && this.listenerTracker.hasObject())
- {
- this.listenerTracker.tick(dt);
- listenerX = this.listenerTracker.obj.x;
- listenerY = this.listenerTracker.obj.y;
- context["listener"]["setPosition"](this.listenerTracker.obj.x, this.listenerTracker.obj.y, this.listenerZ);
- context["listener"]["setVelocity"](this.listenerTracker.getVelocityX(), this.listenerTracker.getVelocityY(), 0);
- }
- };
- var preload_list = [];
- instanceProto.setPreloadList = function (arr)
- {
- var i, len, p, filename, size, isOgg;
- var total_size = 0;
- for (i = 0, len = arr.length; i < len; ++i)
- {
- p = arr[i];
- filename = p[0];
- size = p[1] * 2;
- isOgg = (filename.length > 4 && filename.substr(filename.length - 4) === ".ogg");
- if ((isOgg && useOgg) || (!isOgg && !useOgg))
- {
- preload_list.push({
- filename: filename,
- size: size,
- obj: null
- });
- total_size += size;
- }
- }
- return total_size;
- };
- instanceProto.startPreloads = function ()
- {
- var i, len, p, src;
- for (i = 0, len = preload_list.length; i < len; ++i)
- {
- p = preload_list[i];
- src = this.runtime.files_subfolder + p.filename;
- p.obj = this.getAudioBuffer(src, false);
- }
- };
- instanceProto.getPreloadedSize = function ()
- {
- var completed = 0;
- var i, len, p;
- for (i = 0, len = preload_list.length; i < len; ++i)
- {
- p = preload_list[i];
- if (p.obj.isLoadedAndDecoded() || p.obj.hasFailedToLoad() || this.runtime.isDomFree || this.runtime.isAndroidStockBrowser)
- {
- completed += p.size;
- }
- else if (p.obj.isLoaded()) // downloaded but not decoded: only happens in Web Audio API, count as half-way progress
- {
- completed += Math.floor(p.size / 2);
- }
- };
- return completed;
- };
- instanceProto.getAudioBuffer = function (src_, is_music)
- {
- var i, len, a, ret = null, j, k, lenj, ai;
- for (i = 0, len = audioBuffers.length; i < len; i++)
- {
- a = audioBuffers[i];
- if (a.src === src_)
- {
- ret = a;
- break;
- }
- }
- if (!ret)
- {
- ret = new C2AudioBuffer(src_, is_music);
- audioBuffers.push(ret);
- }
- return ret;
- };
- instanceProto.getAudioInstance = function (src_, tag, is_music, looping, vol)
- {
- var i, len, a;
- for (i = 0, len = audioInstances.length; i < len; i++)
- {
- a = audioInstances[i];
- if (a.src === src_ && (a.canBeRecycled() || is_music))
- {
- a.tag = tag;
- return a;
- }
- }
- var b = this.getAudioBuffer(src_, is_music);
- if (!b.bufferObject)
- {
- if (tag !== "<preload>")
- {
- b.playTagWhenReady = tag;
- b.loopWhenReady = looping;
- b.volumeWhenReady = vol;
- }
- return null;
- }
- a = new C2AudioInstance(b, tag);
- audioInstances.push(a);
- return a;
- };
- var taggedAudio = [];
- function SortByIsPlaying(a, b)
- {
- var an = a.isPlaying() ? 1 : 0;
- var bn = b.isPlaying() ? 1 : 0;
- if (an === bn)
- return 0;
- else if (an < bn)
- return 1;
- else
- return -1;
- };
- function getAudioByTag(tag, sort_by_playing)
- {
- cr.clearArray(taggedAudio);
- if (!tag.length)
- {
- if (!lastAudio || lastAudio.hasEnded())
- return;
- else
- {
- cr.clearArray(taggedAudio);
- taggedAudio[0] = lastAudio;
- return;
- }
- }
- var i, len, a;
- for (i = 0, len = audioInstances.length; i < len; i++)
- {
- a = audioInstances[i];
- if (cr.equals_nocase(tag, a.tag))
- taggedAudio.push(a);
- }
- if (sort_by_playing)
- taggedAudio.sort(SortByIsPlaying);
- };
- function reconnectEffects(tag)
- {
- var i, len, arr, n, toNode = context["destination"];
- if (effects.hasOwnProperty(tag))
- {
- arr = effects[tag];
- if (arr.length)
- {
- toNode = arr[0].getInputNode();
- for (i = 0, len = arr.length; i < len; i++)
- {
- n = arr[i];
- if (i + 1 === len)
- n.connectTo(context["destination"]);
- else
- n.connectTo(arr[i + 1].getInputNode());
- }
- }
- }
- getAudioByTag(tag);
- for (i = 0, len = taggedAudio.length; i < len; i++)
- taggedAudio[i].reconnect(toNode);
- if (micSource && micTag === tag)
- {
- micSource["disconnect"]();
- micSource["connect"](toNode);
- }
- };
- function addEffectForTag(tag, fx)
- {
- if (!effects.hasOwnProperty(tag))
- effects[tag] = [fx];
- else
- effects[tag].push(fx);
- reconnectEffects(tag);
- };
- function Cnds() {};
- Cnds.prototype.OnEnded = function (t)
- {
- return cr.equals_nocase(audTag, t);
- };
- Cnds.prototype.PreloadsComplete = function ()
- {
- var i, len;
- for (i = 0, len = audioBuffers.length; i < len; i++)
- {
- if (!audioBuffers[i].isLoadedAndDecoded() && !audioBuffers[i].hasFailedToLoad())
- return false;
- }
- return true;
- };
- Cnds.prototype.AdvancedAudioSupported = function ()
- {
- return api === API_WEBAUDIO;
- };
- Cnds.prototype.IsSilent = function ()
- {
- return silent;
- };
- Cnds.prototype.IsAnyPlaying = function ()
- {
- var i, len;
- for (i = 0, len = audioInstances.length; i < len; i++)
- {
- if (audioInstances[i].isPlaying())
- return true;
- }
- return false;
- };
- Cnds.prototype.IsTagPlaying = function (tag)
- {
- getAudioByTag(tag);
- var i, len;
- for (i = 0, len = taggedAudio.length; i < len; i++)
- {
- if (taggedAudio[i].isPlaying())
- return true;
- }
- return false;
- };
- pluginProto.cnds = new Cnds();
- function Acts() {};
- Acts.prototype.Play = function (file, looping, vol, tag)
- {
- if (silent)
- return;
- var v = dbToLinear(vol);
- var is_music = file[1];
- var src = this.runtime.files_subfolder + file[0] + (useOgg ? ".ogg" : ".m4a");
- lastAudio = this.getAudioInstance(src, tag, is_music, looping!==0, v);
- if (!lastAudio)
- return;
- lastAudio.setPannerEnabled(false);
- lastAudio.play(looping!==0, v);
- };
- Acts.prototype.PlayAtPosition = function (file, looping, vol, x_, y_, angle_, innerangle_, outerangle_, outergain_, tag)
- {
- if (silent)
- return;
- var v = dbToLinear(vol);
- var is_music = file[1];
- var src = this.runtime.files_subfolder + file[0] + (useOgg ? ".ogg" : ".m4a");
- lastAudio = this.getAudioInstance(src, tag, is_music, looping!==0, v);
- if (!lastAudio)
- {
- var b = this.getAudioBuffer(src, is_music);
- b.panWhenReady.push({ x: x_, y: y_, a: angle_, ia: innerangle_, oa: outerangle_, og: dbToLinear(outergain_), thistag: tag });
- return;
- }
- lastAudio.setPannerEnabled(true);
- lastAudio.setPan(x_, y_, angle_, innerangle_, outerangle_, dbToLinear(outergain_));
- lastAudio.play(looping!==0, v);
- };
- Acts.prototype.PlayAtObject = function (file, looping, vol, obj, innerangle, outerangle, outergain, tag)
- {
- if (silent || !obj)
- return;
- var inst = obj.getFirstPicked();
- if (!inst)
- return;
- var v = dbToLinear(vol);
- var is_music = file[1];
- var src = this.runtime.files_subfolder + file[0] + (useOgg ? ".ogg" : ".m4a");
- lastAudio = this.getAudioInstance(src, tag, is_music, looping!==0, v);
- if (!lastAudio)
- {
- var b = this.getAudioBuffer(src, is_music);
- b.panWhenReady.push({ obj: inst, ia: innerangle, oa: outerangle, og: dbToLinear(outergain), thistag: tag });
- return;
- }
- lastAudio.setPannerEnabled(true);
- var px = cr.rotatePtAround(inst.x, inst.y, -inst.layer.getAngle(), listenerX, listenerY, true);
- var py = cr.rotatePtAround(inst.x, inst.y, -inst.layer.getAngle(), listenerX, listenerY, false);
- lastAudio.setPan(px, py, cr.to_degrees(inst.angle - inst.layer.getAngle()), innerangle, outerangle, dbToLinear(outergain));
- lastAudio.setObject(inst);
- lastAudio.play(looping!==0, v);
- };
- Acts.prototype.PlayByName = function (folder, filename, looping, vol, tag)
- {
- if (silent)
- return;
- var v = dbToLinear(vol);
- var is_music = (folder === 1);
- var src = this.runtime.files_subfolder + filename.toLowerCase() + (useOgg ? ".ogg" : ".m4a");
- lastAudio = this.getAudioInstance(src, tag, is_music, looping!==0, v);
- if (!lastAudio)
- return;
- lastAudio.setPannerEnabled(false);
- lastAudio.play(looping!==0, v);
- };
- Acts.prototype.PlayAtPositionByName = function (folder, filename, looping, vol, x_, y_, angle_, innerangle_, outerangle_, outergain_, tag)
- {
- if (silent)
- return;
- var v = dbToLinear(vol);
- var is_music = (folder === 1);
- var src = this.runtime.files_subfolder + filename.toLowerCase() + (useOgg ? ".ogg" : ".m4a");
- lastAudio = this.getAudioInstance(src, tag, is_music, looping!==0, v);
- if (!lastAudio)
- {
- var b = this.getAudioBuffer(src, is_music);
- b.panWhenReady.push({ x: x_, y: y_, a: angle_, ia: innerangle_, oa: outerangle_, og: dbToLinear(outergain_), thistag: tag });
- return;
- }
- lastAudio.setPannerEnabled(true);
- lastAudio.setPan(x_, y_, angle_, innerangle_, outerangle_, dbToLinear(outergain_));
- lastAudio.play(looping!==0, v);
- };
- Acts.prototype.PlayAtObjectByName = function (folder, filename, looping, vol, obj, innerangle, outerangle, outergain, tag)
- {
- if (silent || !obj)
- return;
- var inst = obj.getFirstPicked();
- if (!inst)
- return;
- var v = dbToLinear(vol);
- var is_music = (folder === 1);
- var src = this.runtime.files_subfolder + filename.toLowerCase() + (useOgg ? ".ogg" : ".m4a");
- lastAudio = this.getAudioInstance(src, tag, is_music, looping!==0, v);
- if (!lastAudio)
- {
- var b = this.getAudioBuffer(src, is_music);
- b.panWhenReady.push({ obj: inst, ia: innerangle, oa: outerangle, og: dbToLinear(outergain), thistag: tag });
- return;
- }
- lastAudio.setPannerEnabled(true);
- var px = cr.rotatePtAround(inst.x, inst.y, -inst.layer.getAngle(), listenerX, listenerY, true);
- var py = cr.rotatePtAround(inst.x, inst.y, -inst.layer.getAngle(), listenerX, listenerY, false);
- lastAudio.setPan(px, py, cr.to_degrees(inst.angle - inst.layer.getAngle()), innerangle, outerangle, dbToLinear(outergain));
- lastAudio.setObject(inst);
- lastAudio.play(looping!==0, v);
- };
- Acts.prototype.SetLooping = function (tag, looping)
- {
- getAudioByTag(tag);
- var i, len;
- for (i = 0, len = taggedAudio.length; i < len; i++)
- taggedAudio[i].setLooping(looping === 0);
- };
- Acts.prototype.SetMuted = function (tag, muted)
- {
- getAudioByTag(tag);
- var i, len;
- for (i = 0, len = taggedAudio.length; i < len; i++)
- taggedAudio[i].setMuted(muted === 0);
- };
- Acts.prototype.SetVolume = function (tag, vol)
- {
- getAudioByTag(tag);
- var v = dbToLinear(vol);
- var i, len;
- for (i = 0, len = taggedAudio.length; i < len; i++)
- taggedAudio[i].setVolume(v);
- };
- Acts.prototype.Preload = function (file)
- {
- if (silent)
- return;
- var is_music = file[1];
- var src = this.runtime.files_subfolder + file[0] + (useOgg ? ".ogg" : ".m4a");
- if (api === API_APPMOBI)
- {
- if (this.runtime.isDirectCanvas)
- AppMobi["context"]["loadSound"](src);
- else
- AppMobi["player"]["loadSound"](src);
- return;
- }
- else if (api === API_CORDOVA)
- {
- return;
- }
- this.getAudioInstance(src, "<preload>", is_music, false);
- };
- Acts.prototype.PreloadByName = function (folder, filename)
- {
- if (silent)
- return;
- var is_music = (folder === 1);
- var src = this.runtime.files_subfolder + filename.toLowerCase() + (useOgg ? ".ogg" : ".m4a");
- if (api === API_APPMOBI)
- {
- if (this.runtime.isDirectCanvas)
- AppMobi["context"]["loadSound"](src);
- else
- AppMobi["player"]["loadSound"](src);
- return;
- }
- else if (api === API_CORDOVA)
- {
- return;
- }
- this.getAudioInstance(src, "<preload>", is_music, false);
- };
- Acts.prototype.SetPlaybackRate = function (tag, rate)
- {
- getAudioByTag(tag);
- if (rate < 0.0)
- rate = 0;
- var i, len;
- for (i = 0, len = taggedAudio.length; i < len; i++)
- taggedAudio[i].setPlaybackRate(rate);
- };
- Acts.prototype.Stop = function (tag)
- {
- getAudioByTag(tag);
- var i, len;
- for (i = 0, len = taggedAudio.length; i < len; i++)
- taggedAudio[i].stop();
- };
- Acts.prototype.StopAll = function ()
- {
- var i, len;
- for (i = 0, len = audioInstances.length; i < len; i++)
- audioInstances[i].stop();
- };
- Acts.prototype.SetPaused = function (tag, state)
- {
- getAudioByTag(tag);
- var i, len;
- for (i = 0, len = taggedAudio.length; i < len; i++)
- {
- if (state === 0)
- taggedAudio[i].pause();
- else
- taggedAudio[i].resume();
- }
- };
- Acts.prototype.Seek = function (tag, pos)
- {
- getAudioByTag(tag);
- var i, len;
- for (i = 0, len = taggedAudio.length; i < len; i++)
- {
- taggedAudio[i].seek(pos);
- }
- };
- Acts.prototype.SetSilent = function (s)
- {
- var i, len;
- if (s === 2) // toggling
- s = (silent ? 1 : 0); // choose opposite state
- if (s === 0 && !silent) // setting silent
- {
- for (i = 0, len = audioInstances.length; i < len; i++)
- audioInstances[i].setSilent(true);
- silent = true;
- }
- else if (s === 1 && silent) // setting not silent
- {
- for (i = 0, len = audioInstances.length; i < len; i++)
- audioInstances[i].setSilent(false);
- silent = false;
- }
- };
- Acts.prototype.SetMasterVolume = function (vol)
- {
- masterVolume = dbToLinear(vol);
- var i, len;
- for (i = 0, len = audioInstances.length; i < len; i++)
- audioInstances[i].updateVolume();
- };
- Acts.prototype.AddFilterEffect = function (tag, type, freq, detune, q, gain, mix)
- {
- if (api !== API_WEBAUDIO || type < 0 || type >= filterTypes.length || !context["createBiquadFilter"])
- return;
- tag = tag.toLowerCase();
- mix = mix / 100;
- if (mix < 0) mix = 0;
- if (mix > 1) mix = 1;
- addEffectForTag(tag, new FilterEffect(type, freq, detune, q, gain, mix));
- };
- Acts.prototype.AddDelayEffect = function (tag, delay, gain, mix)
- {
- if (api !== API_WEBAUDIO)
- return;
- tag = tag.toLowerCase();
- mix = mix / 100;
- if (mix < 0) mix = 0;
- if (mix > 1) mix = 1;
- addEffectForTag(tag, new DelayEffect(delay, dbToLinear(gain), mix));
- };
- Acts.prototype.AddFlangerEffect = function (tag, delay, modulation, freq, feedback, mix)
- {
- if (api !== API_WEBAUDIO || !context["createOscillator"])
- return;
- tag = tag.toLowerCase();
- mix = mix / 100;
- if (mix < 0) mix = 0;
- if (mix > 1) mix = 1;
- addEffectForTag(tag, new FlangerEffect(delay / 1000, modulation / 1000, freq, feedback / 100, mix));
- };
- Acts.prototype.AddPhaserEffect = function (tag, freq, detune, q, mod, modfreq, mix)
- {
- if (api !== API_WEBAUDIO || !context["createOscillator"])
- return;
- tag = tag.toLowerCase();
- mix = mix / 100;
- if (mix < 0) mix = 0;
- if (mix > 1) mix = 1;
- addEffectForTag(tag, new PhaserEffect(freq, detune, q, mod, modfreq, mix));
- };
- Acts.prototype.AddConvolutionEffect = function (tag, file, norm, mix)
- {
- if (api !== API_WEBAUDIO || !context["createConvolver"])
- return;
- var doNormalize = (norm === 0);
- var src = this.runtime.files_subfolder + file[0] + (useOgg ? ".ogg" : ".m4a");
- var b = this.getAudioBuffer(src, false);
- tag = tag.toLowerCase();
- mix = mix / 100;
- if (mix < 0) mix = 0;
- if (mix > 1) mix = 1;
- var fx;
- if (b.bufferObject)
- {
- fx = new ConvolveEffect(b.bufferObject, doNormalize, mix, src);
- }
- else
- {
- fx = new ConvolveEffect(null, doNormalize, mix, src);
- b.normalizeWhenReady = doNormalize;
- b.convolveWhenReady = fx;
- }
- addEffectForTag(tag, fx);
- };
- Acts.prototype.AddGainEffect = function (tag, g)
- {
- if (api !== API_WEBAUDIO)
- return;
- tag = tag.toLowerCase();
- addEffectForTag(tag, new GainEffect(dbToLinear(g)));
- };
- Acts.prototype.AddMuteEffect = function (tag)
- {
- if (api !== API_WEBAUDIO)
- return;
- tag = tag.toLowerCase();
- addEffectForTag(tag, new GainEffect(0)); // re-use gain effect with 0 gain
- };
- Acts.prototype.AddTremoloEffect = function (tag, freq, mix)
- {
- if (api !== API_WEBAUDIO || !context["createOscillator"])
- return;
- tag = tag.toLowerCase();
- mix = mix / 100;
- if (mix < 0) mix = 0;
- if (mix > 1) mix = 1;
- addEffectForTag(tag, new TremoloEffect(freq, mix));
- };
- Acts.prototype.AddRingModEffect = function (tag, freq, mix)
- {
- if (api !== API_WEBAUDIO || !context["createOscillator"])
- return;
- tag = tag.toLowerCase();
- mix = mix / 100;
- if (mix < 0) mix = 0;
- if (mix > 1) mix = 1;
- addEffectForTag(tag, new RingModulatorEffect(freq, mix));
- };
- Acts.prototype.AddDistortionEffect = function (tag, threshold, headroom, drive, makeupgain, mix)
- {
- if (api !== API_WEBAUDIO || !context["createWaveShaper"])
- return;
- tag = tag.toLowerCase();
- mix = mix / 100;
- if (mix < 0) mix = 0;
- if (mix > 1) mix = 1;
- addEffectForTag(tag, new DistortionEffect(threshold, headroom, drive, makeupgain, mix));
- };
- Acts.prototype.AddCompressorEffect = function (tag, threshold, knee, ratio, attack, release)
- {
- if (api !== API_WEBAUDIO || !context["createDynamicsCompressor"])
- return;
- tag = tag.toLowerCase();
- addEffectForTag(tag, new CompressorEffect(threshold, knee, ratio, attack / 1000, release / 1000));
- };
- Acts.prototype.AddAnalyserEffect = function (tag, fftSize, smoothing)
- {
- if (api !== API_WEBAUDIO)
- return;
- tag = tag.toLowerCase();
- addEffectForTag(tag, new AnalyserEffect(fftSize, smoothing));
- };
- Acts.prototype.RemoveEffects = function (tag)
- {
- if (api !== API_WEBAUDIO)
- return;
- tag = tag.toLowerCase();
- var i, len, arr;
- if (effects.hasOwnProperty(tag))
- {
- arr = effects[tag];
- if (arr.length)
- {
- for (i = 0, len = arr.length; i < len; i++)
- arr[i].remove();
- cr.clearArray(arr);
- reconnectEffects(tag);
- }
- }
- };
- Acts.prototype.SetEffectParameter = function (tag, index, param, value, ramp, time)
- {
- if (api !== API_WEBAUDIO)
- return;
- tag = tag.toLowerCase();
- index = Math.floor(index);
- var arr;
- if (!effects.hasOwnProperty(tag))
- return;
- arr = effects[tag];
- if (index < 0 || index >= arr.length)
- return;
- arr[index].setParam(param, value, ramp, time);
- };
- Acts.prototype.SetListenerObject = function (obj_)
- {
- if (!obj_ || api !== API_WEBAUDIO)
- return;
- var inst = obj_.getFirstPicked();
- if (!inst)
- return;
- this.listenerTracker.setObject(inst);
- listenerX = inst.x;
- listenerY = inst.y;
- };
- Acts.prototype.SetListenerZ = function (z)
- {
- this.listenerZ = z;
- };
- pluginProto.acts = new Acts();
- function Exps() {};
- Exps.prototype.Duration = function (ret, tag)
- {
- getAudioByTag(tag, true);
- if (taggedAudio.length)
- ret.set_float(taggedAudio[0].getDuration());
- else
- ret.set_float(0);
- };
- Exps.prototype.PlaybackTime = function (ret, tag)
- {
- getAudioByTag(tag, true);
- if (taggedAudio.length)
- ret.set_float(taggedAudio[0].getPlaybackTime());
- else
- ret.set_float(0);
- };
- Exps.prototype.Volume = function (ret, tag)
- {
- getAudioByTag(tag, true);
- if (taggedAudio.length)
- {
- var v = taggedAudio[0].getVolume();
- ret.set_float(linearToDb(v));
- }
- else
- ret.set_float(0);
- };
- Exps.prototype.MasterVolume = function (ret)
- {
- ret.set_float(linearToDb(masterVolume));
- };
- Exps.prototype.EffectCount = function (ret, tag)
- {
- tag = tag.toLowerCase();
- var arr = null;
- if (effects.hasOwnProperty(tag))
- arr = effects[tag];
- ret.set_int(arr ? arr.length : 0);
- };
- function getAnalyser(tag, index)
- {
- var arr = null;
- if (effects.hasOwnProperty(tag))
- arr = effects[tag];
- if (arr && index >= 0 && index < arr.length && arr[index].freqBins)
- return arr[index];
- else
- return null;
- };
- Exps.prototype.AnalyserFreqBinCount = function (ret, tag, index)
- {
- tag = tag.toLowerCase();
- index = Math.floor(index);
- var analyser = getAnalyser(tag, index);
- ret.set_int(analyser ? analyser.node["frequencyBinCount"] : 0);
- };
- Exps.prototype.AnalyserFreqBinAt = function (ret, tag, index, bin)
- {
- tag = tag.toLowerCase();
- index = Math.floor(index);
- bin = Math.floor(bin);
- var analyser = getAnalyser(tag, index);
- if (!analyser)
- ret.set_float(0);
- else if (bin < 0 || bin >= analyser.node["frequencyBinCount"])
- ret.set_float(0);
- else
- ret.set_float(analyser.freqBins[bin]);
- };
- Exps.prototype.AnalyserPeakLevel = function (ret, tag, index)
- {
- tag = tag.toLowerCase();
- index = Math.floor(index);
- var analyser = getAnalyser(tag, index);
- if (analyser)
- ret.set_float(analyser.peak);
- else
- ret.set_float(0);
- };
- Exps.prototype.AnalyserRMSLevel = function (ret, tag, index)
- {
- tag = tag.toLowerCase();
- index = Math.floor(index);
- var analyser = getAnalyser(tag, index);
- if (analyser)
- ret.set_float(analyser.rms);
- else
- ret.set_float(0);
- };
- pluginProto.exps = new Exps();
- }());
- ;
- ;
- cr.plugins_.Browser = function(runtime)
- {
- this.runtime = runtime;
- };
- (function ()
- {
- var pluginProto = cr.plugins_.Browser.prototype;
- pluginProto.Type = function(plugin)
- {
- this.plugin = plugin;
- this.runtime = plugin.runtime;
- };
- var typeProto = pluginProto.Type.prototype;
- typeProto.onCreate = function()
- {
- };
- pluginProto.Instance = function(type)
- {
- this.type = type;
- this.runtime = type.runtime;
- };
- var instanceProto = pluginProto.Instance.prototype;
- instanceProto.onCreate = function()
- {
- var self = this;
- window.addEventListener("resize", function () {
- self.runtime.trigger(cr.plugins_.Browser.prototype.cnds.OnResize, self);
- });
- if (typeof navigator.onLine !== "undefined")
- {
- window.addEventListener("online", function() {
- self.runtime.trigger(cr.plugins_.Browser.prototype.cnds.OnOnline, self);
- });
- window.addEventListener("offline", function() {
- self.runtime.trigger(cr.plugins_.Browser.prototype.cnds.OnOffline, self);
- });
- }
- if (typeof window.applicationCache !== "undefined")
- {
- window.applicationCache.addEventListener('updateready', function() {
- self.runtime.loadingprogress = 1;
- self.runtime.trigger(cr.plugins_.Browser.prototype.cnds.OnUpdateReady, self);
- });
- window.applicationCache.addEventListener('progress', function(e) {
- self.runtime.loadingprogress = e["loaded"] / e["total"];
- });
- }
- if (!this.runtime.isDirectCanvas)
- {
- document.addEventListener("appMobi.device.update.available", function() {
- self.runtime.trigger(cr.plugins_.Browser.prototype.cnds.OnUpdateReady, self);
- });
- document.addEventListener("backbutton", function() {
- self.runtime.trigger(cr.plugins_.Browser.prototype.cnds.OnBackButton, self);
- });
- document.addEventListener("menubutton", function() {
- self.runtime.trigger(cr.plugins_.Browser.prototype.cnds.OnMenuButton, self);
- });
- document.addEventListener("searchbutton", function() {
- self.runtime.trigger(cr.plugins_.Browser.prototype.cnds.OnSearchButton, self);
- });
- document.addEventListener("tizenhwkey", function (e) {
- var ret;
- switch (e["keyName"]) {
- case "back":
- ret = self.runtime.trigger(cr.plugins_.Browser.prototype.cnds.OnBackButton, self);
- if (!ret)
- {
- if (window["tizen"])
- window["tizen"]["application"]["getCurrentApplication"]()["exit"]();
- }
- break;
- case "menu":
- ret = self.runtime.trigger(cr.plugins_.Browser.prototype.cnds.OnMenuButton, self);
- if (!ret)
- e.preventDefault();
- break;
- }
- });
- }
- if (this.runtime.isWindowsPhone81)
- {
- WinJS["Application"]["onbackclick"] = function (e)
- {
- return !!self.runtime.trigger(cr.plugins_.Browser.prototype.cnds.OnBackButton, self);
- };
- }
- this.runtime.addSuspendCallback(function(s) {
- if (s)
- {
- self.runtime.trigger(cr.plugins_.Browser.prototype.cnds.OnPageHidden, self);
- }
- else
- {
- self.runtime.trigger(cr.plugins_.Browser.prototype.cnds.OnPageVisible, self);
- }
- });
- this.is_arcade = (typeof window["is_scirra_arcade"] !== "undefined");
- };
- var batteryManager = null;
- var loadedBatteryManager = false;
- function maybeLoadBatteryManager()
- {
- if (loadedBatteryManager)
- return;
- if (!navigator["getBattery"])
- return;
- var promise = navigator["getBattery"]();
- loadedBatteryManager = true;
- if (promise)
- {
- promise.then(function (manager) {
- batteryManager = manager;
- });
- }
- };
- function Cnds() {};
- Cnds.prototype.CookiesEnabled = function()
- {
- return navigator ? navigator.cookieEnabled : false;
- };
- Cnds.prototype.IsOnline = function()
- {
- return navigator ? navigator.onLine : false;
- };
- Cnds.prototype.HasJava = function()
- {
- return navigator ? navigator.javaEnabled() : false;
- };
- Cnds.prototype.OnOnline = function()
- {
- return true;
- };
- Cnds.prototype.OnOffline = function()
- {
- return true;
- };
- Cnds.prototype.IsDownloadingUpdate = function ()
- {
- if (typeof window["applicationCache"] === "undefined")
- return false;
- else
- return window["applicationCache"]["status"] === window["applicationCache"]["DOWNLOADING"];
- };
- Cnds.prototype.OnUpdateReady = function ()
- {
- return true;
- };
- Cnds.prototype.PageVisible = function ()
- {
- return !this.runtime.isSuspended;
- };
- Cnds.prototype.OnPageVisible = function ()
- {
- return true;
- };
- Cnds.prototype.OnPageHidden = function ()
- {
- return true;
- };
- Cnds.prototype.OnResize = function ()
- {
- return true;
- };
- Cnds.prototype.IsFullscreen = function ()
- {
- return !!(document["mozFullScreen"] || document["webkitIsFullScreen"] || document["fullScreen"] || this.runtime.isNodeFullscreen);
- };
- Cnds.prototype.OnBackButton = function ()
- {
- return true;
- };
- Cnds.prototype.OnMenuButton = function ()
- {
- return true;
- };
- Cnds.prototype.OnSearchButton = function ()
- {
- return true;
- };
- Cnds.prototype.IsMetered = function ()
- {
- var connection = navigator["connection"] || navigator["mozConnection"] || navigator["webkitConnection"];
- if (!connection)
- return false;
- return !!connection["metered"];
- };
- Cnds.prototype.IsCharging = function ()
- {
- var battery = navigator["battery"] || navigator["mozBattery"] || navigator["webkitBattery"];
- if (battery)
- {
- return !!battery["charging"]
- }
- else
- {
- maybeLoadBatteryManager();
- if (batteryManager)
- {
- return !!batteryManager["charging"];
- }
- else
- {
- return true; // if unknown, default to charging (powered)
- }
- }
- };
- Cnds.prototype.IsPortraitLandscape = function (p)
- {
- var current = (window.innerWidth <= window.innerHeight ? 0 : 1);
- return current === p;
- };
- Cnds.prototype.SupportsFullscreen = function ()
- {
- if (this.runtime.isNodeWebkit)
- return true;
- var elem = this.runtime.canvasdiv || this.runtime.canvas;
- return !!(elem["requestFullscreen"] || elem["mozRequestFullScreen"] || elem["msRequestFullscreen"] || elem["webkitRequestFullScreen"]);
- };
- pluginProto.cnds = new Cnds();
- function Acts() {};
- Acts.prototype.Alert = function (msg)
- {
- if (!this.runtime.isDomFree)
- alert(msg.toString());
- };
- Acts.prototype.Close = function ()
- {
- if (this.runtime.isCocoonJs)
- CocoonJS["App"]["forceToFinish"]();
- else if (window["tizen"])
- window["tizen"]["application"]["getCurrentApplication"]()["exit"]();
- else if (navigator["app"] && navigator["app"]["exitApp"])
- navigator["app"]["exitApp"]();
- else if (navigator["device"] && navigator["device"]["exitApp"])
- navigator["device"]["exitApp"]();
- else if (!this.is_arcade && !this.runtime.isDomFree)
- window.close();
- };
- Acts.prototype.Focus = function ()
- {
- if (this.runtime.isNodeWebkit)
- {
- var win = window["nwgui"]["Window"]["get"]();
- win["focus"]();
- }
- else if (!this.is_arcade && !this.runtime.isDomFree)
- window.focus();
- };
- Acts.prototype.Blur = function ()
- {
- if (this.runtime.isNodeWebkit)
- {
- var win = window["nwgui"]["Window"]["get"]();
- win["blur"]();
- }
- else if (!this.is_arcade && !this.runtime.isDomFree)
- window.blur();
- };
- Acts.prototype.GoBack = function ()
- {
- if (navigator["app"] && navigator["app"]["backHistory"])
- navigator["app"]["backHistory"]();
- else if (!this.is_arcade && !this.runtime.isDomFree && window.back)
- window.back();
- };
- Acts.prototype.GoForward = function ()
- {
- if (!this.is_arcade && !this.runtime.isDomFree && window.forward)
- window.forward();
- };
- Acts.prototype.GoHome = function ()
- {
- if (!this.is_arcade && !this.runtime.isDomFree && window.home)
- window.home();
- };
- Acts.prototype.GoToURL = function (url, target)
- {
- if (this.runtime.isCocoonJs)
- CocoonJS["App"]["openURL"](url);
- else if (this.runtime.isEjecta)
- ejecta["openURL"](url);
- else if (this.runtime.isWinJS)
- Windows["System"]["Launcher"]["launchUriAsync"](new Windows["Foundation"]["Uri"](url));
- else if (navigator["app"] && navigator["app"]["loadUrl"])
- navigator["app"]["loadUrl"](url, { "openExternal": true });
- else if (this.runtime.isCordova)
- window.open(url, "_system");
- else if (!this.is_arcade && !this.runtime.isDomFree)
- {
- if (target === 2 && !this.is_arcade) // top
- window.top.location = url;
- else if (target === 1 && !this.is_arcade) // parent
- window.parent.location = url;
- else // self
- window.location = url;
- }
- };
- Acts.prototype.GoToURLWindow = function (url, tag)
- {
- if (this.runtime.isCocoonJs)
- CocoonJS["App"]["openURL"](url);
- else if (this.runtime.isEjecta)
- ejecta["openURL"](url);
- else if (this.runtime.isWinJS)
- Windows["System"]["Launcher"]["launchUriAsync"](new Windows["Foundation"]["Uri"](url));
- else if (navigator["app"] && navigator["app"]["loadUrl"])
- navigator["app"]["loadUrl"](url, { "openExternal": true });
- else if (this.runtime.isCordova)
- window.open(url, "_system");
- else if (!this.is_arcade && !this.runtime.isDomFree)
- window.open(url, tag);
- };
- Acts.prototype.Reload = function ()
- {
- if (!this.is_arcade && !this.runtime.isDomFree)
- window.location.reload();
- };
- var firstRequestFullscreen = true;
- var crruntime = null;
- function onFullscreenError(e)
- {
- if (console && console.warn)
- console.warn("Fullscreen request failed: ", e);
- crruntime["setSize"](window.innerWidth, window.innerHeight);
- };
- Acts.prototype.RequestFullScreen = function (stretchmode)
- {
- if (this.runtime.isDomFree)
- {
- cr.logexport("[Construct 2] Requesting fullscreen is not supported on this platform - the request has been ignored");
- return;
- }
- if (stretchmode >= 2)
- stretchmode += 1;
- if (stretchmode === 6)
- stretchmode = 2;
- if (this.runtime.isNodeWebkit)
- {
- if (this.runtime.isDebug)
- {
- debuggerFullscreen(true);
- }
- else if (!this.runtime.isNodeFullscreen && window["nwgui"])
- {
- window["nwgui"]["Window"]["get"]()["enterFullscreen"]();
- this.runtime.isNodeFullscreen = true;
- this.runtime.fullscreen_scaling = (stretchmode >= 2 ? stretchmode : 0);
- }
- }
- else
- {
- if (document["mozFullScreen"] || document["webkitIsFullScreen"] || !!document["msFullscreenElement"] || document["fullScreen"] || document["fullScreenElement"])
- {
- return;
- }
- this.runtime.fullscreen_scaling = (stretchmode >= 2 ? stretchmode : 0);
- var elem = this.runtime.canvasdiv || this.runtime.canvas;
- if (firstRequestFullscreen)
- {
- firstRequestFullscreen = false;
- crruntime = this.runtime;
- elem.addEventListener("mozfullscreenerror", onFullscreenError);
- elem.addEventListener("webkitfullscreenerror", onFullscreenError);
- elem.addEventListener("MSFullscreenError", onFullscreenError);
- elem.addEventListener("fullscreenerror", onFullscreenError);
- }
- if (elem["requestFullscreen"])
- elem["requestFullscreen"]();
- else if (elem["mozRequestFullScreen"])
- elem["mozRequestFullScreen"]();
- else if (elem["msRequestFullscreen"])
- elem["msRequestFullscreen"]();
- else if (elem["webkitRequestFullScreen"])
- {
- if (typeof Element !== "undefined" && typeof Element["ALLOW_KEYBOARD_INPUT"] !== "undefined")
- elem["webkitRequestFullScreen"](Element["ALLOW_KEYBOARD_INPUT"]);
- else
- elem["webkitRequestFullScreen"]();
- }
- }
- };
- Acts.prototype.CancelFullScreen = function ()
- {
- if (this.runtime.isDomFree)
- {
- cr.logexport("[Construct 2] Exiting fullscreen is not supported on this platform - the request has been ignored");
- return;
- }
- if (this.runtime.isNodeWebkit)
- {
- if (this.runtime.isDebug)
- {
- debuggerFullscreen(false);
- }
- else if (this.runtime.isNodeFullscreen && window["nwgui"])
- {
- window["nwgui"]["Window"]["get"]()["leaveFullscreen"]();
- this.runtime.isNodeFullscreen = false;
- }
- }
- else
- {
- if (document["exitFullscreen"])
- document["exitFullscreen"]();
- else if (document["mozCancelFullScreen"])
- document["mozCancelFullScreen"]();
- else if (document["msExitFullscreen"])
- document["msExitFullscreen"]();
- else if (document["webkitCancelFullScreen"])
- document["webkitCancelFullScreen"]();
- }
- };
- Acts.prototype.Vibrate = function (pattern_)
- {
- try {
- var arr = pattern_.split(",");
- var i, len;
- for (i = 0, len = arr.length; i < len; i++)
- {
- arr[i] = parseInt(arr[i], 10);
- }
- if (navigator["vibrate"])
- navigator["vibrate"](arr);
- else if (navigator["mozVibrate"])
- navigator["mozVibrate"](arr);
- else if (navigator["webkitVibrate"])
- navigator["webkitVibrate"](arr);
- else if (navigator["msVibrate"])
- navigator["msVibrate"](arr);
- }
- catch (e) {}
- };
- Acts.prototype.InvokeDownload = function (url_, filename_)
- {
- var a = document.createElement("a");
- if (typeof a["download"] === "undefined")
- {
- window.open(url_);
- }
- else
- {
- var body = document.getElementsByTagName("body")[0];
- a.textContent = filename_;
- a.href = url_;
- a["download"] = filename_;
- body.appendChild(a);
- var clickEvent = document.createEvent("MouseEvent");
- clickEvent.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
- a.dispatchEvent(clickEvent);
- body.removeChild(a);
- }
- };
- Acts.prototype.InvokeDownloadString = function (str_, mimetype_, filename_)
- {
- var datauri = "data:" + mimetype_ + "," + encodeURIComponent(str_);
- var a = document.createElement("a");
- if (typeof a["download"] === "undefined")
- {
- window.open(datauri);
- }
- else
- {
- var body = document.getElementsByTagName("body")[0];
- a.textContent = filename_;
- a.href = datauri;
- a["download"] = filename_;
- body.appendChild(a);
- var clickEvent = document.createEvent("MouseEvent");
- clickEvent.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
- a.dispatchEvent(clickEvent);
- body.removeChild(a);
- }
- };
- Acts.prototype.ConsoleLog = function (type_, msg_)
- {
- if (typeof console === "undefined")
- return;
- if (type_ === 0 && console.log)
- console.log(msg_.toString());
- if (type_ === 1 && console.warn)
- console.warn(msg_.toString());
- if (type_ === 2 && console.error)
- console.error(msg_.toString());
- };
- Acts.prototype.ConsoleGroup = function (name_)
- {
- if (console && console.group)
- console.group(name_);
- };
- Acts.prototype.ConsoleGroupEnd = function ()
- {
- if (console && console.groupEnd)
- console.groupEnd();
- };
- Acts.prototype.ExecJs = function (js_)
- {
- try {
- if (eval)
- eval(js_);
- }
- catch (e)
- {
- if (console && console.error)
- console.error("Error executing Javascript: ", e);
- }
- };
- var orientations = [
- "portrait",
- "landscape",
- "portrait-primary",
- "portrait-secondary",
- "landscape-primary",
- "landscape-secondary"
- ];
- Acts.prototype.LockOrientation = function (o)
- {
- o = Math.floor(o);
- if (o < 0 || o >= orientations.length)
- return;
- this.runtime.autoLockOrientation = false;
- var orientation = orientations[o];
- if (screen["orientation"] && screen["orientation"]["lock"])
- screen["orientation"]["lock"](orientation);
- else if (screen["lockOrientation"])
- screen["lockOrientation"](orientation);
- else if (screen["webkitLockOrientation"])
- screen["webkitLockOrientation"](orientation);
- else if (screen["mozLockOrientation"])
- screen["mozLockOrientation"](orientation);
- else if (screen["msLockOrientation"])
- screen["msLockOrientation"](orientation);
- };
- Acts.prototype.UnlockOrientation = function ()
- {
- this.runtime.autoLockOrientation = false;
- if (screen["orientation"] && screen["orientation"]["unlock"])
- screen["orientation"]["unlock"]();
- else if (screen["unlockOrientation"])
- screen["unlockOrientation"]();
- else if (screen["webkitUnlockOrientation"])
- screen["webkitUnlockOrientation"]();
- else if (screen["mozUnlockOrientation"])
- screen["mozUnlockOrientation"]();
- else if (screen["msUnlockOrientation"])
- screen["msUnlockOrientation"]();
- };
- pluginProto.acts = new Acts();
- function Exps() {};
- Exps.prototype.URL = function (ret)
- {
- ret.set_string(this.runtime.isDomFree ? "" : window.location.toString());
- };
- Exps.prototype.Protocol = function (ret)
- {
- ret.set_string(this.runtime.isDomFree ? "" : window.location.protocol);
- };
- Exps.prototype.Domain = function (ret)
- {
- ret.set_string(this.runtime.isDomFree ? "" : window.location.hostname);
- };
- Exps.prototype.PathName = function (ret)
- {
- ret.set_string(this.runtime.isDomFree ? "" : window.location.pathname);
- };
- Exps.prototype.Hash = function (ret)
- {
- ret.set_string(this.runtime.isDomFree ? "" : window.location.hash);
- };
- Exps.prototype.Referrer = function (ret)
- {
- ret.set_string(this.runtime.isDomFree ? "" : document.referrer);
- };
- Exps.prototype.Title = function (ret)
- {
- ret.set_string(this.runtime.isDomFree ? "" : document.title);
- };
- Exps.prototype.Name = function (ret)
- {
- ret.set_string(this.runtime.isDomFree ? "" : navigator.appName);
- };
- Exps.prototype.Version = function (ret)
- {
- ret.set_string(this.runtime.isDomFree ? "" : navigator.appVersion);
- };
- Exps.prototype.Language = function (ret)
- {
- if (navigator && navigator.language)
- ret.set_string(navigator.language);
- else
- ret.set_string("");
- };
- Exps.prototype.Platform = function (ret)
- {
- ret.set_string(this.runtime.isDomFree ? "" : navigator.platform);
- };
- Exps.prototype.Product = function (ret)
- {
- if (navigator && navigator.product)
- ret.set_string(navigator.product);
- else
- ret.set_string("");
- };
- Exps.prototype.Vendor = function (ret)
- {
- if (navigator && navigator.vendor)
- ret.set_string(navigator.vendor);
- else
- ret.set_string("");
- };
- Exps.prototype.UserAgent = function (ret)
- {
- ret.set_string(this.runtime.isDomFree ? "" : navigator.userAgent);
- };
- Exps.prototype.QueryString = function (ret)
- {
- ret.set_string(this.runtime.isDomFree ? "" : window.location.search);
- };
- Exps.prototype.QueryParam = function (ret, paramname)
- {
- if (this.runtime.isDomFree)
- {
- ret.set_string("");
- return;
- }
- var match = RegExp('[?&]' + paramname + '=([^&]*)').exec(window.location.search);
- if (match)
- ret.set_string(decodeURIComponent(match[1].replace(/\+/g, ' ')));
- else
- ret.set_string("");
- };
- Exps.prototype.Bandwidth = function (ret)
- {
- var connection = navigator["connection"] || navigator["mozConnection"] || navigator["webkitConnection"];
- if (!connection)
- ret.set_float(Number.POSITIVE_INFINITY);
- else
- {
- if (typeof connection["bandwidth"] !== "undefined")
- ret.set_float(connection["bandwidth"]);
- else if (typeof connection["downlinkMax"] !== "undefined")
- ret.set_float(connection["downlinkMax"]);
- else
- ret.set_float(Number.POSITIVE_INFINITY);
- }
- };
- Exps.prototype.ConnectionType = function (ret)
- {
- var connection = navigator["connection"] || navigator["mozConnection"] || navigator["webkitConnection"];
- if (!connection)
- ret.set_string("unknown");
- else
- {
- ret.set_string(connection["type"] || "unknown");
- }
- };
- Exps.prototype.BatteryLevel = function (ret)
- {
- var battery = navigator["battery"] || navigator["mozBattery"] || navigator["webkitBattery"];
- if (battery)
- {
- ret.set_float(battery["level"]);
- }
- else
- {
- maybeLoadBatteryManager();
- if (batteryManager)
- {
- ret.set_float(batteryManager["level"]);
- }
- else
- {
- ret.set_float(1); // not supported/unknown: assume charged
- }
- }
- };
- Exps.prototype.BatteryTimeLeft = function (ret)
- {
- var battery = navigator["battery"] || navigator["mozBattery"] || navigator["webkitBattery"];
- if (battery)
- {
- ret.set_float(battery["dischargingTime"]);
- }
- else
- {
- maybeLoadBatteryManager();
- if (batteryManager)
- {
- ret.set_float(batteryManager["dischargingTime"]);
- }
- else
- {
- ret.set_float(Number.POSITIVE_INFINITY); // not supported/unknown: assume infinite time left
- }
- }
- };
- Exps.prototype.ExecJS = function (ret, js_)
- {
- if (!eval)
- {
- ret.set_any(0);
- return;
- }
- var result = 0;
- try {
- result = eval(js_);
- }
- catch (e)
- {
- if (console && console.error)
- console.error("Error executing Javascript: ", e);
- }
- if (typeof result === "number")
- ret.set_any(result);
- else if (typeof result === "string")
- ret.set_any(result);
- else if (typeof result === "boolean")
- ret.set_any(result ? 1 : 0);
- else
- ret.set_any(0);
- };
- Exps.prototype.ScreenWidth = function (ret)
- {
- ret.set_int(screen.width);
- };
- Exps.prototype.ScreenHeight = function (ret)
- {
- ret.set_int(screen.height);
- };
- Exps.prototype.DevicePixelRatio = function (ret)
- {
- ret.set_float(this.runtime.devicePixelRatio);
- };
- pluginProto.exps = new Exps();
- }());
- ;
- ;
- cr.plugins_.Function = function(runtime)
- {
- this.runtime = runtime;
- };
- (function ()
- {
- var pluginProto = cr.plugins_.Function.prototype;
- pluginProto.Type = function(plugin)
- {
- this.plugin = plugin;
- this.runtime = plugin.runtime;
- };
- var typeProto = pluginProto.Type.prototype;
- typeProto.onCreate = function()
- {
- };
- pluginProto.Instance = function(type)
- {
- this.type = type;
- this.runtime = type.runtime;
- };
- var instanceProto = pluginProto.Instance.prototype;
- var funcStack = [];
- var funcStackPtr = -1;
- var isInPreview = false; // set in onCreate
- function FuncStackEntry()
- {
- this.name = "";
- this.retVal = 0;
- this.params = [];
- };
- function pushFuncStack()
- {
- funcStackPtr++;
- if (funcStackPtr === funcStack.length)
- funcStack.push(new FuncStackEntry());
- return funcStack[funcStackPtr];
- };
- function getCurrentFuncStack()
- {
- if (funcStackPtr < 0)
- return null;
- return funcStack[funcStackPtr];
- };
- function getOneAboveFuncStack()
- {
- if (!funcStack.length)
- return null;
- var i = funcStackPtr + 1;
- if (i >= funcStack.length)
- i = funcStack.length - 1;
- return funcStack[i];
- };
- function popFuncStack()
- {
- ;
- funcStackPtr--;
- };
- instanceProto.onCreate = function()
- {
- isInPreview = (typeof cr_is_preview !== "undefined");
- var self = this;
- window["c2_callFunction"] = function (name_, params_)
- {
- var i, len, v;
- var fs = pushFuncStack();
- fs.name = name_.toLowerCase();
- fs.retVal = 0;
- if (params_)
- {
- fs.params.length = params_.length;
- for (i = 0, len = params_.length; i < len; ++i)
- {
- v = params_[i];
- if (typeof v === "number" || typeof v === "string")
- fs.params[i] = v;
- else if (typeof v === "boolean")
- fs.params[i] = (v ? 1 : 0);
- else
- fs.params[i] = 0;
- }
- }
- else
- {
- cr.clearArray(fs.params);
- }
- self.runtime.trigger(cr.plugins_.Function.prototype.cnds.OnFunction, self, fs.name);
- popFuncStack();
- return fs.retVal;
- };
- };
- function Cnds() {};
- Cnds.prototype.OnFunction = function (name_)
- {
- var fs = getCurrentFuncStack();
- if (!fs)
- return false;
- return cr.equals_nocase(name_, fs.name);
- };
- Cnds.prototype.CompareParam = function (index_, cmp_, value_)
- {
- var fs = getCurrentFuncStack();
- if (!fs)
- return false;
- index_ = cr.floor(index_);
- if (index_ < 0 || index_ >= fs.params.length)
- return false;
- return cr.do_cmp(fs.params[index_], cmp_, value_);
- };
- pluginProto.cnds = new Cnds();
- function Acts() {};
- Acts.prototype.CallFunction = function (name_, params_)
- {
- var fs = pushFuncStack();
- fs.name = name_.toLowerCase();
- fs.retVal = 0;
- cr.shallowAssignArray(fs.params, params_);
- var ran = this.runtime.trigger(cr.plugins_.Function.prototype.cnds.OnFunction, this, fs.name);
- if (isInPreview && !ran)
- {
- ;
- }
- popFuncStack();
- };
- Acts.prototype.SetReturnValue = function (value_)
- {
- var fs = getCurrentFuncStack();
- if (fs)
- fs.retVal = value_;
- else
- ;
- };
- Acts.prototype.CallExpression = function (unused)
- {
- };
- pluginProto.acts = new Acts();
- function Exps() {};
- Exps.prototype.ReturnValue = function (ret)
- {
- var fs = getOneAboveFuncStack();
- if (fs)
- ret.set_any(fs.retVal);
- else
- ret.set_int(0);
- };
- Exps.prototype.ParamCount = function (ret)
- {
- var fs = getCurrentFuncStack();
- if (fs)
- ret.set_int(fs.params.length);
- else
- {
- ;
- ret.set_int(0);
- }
- };
- Exps.prototype.Param = function (ret, index_)
- {
- index_ = cr.floor(index_);
- var fs = getCurrentFuncStack();
- if (fs)
- {
- if (index_ >= 0 && index_ < fs.params.length)
- {
- ret.set_any(fs.params[index_]);
- }
- else
- {
- ;
- ret.set_int(0);
- }
- }
- else
- {
- ;
- ret.set_int(0);
- }
- };
- Exps.prototype.Call = function (ret, name_)
- {
- var fs = pushFuncStack();
- fs.name = name_.toLowerCase();
- fs.retVal = 0;
- cr.clearArray(fs.params);
- var i, len;
- for (i = 2, len = arguments.length; i < len; i++)
- fs.params.push(arguments[i]);
- var ran = this.runtime.trigger(cr.plugins_.Function.prototype.cnds.OnFunction, this, fs.name);
- if (isInPreview && !ran)
- {
- ;
- }
- popFuncStack();
- ret.set_any(fs.retVal);
- };
- pluginProto.exps = new Exps();
- }());
- ;
- ;
- cr.plugins_.Keyboard = function(runtime)
- {
- this.runtime = runtime;
- };
- (function ()
- {
- var pluginProto = cr.plugins_.Keyboard.prototype;
- pluginProto.Type = function(plugin)
- {
- this.plugin = plugin;
- this.runtime = plugin.runtime;
- };
- var typeProto = pluginProto.Type.prototype;
- typeProto.onCreate = function()
- {
- };
- pluginProto.Instance = function(type)
- {
- this.type = type;
- this.runtime = type.runtime;
- this.keyMap = new Array(256); // stores key up/down state
- this.usedKeys = new Array(256);
- this.triggerKey = 0;
- };
- var instanceProto = pluginProto.Instance.prototype;
- instanceProto.onCreate = function()
- {
- var self = this;
- if (!this.runtime.isDomFree)
- {
- jQuery(document).keydown(
- function(info) {
- self.onKeyDown(info);
- }
- );
- jQuery(document).keyup(
- function(info) {
- self.onKeyUp(info);
- }
- );
- }
- };
- var keysToBlockWhenFramed = [32, 33, 34, 35, 36, 37, 38, 39, 40, 44];
- instanceProto.onKeyDown = function (info)
- {
- var alreadyPreventedDefault = false;
- if (window != window.top && keysToBlockWhenFramed.indexOf(info.which) > -1)
- {
- info.preventDefault();
- alreadyPreventedDefault = true;
- info.stopPropagation();
- }
- if (this.keyMap[info.which])
- {
- if (this.usedKeys[info.which] && !alreadyPreventedDefault)
- info.preventDefault();
- return;
- }
- this.keyMap[info.which] = true;
- this.triggerKey = info.which;
- this.runtime.isInUserInputEvent = true;
- this.runtime.trigger(cr.plugins_.Keyboard.prototype.cnds.OnAnyKey, this);
- var eventRan = this.runtime.trigger(cr.plugins_.Keyboard.prototype.cnds.OnKey, this);
- var eventRan2 = this.runtime.trigger(cr.plugins_.Keyboard.prototype.cnds.OnKeyCode, this);
- this.runtime.isInUserInputEvent = false;
- if (eventRan || eventRan2)
- {
- this.usedKeys[info.which] = true;
- if (!alreadyPreventedDefault)
- info.preventDefault();
- }
- };
- instanceProto.onKeyUp = function (info)
- {
- this.keyMap[info.which] = false;
- this.triggerKey = info.which;
- this.runtime.isInUserInputEvent = true;
- this.runtime.trigger(cr.plugins_.Keyboard.prototype.cnds.OnAnyKeyReleased, this);
- var eventRan = this.runtime.trigger(cr.plugins_.Keyboard.prototype.cnds.OnKeyReleased, this);
- var eventRan2 = this.runtime.trigger(cr.plugins_.Keyboard.prototype.cnds.OnKeyCodeReleased, this);
- this.runtime.isInUserInputEvent = false;
- if (eventRan || eventRan2 || this.usedKeys[info.which])
- {
- this.usedKeys[info.which] = true;
- info.preventDefault();
- }
- };
- instanceProto.saveToJSON = function ()
- {
- return { "triggerKey": this.triggerKey };
- };
- instanceProto.loadFromJSON = function (o)
- {
- this.triggerKey = o["triggerKey"];
- };
- function Cnds() {};
- Cnds.prototype.IsKeyDown = function(key)
- {
- return this.keyMap[key];
- };
- Cnds.prototype.OnKey = function(key)
- {
- return (key === this.triggerKey);
- };
- Cnds.prototype.OnAnyKey = function(key)
- {
- return true;
- };
- Cnds.prototype.OnAnyKeyReleased = function(key)
- {
- return true;
- };
- Cnds.prototype.OnKeyReleased = function(key)
- {
- return (key === this.triggerKey);
- };
- Cnds.prototype.IsKeyCodeDown = function(key)
- {
- key = Math.floor(key);
- if (key < 0 || key >= this.keyMap.length)
- return false;
- return this.keyMap[key];
- };
- Cnds.prototype.OnKeyCode = function(key)
- {
- return (key === this.triggerKey);
- };
- Cnds.prototype.OnKeyCodeReleased = function(key)
- {
- return (key === this.triggerKey);
- };
- pluginProto.cnds = new Cnds();
- function Acts() {};
- pluginProto.acts = new Acts();
- function Exps() {};
- Exps.prototype.LastKeyCode = function (ret)
- {
- ret.set_int(this.triggerKey);
- };
- function fixedStringFromCharCode(kc)
- {
- kc = Math.floor(kc);
- switch (kc) {
- case 8: return "backspace";
- case 9: return "tab";
- case 13: return "enter";
- case 16: return "shift";
- case 17: return "control";
- case 18: return "alt";
- case 19: return "pause";
- case 20: return "capslock";
- case 27: return "esc";
- case 33: return "pageup";
- case 34: return "pagedown";
- case 35: return "end";
- case 36: return "home";
- case 37: return "←";
- case 38: return "↑";
- case 39: return "→";
- case 40: return "↓";
- case 45: return "insert";
- case 46: return "del";
- case 91: return "left window key";
- case 92: return "right window key";
- case 93: return "select";
- case 96: return "numpad 0";
- case 97: return "numpad 1";
- case 98: return "numpad 2";
- case 99: return "numpad 3";
- case 100: return "numpad 4";
- case 101: return "numpad 5";
- case 102: return "numpad 6";
- case 103: return "numpad 7";
- case 104: return "numpad 8";
- case 105: return "numpad 9";
- case 106: return "numpad *";
- case 107: return "numpad +";
- case 109: return "numpad -";
- case 110: return "numpad .";
- case 111: return "numpad /";
- case 112: return "F1";
- case 113: return "F2";
- case 114: return "F3";
- case 115: return "F4";
- case 116: return "F5";
- case 117: return "F6";
- case 118: return "F7";
- case 119: return "F8";
- case 120: return "F9";
- case 121: return "F10";
- case 122: return "F11";
- case 123: return "F12";
- case 144: return "numlock";
- case 145: return "scroll lock";
- case 186: return ";";
- case 187: return "=";
- case 188: return ",";
- case 189: return "-";
- case 190: return ".";
- case 191: return "/";
- case 192: return "'";
- case 219: return "[";
- case 220: return "\\";
- case 221: return "]";
- case 222: return "#";
- case 223: return "`";
- default: return String.fromCharCode(kc);
- }
- };
- Exps.prototype.StringFromKeyCode = function (ret, kc)
- {
- ret.set_string(fixedStringFromCharCode(kc));
- };
- pluginProto.exps = new Exps();
- }());
- ;
- ;
- cr.plugins_.Mouse = function(runtime)
- {
- this.runtime = runtime;
- };
- (function ()
- {
- var pluginProto = cr.plugins_.Mouse.prototype;
- pluginProto.Type = function(plugin)
- {
- this.plugin = plugin;
- this.runtime = plugin.runtime;
- };
- var typeProto = pluginProto.Type.prototype;
- typeProto.onCreate = function()
- {
- };
- pluginProto.Instance = function(type)
- {
- this.type = type;
- this.runtime = type.runtime;
- this.buttonMap = new Array(4); // mouse down states
- this.mouseXcanvas = 0; // mouse position relative to canvas
- this.mouseYcanvas = 0;
- this.triggerButton = 0;
- this.triggerType = 0;
- this.triggerDir = 0;
- this.handled = false;
- };
- var instanceProto = pluginProto.Instance.prototype;
- instanceProto.onCreate = function()
- {
- var self = this;
- if (!this.runtime.isDomFree)
- {
- jQuery(document).mousemove(
- function(info) {
- self.onMouseMove(info);
- }
- );
- jQuery(document).mousedown(
- function(info) {
- self.onMouseDown(info);
- }
- );
- jQuery(document).mouseup(
- function(info) {
- self.onMouseUp(info);
- }
- );
- jQuery(document).dblclick(
- function(info) {
- self.onDoubleClick(info);
- }
- );
- var wheelevent = function(info) {
- self.onWheel(info);
- };
- document.addEventListener("mousewheel", wheelevent, false);
- document.addEventListener("DOMMouseScroll", wheelevent, false);
- }
- };
- var dummyoffset = {left: 0, top: 0};
- instanceProto.onMouseMove = function(info)
- {
- var offset = this.runtime.isDomFree ? dummyoffset : jQuery(this.runtime.canvas).offset();
- this.mouseXcanvas = info.pageX - offset.left;
- this.mouseYcanvas = info.pageY - offset.top;
- };
- instanceProto.mouseInGame = function ()
- {
- if (this.runtime.fullscreen_mode > 0)
- return true;
- return this.mouseXcanvas >= 0 && this.mouseYcanvas >= 0
- && this.mouseXcanvas < this.runtime.width && this.mouseYcanvas < this.runtime.height;
- };
- instanceProto.onMouseDown = function(info)
- {
- if (!this.mouseInGame())
- return;
- this.buttonMap[info.which] = true;
- this.runtime.isInUserInputEvent = true;
- this.runtime.trigger(cr.plugins_.Mouse.prototype.cnds.OnAnyClick, this);
- this.triggerButton = info.which - 1; // 1-based
- this.triggerType = 0; // single click
- this.runtime.trigger(cr.plugins_.Mouse.prototype.cnds.OnClick, this);
- this.runtime.trigger(cr.plugins_.Mouse.prototype.cnds.OnObjectClicked, this);
- this.runtime.isInUserInputEvent = false;
- };
- instanceProto.onMouseUp = function(info)
- {
- if (!this.buttonMap[info.which])
- return;
- if (this.runtime.had_a_click && !this.runtime.isMobile)
- info.preventDefault();
- this.runtime.had_a_click = true;
- this.buttonMap[info.which] = false;
- this.runtime.isInUserInputEvent = true;
- this.triggerButton = info.which - 1; // 1-based
- this.runtime.trigger(cr.plugins_.Mouse.prototype.cnds.OnRelease, this);
- this.runtime.isInUserInputEvent = false;
- };
- instanceProto.onDoubleClick = function(info)
- {
- if (!this.mouseInGame())
- return;
- info.preventDefault();
- this.runtime.isInUserInputEvent = true;
- this.triggerButton = info.which - 1; // 1-based
- this.triggerType = 1; // double click
- this.runtime.trigger(cr.plugins_.Mouse.prototype.cnds.OnClick, this);
- this.runtime.trigger(cr.plugins_.Mouse.prototype.cnds.OnObjectClicked, this);
- this.runtime.isInUserInputEvent = false;
- };
- instanceProto.onWheel = function (info)
- {
- var delta = info.wheelDelta ? info.wheelDelta : info.detail ? -info.detail : 0;
- this.triggerDir = (delta < 0 ? 0 : 1);
- this.handled = false;
- this.runtime.isInUserInputEvent = true;
- this.runtime.trigger(cr.plugins_.Mouse.prototype.cnds.OnWheel, this);
- this.runtime.isInUserInputEvent = false;
- if (this.handled && cr.isCanvasInputEvent(info))
- info.preventDefault();
- };
- function Cnds() {};
- Cnds.prototype.OnClick = function (button, type)
- {
- return button === this.triggerButton && type === this.triggerType;
- };
- Cnds.prototype.OnAnyClick = function ()
- {
- return true;
- };
- Cnds.prototype.IsButtonDown = function (button)
- {
- return this.buttonMap[button + 1]; // jQuery uses 1-based buttons for some reason
- };
- Cnds.prototype.OnRelease = function (button)
- {
- return button === this.triggerButton;
- };
- Cnds.prototype.IsOverObject = function (obj)
- {
- var cnd = this.runtime.getCurrentCondition();
- var mx = this.mouseXcanvas;
- var my = this.mouseYcanvas;
- return cr.xor(this.runtime.testAndSelectCanvasPointOverlap(obj, mx, my, cnd.inverted), cnd.inverted);
- };
- Cnds.prototype.OnObjectClicked = function (button, type, obj)
- {
- if (button !== this.triggerButton || type !== this.triggerType)
- return false; // wrong click type
- return this.runtime.testAndSelectCanvasPointOverlap(obj, this.mouseXcanvas, this.mouseYcanvas, false);
- };
- Cnds.prototype.OnWheel = function (dir)
- {
- this.handled = true;
- return dir === this.triggerDir;
- };
- pluginProto.cnds = new Cnds();
- function Acts() {};
- var lastSetCursor = null;
- Acts.prototype.SetCursor = function (c)
- {
- var cursor_style = ["auto", "pointer", "text", "crosshair", "move", "help", "wait", "none"][c];
- if (lastSetCursor === cursor_style)
- return; // redundant
- lastSetCursor = cursor_style;
- if (this.runtime.canvas && this.runtime.canvas.style)
- this.runtime.canvas.style.cursor = cursor_style;
- };
- Acts.prototype.SetCursorSprite = function (obj)
- {
- if (this.runtime.isDomFree || this.runtime.isMobile || !obj)
- return;
- var inst = obj.getFirstPicked();
- if (!inst || !inst.curFrame)
- return;
- var frame = inst.curFrame;
- if (lastSetCursor === frame)
- return; // already set this frame
- lastSetCursor = frame;
- var datauri = frame.getDataUri();
- var cursor_style = "url(" + datauri + ") " + Math.round(frame.hotspotX * frame.width) + " " + Math.round(frame.hotspotY * frame.height) + ", auto";
- jQuery(this.runtime.canvas).css("cursor", cursor_style);
- };
- pluginProto.acts = new Acts();
- function Exps() {};
- Exps.prototype.X = function (ret, layerparam)
- {
- var layer, oldScale, oldZoomRate, oldParallaxX, oldAngle;
- if (cr.is_undefined(layerparam))
- {
- layer = this.runtime.getLayerByNumber(0);
- oldScale = layer.scale;
- oldZoomRate = layer.zoomRate;
- oldParallaxX = layer.parallaxX;
- oldAngle = layer.angle;
- layer.scale = 1;
- layer.zoomRate = 1.0;
- layer.parallaxX = 1.0;
- layer.angle = 0;
- ret.set_float(layer.canvasToLayer(this.mouseXcanvas, this.mouseYcanvas, true));
- layer.scale = oldScale;
- layer.zoomRate = oldZoomRate;
- layer.parallaxX = oldParallaxX;
- layer.angle = oldAngle;
- }
- else
- {
- if (cr.is_number(layerparam))
- layer = this.runtime.getLayerByNumber(layerparam);
- else
- layer = this.runtime.getLayerByName(layerparam);
- if (layer)
- ret.set_float(layer.canvasToLayer(this.mouseXcanvas, this.mouseYcanvas, true));
- else
- ret.set_float(0);
- }
- };
- Exps.prototype.Y = function (ret, layerparam)
- {
- var layer, oldScale, oldZoomRate, oldParallaxY, oldAngle;
- if (cr.is_undefined(layerparam))
- {
- layer = this.runtime.getLayerByNumber(0);
- oldScale = layer.scale;
- oldZoomRate = layer.zoomRate;
- oldParallaxY = layer.parallaxY;
- oldAngle = layer.angle;
- layer.scale = 1;
- layer.zoomRate = 1.0;
- layer.parallaxY = 1.0;
- layer.angle = 0;
- ret.set_float(layer.canvasToLayer(this.mouseXcanvas, this.mouseYcanvas, false));
- layer.scale = oldScale;
- layer.zoomRate = oldZoomRate;
- layer.parallaxY = oldParallaxY;
- layer.angle = oldAngle;
- }
- else
- {
- if (cr.is_number(layerparam))
- layer = this.runtime.getLayerByNumber(layerparam);
- else
- layer = this.runtime.getLayerByName(layerparam);
- if (layer)
- ret.set_float(layer.canvasToLayer(this.mouseXcanvas, this.mouseYcanvas, false));
- else
- ret.set_float(0);
- }
- };
- Exps.prototype.AbsoluteX = function (ret)
- {
- ret.set_float(this.mouseXcanvas);
- };
- Exps.prototype.AbsoluteY = function (ret)
- {
- ret.set_float(this.mouseYcanvas);
- };
- pluginProto.exps = new Exps();
- }());
- ;
- ;
- cr.plugins_.Rex_ZSorter = function(runtime)
- {
- this.runtime = runtime;
- };
- (function ()
- {
- var pluginProto = cr.plugins_.Rex_ZSorter.prototype;
- pluginProto.Type = function(plugin)
- {
- this.plugin = plugin;
- this.runtime = plugin.runtime;
- };
- var typeProto = pluginProto.Type.prototype;
- typeProto.onCreate = function()
- {
- };
- pluginProto.Instance = function(type)
- {
- this.type = type;
- this.runtime = type.runtime;
- };
- var instanceProto = pluginProto.Instance.prototype;
- var x_increasing = true;
- instanceProto.onCreate = function()
- {
- x_increasing = (this.properties[0] == 0);
- this._cmp_uidA = 0;
- this._cmp_uidB = 0;
- this._compared_result = 0;
- this._sort_fn_name = "";
- };
- instanceProto.draw = function(ctx)
- {
- };
- instanceProto.get_layer = function(layerparam)
- {
- return (typeof layerparam == "number")?
- this.runtime.getLayerByNumber(layerparam):
- this.runtime.getLayerByName(layerparam);
- };
- var _thisArg = null;
- var _sort_fn = function(instance_a, instance_b)
- {
- _thisArg._cmp_uidA = instance_a.uid;
- _thisArg._cmp_uidB = instance_b.uid;
- _thisArg.runtime.trigger(cr.plugins_.Rex_ZSorter.prototype.cnds.OnSortingFn, _thisArg);
- return _thisArg._compared_result;
- };
- instanceProto.saveToJSON = function ()
- {
- return { "xi": x_increasing };
- };
- instanceProto.loadFromJSON = function (o)
- {
- x_increasing = o["xi"];
- };
- function Cnds() {};
- pluginProto.cnds = new Cnds();
- Cnds.prototype.OnSortingFn = function (name)
- {
- return (this._sort_fn_name == name);
- };
- function Acts() {};
- pluginProto.acts = new Acts();
- var ZSORT = function(instance_a, instance_b)
- {
- var ax = instance_a.x;
- var ay = instance_a.y;
- var bx = instance_b.x;
- var by = instance_b.y;
- if (ay > by)
- return 1;
- else if (ay == by)
- {
- if (ax == bx)
- return 0;
- if ((x_increasing && (ax > bx)) || (!x_increasing && (ax < bx)))
- return 1;
- else
- return (-1);
- }
- else // ay < by
- return (-1);
- }
- Acts.prototype.SortObjsLayerByY = function (layerparam)
- {
- var layer = this.get_layer(layerparam);
- if (layer == null)
- {
- alart("Z Sort: Can not find layer " + layerparam);
- return;
- }
- layer.instances.sort(ZSORT);
- layer.zindices_stale = true;
- this.runtime.redraw = true;
- };
- Acts.prototype.SetXorder = function (x_order)
- {
- x_increasing = (x_order == 0);
- };
- Acts.prototype.SortByFn = function (layerparam, fn_name)
- {
- var layer = this.get_layer(layerparam);
- if (layer == null)
- {
- alert("Z Sort: Can not find layer " + layerparam);
- return;
- }
- _thisArg = this;
- this._sort_fn_name = fn_name;
- layer.instances.sort(_sort_fn);
- layer.zindices_stale = true;
- this.runtime.redraw = true;
- };
- Acts.prototype.SetCmpResultDirectly = function (result)
- {
- this._compared_result = result;
- };
- Acts.prototype.SetCmpResultCombo = function (result)
- {
- this._compared_result = result -1;
- };
- function Exps() {};
- pluginProto.exps = new Exps();
- Exps.prototype.CmpUIDA = function (ret)
- {
- ret.set_int(this._cmp_uidA);
- };
- Exps.prototype.CmpUIDB = function (ret)
- {
- ret.set_int(this._cmp_uidB);
- };
- }());
- ;
- ;
- cr.plugins_.Sprite = function(runtime)
- {
- this.runtime = runtime;
- };
- (function ()
- {
- var pluginProto = cr.plugins_.Sprite.prototype;
- pluginProto.Type = function(plugin)
- {
- this.plugin = plugin;
- this.runtime = plugin.runtime;
- };
- var typeProto = pluginProto.Type.prototype;
- function frame_getDataUri()
- {
- if (this.datauri.length === 0)
- {
- var tmpcanvas = document.createElement("canvas");
- tmpcanvas.width = this.width;
- tmpcanvas.height = this.height;
- var tmpctx = tmpcanvas.getContext("2d");
- if (this.spritesheeted)
- {
- tmpctx.drawImage(this.texture_img, this.offx, this.offy, this.width, this.height,
- 0, 0, this.width, this.height);
- }
- else
- {
- tmpctx.drawImage(this.texture_img, 0, 0, this.width, this.height);
- }
- this.datauri = tmpcanvas.toDataURL("image/png");
- }
- return this.datauri;
- };
- typeProto.onCreate = function()
- {
- if (this.is_family)
- return;
- var i, leni, j, lenj;
- var anim, frame, animobj, frameobj, wt, uv;
- this.all_frames = [];
- this.has_loaded_textures = false;
- for (i = 0, leni = this.animations.length; i < leni; i++)
- {
- anim = this.animations[i];
- animobj = {};
- animobj.name = anim[0];
- animobj.speed = anim[1];
- animobj.loop = anim[2];
- animobj.repeatcount = anim[3];
- animobj.repeatto = anim[4];
- animobj.pingpong = anim[5];
- animobj.sid = anim[6];
- animobj.frames = [];
- for (j = 0, lenj = anim[7].length; j < lenj; j++)
- {
- frame = anim[7][j];
- frameobj = {};
- frameobj.texture_file = frame[0];
- frameobj.texture_filesize = frame[1];
- frameobj.offx = frame[2];
- frameobj.offy = frame[3];
- frameobj.width = frame[4];
- frameobj.height = frame[5];
- frameobj.duration = frame[6];
- frameobj.hotspotX = frame[7];
- frameobj.hotspotY = frame[8];
- frameobj.image_points = frame[9];
- frameobj.poly_pts = frame[10];
- frameobj.pixelformat = frame[11];
- frameobj.spritesheeted = (frameobj.width !== 0);
- frameobj.datauri = ""; // generated on demand and cached
- frameobj.getDataUri = frame_getDataUri;
- uv = {};
- uv.left = 0;
- uv.top = 0;
- uv.right = 1;
- uv.bottom = 1;
- frameobj.sheetTex = uv;
- frameobj.webGL_texture = null;
- wt = this.runtime.findWaitingTexture(frame[0]);
- if (wt)
- {
- frameobj.texture_img = wt;
- }
- else
- {
- frameobj.texture_img = new Image();
- frameobj.texture_img.cr_src = frame[0];
- frameobj.texture_img.cr_filesize = frame[1];
- frameobj.texture_img.c2webGL_texture = null;
- this.runtime.waitForImageLoad(frameobj.texture_img, frame[0]);
- }
- cr.seal(frameobj);
- animobj.frames.push(frameobj);
- this.all_frames.push(frameobj);
- }
- cr.seal(animobj);
- this.animations[i] = animobj; // swap array data for object
- }
- };
- typeProto.updateAllCurrentTexture = function ()
- {
- var i, len, inst;
- for (i = 0, len = this.instances.length; i < len; i++)
- {
- inst = this.instances[i];
- inst.curWebGLTexture = inst.curFrame.webGL_texture;
- }
- };
- typeProto.onLostWebGLContext = function ()
- {
- if (this.is_family)
- return;
- var i, len, frame;
- for (i = 0, len = this.all_frames.length; i < len; ++i)
- {
- frame = this.all_frames[i];
- frame.texture_img.c2webGL_texture = null;
- frame.webGL_texture = null;
- }
- this.has_loaded_textures = false;
- this.updateAllCurrentTexture();
- };
- typeProto.onRestoreWebGLContext = function ()
- {
- if (this.is_family || !this.instances.length)
- return;
- var i, len, frame;
- for (i = 0, len = this.all_frames.length; i < len; ++i)
- {
- frame = this.all_frames[i];
- frame.webGL_texture = this.runtime.glwrap.loadTexture(frame.texture_img, false, this.runtime.linearSampling, frame.pixelformat);
- }
- this.updateAllCurrentTexture();
- };
- typeProto.loadTextures = function ()
- {
- if (this.is_family || this.has_loaded_textures || !this.runtime.glwrap)
- return;
- var i, len, frame;
- for (i = 0, len = this.all_frames.length; i < len; ++i)
- {
- frame = this.all_frames[i];
- frame.webGL_texture = this.runtime.glwrap.loadTexture(frame.texture_img, false, this.runtime.linearSampling, frame.pixelformat);
- }
- this.has_loaded_textures = true;
- };
- typeProto.unloadTextures = function ()
- {
- if (this.is_family || this.instances.length || !this.has_loaded_textures)
- return;
- var i, len, frame;
- for (i = 0, len = this.all_frames.length; i < len; ++i)
- {
- frame = this.all_frames[i];
- this.runtime.glwrap.deleteTexture(frame.webGL_texture);
- frame.webGL_texture = null;
- }
- this.has_loaded_textures = false;
- };
- var already_drawn_images = [];
- typeProto.preloadCanvas2D = function (ctx)
- {
- var i, len, frameimg;
- cr.clearArray(already_drawn_images);
- for (i = 0, len = this.all_frames.length; i < len; ++i)
- {
- frameimg = this.all_frames[i].texture_img;
- if (already_drawn_images.indexOf(frameimg) !== -1)
- continue;
- ctx.drawImage(frameimg, 0, 0);
- already_drawn_images.push(frameimg);
- }
- };
- pluginProto.Instance = function(type)
- {
- this.type = type;
- this.runtime = type.runtime;
- var poly_pts = this.type.animations[0].frames[0].poly_pts;
- if (this.recycled)
- this.collision_poly.set_pts(poly_pts);
- else
- this.collision_poly = new cr.CollisionPoly(poly_pts);
- };
- var instanceProto = pluginProto.Instance.prototype;
- instanceProto.onCreate = function()
- {
- this.visible = (this.properties[0] === 0); // 0=visible, 1=invisible
- this.isTicking = false;
- this.inAnimTrigger = false;
- this.collisionsEnabled = (this.properties[3] !== 0);
- if (!(this.type.animations.length === 1 && this.type.animations[0].frames.length === 1) && this.type.animations[0].speed !== 0)
- {
- this.runtime.tickMe(this);
- this.isTicking = true;
- }
- this.cur_animation = this.getAnimationByName(this.properties[1]) || this.type.animations[0];
- this.cur_frame = this.properties[2];
- if (this.cur_frame < 0)
- this.cur_frame = 0;
- if (this.cur_frame >= this.cur_animation.frames.length)
- this.cur_frame = this.cur_animation.frames.length - 1;
- var curanimframe = this.cur_animation.frames[this.cur_frame];
- this.collision_poly.set_pts(curanimframe.poly_pts);
- this.hotspotX = curanimframe.hotspotX;
- this.hotspotY = curanimframe.hotspotY;
- this.cur_anim_speed = this.cur_animation.speed;
- if (this.recycled)
- this.animTimer.reset();
- else
- this.animTimer = new cr.KahanAdder();
- this.frameStart = this.getNowTime();
- this.animPlaying = true;
- this.animRepeats = 0;
- this.animForwards = true;
- this.animTriggerName = "";
- this.changeAnimName = "";
- this.changeAnimFrom = 0;
- this.changeAnimFrame = -1;
- this.type.loadTextures();
- var i, leni, j, lenj;
- var anim, frame, uv, maintex;
- for (i = 0, leni = this.type.animations.length; i < leni; i++)
- {
- anim = this.type.animations[i];
- for (j = 0, lenj = anim.frames.length; j < lenj; j++)
- {
- frame = anim.frames[j];
- if (frame.width === 0)
- {
- frame.width = frame.texture_img.width;
- frame.height = frame.texture_img.height;
- }
- if (frame.spritesheeted)
- {
- maintex = frame.texture_img;
- uv = frame.sheetTex;
- uv.left = frame.offx / maintex.width;
- uv.top = frame.offy / maintex.height;
- uv.right = (frame.offx + frame.width) / maintex.width;
- uv.bottom = (frame.offy + frame.height) / maintex.height;
- if (frame.offx === 0 && frame.offy === 0 && frame.width === maintex.width && frame.height === maintex.height)
- {
- frame.spritesheeted = false;
- }
- }
- }
- }
- this.curFrame = this.cur_animation.frames[this.cur_frame];
- this.curWebGLTexture = this.curFrame.webGL_texture;
- };
- instanceProto.saveToJSON = function ()
- {
- var o = {
- "a": this.cur_animation.sid,
- "f": this.cur_frame,
- "cas": this.cur_anim_speed,
- "fs": this.frameStart,
- "ar": this.animRepeats,
- "at": this.animTimer.sum
- };
- if (!this.animPlaying)
- o["ap"] = this.animPlaying;
- if (!this.animForwards)
- o["af"] = this.animForwards;
- return o;
- };
- instanceProto.loadFromJSON = function (o)
- {
- var anim = this.getAnimationBySid(o["a"]);
- if (anim)
- this.cur_animation = anim;
- this.cur_frame = o["f"];
- if (this.cur_frame < 0)
- this.cur_frame = 0;
- if (this.cur_frame >= this.cur_animation.frames.length)
- this.cur_frame = this.cur_animation.frames.length - 1;
- this.cur_anim_speed = o["cas"];
- this.frameStart = o["fs"];
- this.animRepeats = o["ar"];
- this.animTimer.reset();
- this.animTimer.sum = o["at"];
- this.animPlaying = o.hasOwnProperty("ap") ? o["ap"] : true;
- this.animForwards = o.hasOwnProperty("af") ? o["af"] : true;
- this.curFrame = this.cur_animation.frames[this.cur_frame];
- this.curWebGLTexture = this.curFrame.webGL_texture;
- this.collision_poly.set_pts(this.curFrame.poly_pts);
- this.hotspotX = this.curFrame.hotspotX;
- this.hotspotY = this.curFrame.hotspotY;
- };
- instanceProto.animationFinish = function (reverse)
- {
- this.cur_frame = reverse ? 0 : this.cur_animation.frames.length - 1;
- this.animPlaying = false;
- this.animTriggerName = this.cur_animation.name;
- this.inAnimTrigger = true;
- this.runtime.trigger(cr.plugins_.Sprite.prototype.cnds.OnAnyAnimFinished, this);
- this.runtime.trigger(cr.plugins_.Sprite.prototype.cnds.OnAnimFinished, this);
- this.inAnimTrigger = false;
- this.animRepeats = 0;
- };
- instanceProto.getNowTime = function()
- {
- return this.animTimer.sum;
- };
- instanceProto.tick = function()
- {
- this.animTimer.add(this.runtime.getDt(this));
- if (this.changeAnimName.length)
- this.doChangeAnim();
- if (this.changeAnimFrame >= 0)
- this.doChangeAnimFrame();
- var now = this.getNowTime();
- var cur_animation = this.cur_animation;
- var prev_frame = cur_animation.frames[this.cur_frame];
- var next_frame;
- var cur_frame_time = prev_frame.duration / this.cur_anim_speed;
- if (this.animPlaying && now >= this.frameStart + cur_frame_time)
- {
- if (this.animForwards)
- {
- this.cur_frame++;
- }
- else
- {
- this.cur_frame--;
- }
- this.frameStart += cur_frame_time;
- if (this.cur_frame >= cur_animation.frames.length)
- {
- if (cur_animation.pingpong)
- {
- this.animForwards = false;
- this.cur_frame = cur_animation.frames.length - 2;
- }
- else if (cur_animation.loop)
- {
- this.cur_frame = cur_animation.repeatto;
- }
- else
- {
- this.animRepeats++;
- if (this.animRepeats >= cur_animation.repeatcount)
- {
- this.animationFinish(false);
- }
- else
- {
- this.cur_frame = cur_animation.repeatto;
- }
- }
- }
- if (this.cur_frame < 0)
- {
- if (cur_animation.pingpong)
- {
- this.cur_frame = 1;
- this.animForwards = true;
- if (!cur_animation.loop)
- {
- this.animRepeats++;
- if (this.animRepeats >= cur_animation.repeatcount)
- {
- this.animationFinish(true);
- }
- }
- }
- else
- {
- if (cur_animation.loop)
- {
- this.cur_frame = cur_animation.repeatto;
- }
- else
- {
- this.animRepeats++;
- if (this.animRepeats >= cur_animation.repeatcount)
- {
- this.animationFinish(true);
- }
- else
- {
- this.cur_frame = cur_animation.repeatto;
- }
- }
- }
- }
- if (this.cur_frame < 0)
- this.cur_frame = 0;
- else if (this.cur_frame >= cur_animation.frames.length)
- this.cur_frame = cur_animation.frames.length - 1;
- if (now > this.frameStart + (cur_animation.frames[this.cur_frame].duration / this.cur_anim_speed))
- {
- this.frameStart = now;
- }
- next_frame = cur_animation.frames[this.cur_frame];
- this.OnFrameChanged(prev_frame, next_frame);
- this.runtime.redraw = true;
- }
- };
- instanceProto.getAnimationByName = function (name_)
- {
- var i, len, a;
- for (i = 0, len = this.type.animations.length; i < len; i++)
- {
- a = this.type.animations[i];
- if (cr.equals_nocase(a.name, name_))
- return a;
- }
- return null;
- };
- instanceProto.getAnimationBySid = function (sid_)
- {
- var i, len, a;
- for (i = 0, len = this.type.animations.length; i < len; i++)
- {
- a = this.type.animations[i];
- if (a.sid === sid_)
- return a;
- }
- return null;
- };
- instanceProto.doChangeAnim = function ()
- {
- var prev_frame = this.cur_animation.frames[this.cur_frame];
- var anim = this.getAnimationByName(this.changeAnimName);
- this.changeAnimName = "";
- if (!anim)
- return;
- if (cr.equals_nocase(anim.name, this.cur_animation.name) && this.animPlaying)
- return;
- this.cur_animation = anim;
- this.cur_anim_speed = anim.speed;
- if (this.cur_frame < 0)
- this.cur_frame = 0;
- if (this.cur_frame >= this.cur_animation.frames.length)
- this.cur_frame = this.cur_animation.frames.length - 1;
- if (this.changeAnimFrom === 1)
- this.cur_frame = 0;
- this.animPlaying = true;
- this.frameStart = this.getNowTime();
- this.animForwards = true;
- this.OnFrameChanged(prev_frame, this.cur_animation.frames[this.cur_frame]);
- this.runtime.redraw = true;
- };
- instanceProto.doChangeAnimFrame = function ()
- {
- var prev_frame = this.cur_animation.frames[this.cur_frame];
- var prev_frame_number = this.cur_frame;
- this.cur_frame = cr.floor(this.changeAnimFrame);
- if (this.cur_frame < 0)
- this.cur_frame = 0;
- if (this.cur_frame >= this.cur_animation.frames.length)
- this.cur_frame = this.cur_animation.frames.length - 1;
- if (prev_frame_number !== this.cur_frame)
- {
- this.OnFrameChanged(prev_frame, this.cur_animation.frames[this.cur_frame]);
- this.frameStart = this.getNowTime();
- this.runtime.redraw = true;
- }
- this.changeAnimFrame = -1;
- };
- instanceProto.OnFrameChanged = function (prev_frame, next_frame)
- {
- var oldw = prev_frame.width;
- var oldh = prev_frame.height;
- var neww = next_frame.width;
- var newh = next_frame.height;
- if (oldw != neww)
- this.width *= (neww / oldw);
- if (oldh != newh)
- this.height *= (newh / oldh);
- this.hotspotX = next_frame.hotspotX;
- this.hotspotY = next_frame.hotspotY;
- this.collision_poly.set_pts(next_frame.poly_pts);
- this.set_bbox_changed();
- this.curFrame = next_frame;
- this.curWebGLTexture = next_frame.webGL_texture;
- var i, len, b;
- for (i = 0, len = this.behavior_insts.length; i < len; i++)
- {
- b = this.behavior_insts[i];
- if (b.onSpriteFrameChanged)
- b.onSpriteFrameChanged(prev_frame, next_frame);
- }
- this.runtime.trigger(cr.plugins_.Sprite.prototype.cnds.OnFrameChanged, this);
- };
- instanceProto.draw = function(ctx)
- {
- ctx.globalAlpha = this.opacity;
- var cur_frame = this.curFrame;
- var spritesheeted = cur_frame.spritesheeted;
- var cur_image = cur_frame.texture_img;
- var myx = this.x;
- var myy = this.y;
- var w = this.width;
- var h = this.height;
- if (this.angle === 0 && w >= 0 && h >= 0)
- {
- myx -= this.hotspotX * w;
- myy -= this.hotspotY * h;
- if (this.runtime.pixel_rounding)
- {
- myx = Math.round(myx);
- myy = Math.round(myy);
- }
- if (spritesheeted)
- {
- ctx.drawImage(cur_image, cur_frame.offx, cur_frame.offy, cur_frame.width, cur_frame.height,
- myx, myy, w, h);
- }
- else
- {
- ctx.drawImage(cur_image, myx, myy, w, h);
- }
- }
- else
- {
- if (this.runtime.pixel_rounding)
- {
- myx = Math.round(myx);
- myy = Math.round(myy);
- }
- ctx.save();
- var widthfactor = w > 0 ? 1 : -1;
- var heightfactor = h > 0 ? 1 : -1;
- ctx.translate(myx, myy);
- if (widthfactor !== 1 || heightfactor !== 1)
- ctx.scale(widthfactor, heightfactor);
- ctx.rotate(this.angle * widthfactor * heightfactor);
- var drawx = 0 - (this.hotspotX * cr.abs(w))
- var drawy = 0 - (this.hotspotY * cr.abs(h));
- if (spritesheeted)
- {
- ctx.drawImage(cur_image, cur_frame.offx, cur_frame.offy, cur_frame.width, cur_frame.height,
- drawx, drawy, cr.abs(w), cr.abs(h));
- }
- else
- {
- ctx.drawImage(cur_image, drawx, drawy, cr.abs(w), cr.abs(h));
- }
- ctx.restore();
- }
- /*
- ctx.strokeStyle = "#f00";
- ctx.lineWidth = 3;
- ctx.beginPath();
- this.collision_poly.cache_poly(this.width, this.height, this.angle);
- var i, len, ax, ay, bx, by;
- for (i = 0, len = this.collision_poly.pts_count; i < len; i++)
- {
- ax = this.collision_poly.pts_cache[i*2] + this.x;
- ay = this.collision_poly.pts_cache[i*2+1] + this.y;
- bx = this.collision_poly.pts_cache[((i+1)%len)*2] + this.x;
- by = this.collision_poly.pts_cache[((i+1)%len)*2+1] + this.y;
- ctx.moveTo(ax, ay);
- ctx.lineTo(bx, by);
- }
- ctx.stroke();
- ctx.closePath();
- */
- /*
- if (this.behavior_insts.length >= 1 && this.behavior_insts[0].draw)
- {
- this.behavior_insts[0].draw(ctx);
- }
- */
- };
- instanceProto.drawGL_earlyZPass = function(glw)
- {
- this.drawGL(glw);
- };
- instanceProto.drawGL = function(glw)
- {
- glw.setTexture(this.curWebGLTexture);
- glw.setOpacity(this.opacity);
- var cur_frame = this.curFrame;
- var q = this.bquad;
- if (this.runtime.pixel_rounding)
- {
- var ox = Math.round(this.x) - this.x;
- var oy = Math.round(this.y) - this.y;
- if (cur_frame.spritesheeted)
- glw.quadTex(q.tlx + ox, q.tly + oy, q.trx + ox, q.try_ + oy, q.brx + ox, q.bry + oy, q.blx + ox, q.bly + oy, cur_frame.sheetTex);
- else
- glw.quad(q.tlx + ox, q.tly + oy, q.trx + ox, q.try_ + oy, q.brx + ox, q.bry + oy, q.blx + ox, q.bly + oy);
- }
- else
- {
- if (cur_frame.spritesheeted)
- glw.quadTex(q.tlx, q.tly, q.trx, q.try_, q.brx, q.bry, q.blx, q.bly, cur_frame.sheetTex);
- else
- glw.quad(q.tlx, q.tly, q.trx, q.try_, q.brx, q.bry, q.blx, q.bly);
- }
- };
- instanceProto.getImagePointIndexByName = function(name_)
- {
- var cur_frame = this.curFrame;
- var i, len;
- for (i = 0, len = cur_frame.image_points.length; i < len; i++)
- {
- if (cr.equals_nocase(name_, cur_frame.image_points[i][0]))
- return i;
- }
- return -1;
- };
- instanceProto.getImagePoint = function(imgpt, getX)
- {
- var cur_frame = this.curFrame;
- var image_points = cur_frame.image_points;
- var index;
- if (cr.is_string(imgpt))
- index = this.getImagePointIndexByName(imgpt);
- else
- index = imgpt - 1; // 0 is origin
- index = cr.floor(index);
- if (index < 0 || index >= image_points.length)
- return getX ? this.x : this.y; // return origin
- var x = (image_points[index][1] - cur_frame.hotspotX) * this.width;
- var y = image_points[index][2];
- y = (y - cur_frame.hotspotY) * this.height;
- var cosa = Math.cos(this.angle);
- var sina = Math.sin(this.angle);
- var x_temp = (x * cosa) - (y * sina);
- y = (y * cosa) + (x * sina);
- x = x_temp;
- x += this.x;
- y += this.y;
- return getX ? x : y;
- };
- function Cnds() {};
- var arrCache = [];
- function allocArr()
- {
- if (arrCache.length)
- return arrCache.pop();
- else
- return [0, 0, 0];
- };
- function freeArr(a)
- {
- a[0] = 0;
- a[1] = 0;
- a[2] = 0;
- arrCache.push(a);
- };
- function makeCollKey(a, b)
- {
- if (a < b)
- return "" + a + "," + b;
- else
- return "" + b + "," + a;
- };
- function collmemory_add(collmemory, a, b, tickcount)
- {
- var a_uid = a.uid;
- var b_uid = b.uid;
- var key = makeCollKey(a_uid, b_uid);
- if (collmemory.hasOwnProperty(key))
- {
- collmemory[key][2] = tickcount;
- return;
- }
- var arr = allocArr();
- arr[0] = a_uid;
- arr[1] = b_uid;
- arr[2] = tickcount;
- collmemory[key] = arr;
- };
- function collmemory_remove(collmemory, a, b)
- {
- var key = makeCollKey(a.uid, b.uid);
- if (collmemory.hasOwnProperty(key))
- {
- freeArr(collmemory[key]);
- delete collmemory[key];
- }
- };
- function collmemory_removeInstance(collmemory, inst)
- {
- var uid = inst.uid;
- var p, entry;
- for (p in collmemory)
- {
- if (collmemory.hasOwnProperty(p))
- {
- entry = collmemory[p];
- if (entry[0] === uid || entry[1] === uid)
- {
- freeArr(collmemory[p]);
- delete collmemory[p];
- }
- }
- }
- };
- var last_coll_tickcount = -2;
- function collmemory_has(collmemory, a, b)
- {
- var key = makeCollKey(a.uid, b.uid);
- if (collmemory.hasOwnProperty(key))
- {
- last_coll_tickcount = collmemory[key][2];
- return true;
- }
- else
- {
- last_coll_tickcount = -2;
- return false;
- }
- };
- var candidates1 = [];
- Cnds.prototype.OnCollision = function (rtype)
- {
- if (!rtype)
- return false;
- var runtime = this.runtime;
- var cnd = runtime.getCurrentCondition();
- var ltype = cnd.type;
- var collmemory = null;
- if (cnd.extra["collmemory"])
- {
- collmemory = cnd.extra["collmemory"];
- }
- else
- {
- collmemory = {};
- cnd.extra["collmemory"] = collmemory;
- runtime.addDestroyCallback(function(inst) {
- collmemory_removeInstance(cnd.extra["collmemory"], inst);
- });
- }
- var lsol = ltype.getCurrentSol();
- var rsol = rtype.getCurrentSol();
- var linstances = lsol.getObjects();
- var rinstances;
- var l, linst, r, rinst;
- var curlsol, currsol;
- var tickcount = this.runtime.tickcount;
- var lasttickcount = tickcount - 1;
- var exists, run;
- var current_event = runtime.getCurrentEventStack().current_event;
- var orblock = current_event.orblock;
- for (l = 0; l < linstances.length; l++)
- {
- linst = linstances[l];
- if (rsol.select_all)
- {
- linst.update_bbox();
- this.runtime.getCollisionCandidates(linst.layer, rtype, linst.bbox, candidates1);
- rinstances = candidates1;
- }
- else
- rinstances = rsol.getObjects();
- for (r = 0; r < rinstances.length; r++)
- {
- rinst = rinstances[r];
- if (runtime.testOverlap(linst, rinst) || runtime.checkRegisteredCollision(linst, rinst))
- {
- exists = collmemory_has(collmemory, linst, rinst);
- run = (!exists || (last_coll_tickcount < lasttickcount));
- collmemory_add(collmemory, linst, rinst, tickcount);
- if (run)
- {
- runtime.pushCopySol(current_event.solModifiers);
- curlsol = ltype.getCurrentSol();
- currsol = rtype.getCurrentSol();
- curlsol.select_all = false;
- currsol.select_all = false;
- if (ltype === rtype)
- {
- curlsol.instances.length = 2; // just use lsol, is same reference as rsol
- curlsol.instances[0] = linst;
- curlsol.instances[1] = rinst;
- ltype.applySolToContainer();
- }
- else
- {
- curlsol.instances.length = 1;
- currsol.instances.length = 1;
- curlsol.instances[0] = linst;
- currsol.instances[0] = rinst;
- ltype.applySolToContainer();
- rtype.applySolToContainer();
- }
- current_event.retrigger();
- runtime.popSol(current_event.solModifiers);
- }
- }
- else
- {
- collmemory_remove(collmemory, linst, rinst);
- }
- }
- cr.clearArray(candidates1);
- }
- return false;
- };
- var rpicktype = null;
- var rtopick = new cr.ObjectSet();
- var needscollisionfinish = false;
- var candidates2 = [];
- var temp_bbox = new cr.rect(0, 0, 0, 0);
- function DoOverlapCondition(rtype, offx, offy)
- {
- if (!rtype)
- return false;
- var do_offset = (offx !== 0 || offy !== 0);
- var oldx, oldy, ret = false, r, lenr, rinst;
- var cnd = this.runtime.getCurrentCondition();
- var ltype = cnd.type;
- var inverted = cnd.inverted;
- var rsol = rtype.getCurrentSol();
- var orblock = this.runtime.getCurrentEventStack().current_event.orblock;
- var rinstances;
- if (rsol.select_all)
- {
- this.update_bbox();
- temp_bbox.copy(this.bbox);
- temp_bbox.offset(offx, offy);
- this.runtime.getCollisionCandidates(this.layer, rtype, temp_bbox, candidates2);
- rinstances = candidates2;
- }
- else if (orblock)
- rinstances = rsol.else_instances;
- else
- rinstances = rsol.instances;
- rpicktype = rtype;
- needscollisionfinish = (ltype !== rtype && !inverted);
- if (do_offset)
- {
- oldx = this.x;
- oldy = this.y;
- this.x += offx;
- this.y += offy;
- this.set_bbox_changed();
- }
- for (r = 0, lenr = rinstances.length; r < lenr; r++)
- {
- rinst = rinstances[r];
- if (this.runtime.testOverlap(this, rinst))
- {
- ret = true;
- if (inverted)
- break;
- if (ltype !== rtype)
- rtopick.add(rinst);
- }
- }
- if (do_offset)
- {
- this.x = oldx;
- this.y = oldy;
- this.set_bbox_changed();
- }
- cr.clearArray(candidates2);
- return ret;
- };
- typeProto.finish = function (do_pick)
- {
- if (!needscollisionfinish)
- return;
- if (do_pick)
- {
- var orblock = this.runtime.getCurrentEventStack().current_event.orblock;
- var sol = rpicktype.getCurrentSol();
- var topick = rtopick.valuesRef();
- var i, len, inst;
- if (sol.select_all)
- {
- sol.select_all = false;
- cr.clearArray(sol.instances);
- for (i = 0, len = topick.length; i < len; ++i)
- {
- sol.instances[i] = topick[i];
- }
- if (orblock)
- {
- cr.clearArray(sol.else_instances);
- for (i = 0, len = rpicktype.instances.length; i < len; ++i)
- {
- inst = rpicktype.instances[i];
- if (!rtopick.contains(inst))
- sol.else_instances.push(inst);
- }
- }
- }
- else
- {
- if (orblock)
- {
- var initsize = sol.instances.length;
- for (i = 0, len = topick.length; i < len; ++i)
- {
- sol.instances[initsize + i] = topick[i];
- cr.arrayFindRemove(sol.else_instances, topick[i]);
- }
- }
- else
- {
- cr.shallowAssignArray(sol.instances, topick);
- }
- }
- rpicktype.applySolToContainer();
- }
- rtopick.clear();
- needscollisionfinish = false;
- };
- Cnds.prototype.IsOverlapping = function (rtype)
- {
- return DoOverlapCondition.call(this, rtype, 0, 0);
- };
- Cnds.prototype.IsOverlappingOffset = function (rtype, offx, offy)
- {
- return DoOverlapCondition.call(this, rtype, offx, offy);
- };
- Cnds.prototype.IsAnimPlaying = function (animname)
- {
- if (this.changeAnimName.length)
- return cr.equals_nocase(this.changeAnimName, animname);
- else
- return cr.equals_nocase(this.cur_animation.name, animname);
- };
- Cnds.prototype.CompareFrame = function (cmp, framenum)
- {
- return cr.do_cmp(this.cur_frame, cmp, framenum);
- };
- Cnds.prototype.CompareAnimSpeed = function (cmp, x)
- {
- var s = (this.animForwards ? this.cur_anim_speed : -this.cur_anim_speed);
- return cr.do_cmp(s, cmp, x);
- };
- Cnds.prototype.OnAnimFinished = function (animname)
- {
- return cr.equals_nocase(this.animTriggerName, animname);
- };
- Cnds.prototype.OnAnyAnimFinished = function ()
- {
- return true;
- };
- Cnds.prototype.OnFrameChanged = function ()
- {
- return true;
- };
- Cnds.prototype.IsMirrored = function ()
- {
- return this.width < 0;
- };
- Cnds.prototype.IsFlipped = function ()
- {
- return this.height < 0;
- };
- Cnds.prototype.OnURLLoaded = function ()
- {
- return true;
- };
- Cnds.prototype.IsCollisionEnabled = function ()
- {
- return this.collisionsEnabled;
- };
- pluginProto.cnds = new Cnds();
- function Acts() {};
- Acts.prototype.Spawn = function (obj, layer, imgpt)
- {
- if (!obj || !layer)
- return;
- var inst = this.runtime.createInstance(obj, layer, this.getImagePoint(imgpt, true), this.getImagePoint(imgpt, false));
- if (!inst)
- return;
- if (typeof inst.angle !== "undefined")
- {
- inst.angle = this.angle;
- inst.set_bbox_changed();
- }
- this.runtime.isInOnDestroy++;
- var i, len, s;
- this.runtime.trigger(Object.getPrototypeOf(obj.plugin).cnds.OnCreated, inst);
- if (inst.is_contained)
- {
- for (i = 0, len = inst.siblings.length; i < len; i++)
- {
- s = inst.siblings[i];
- this.runtime.trigger(Object.getPrototypeOf(s.type.plugin).cnds.OnCreated, s);
- }
- }
- this.runtime.isInOnDestroy--;
- var cur_act = this.runtime.getCurrentAction();
- var reset_sol = false;
- if (cr.is_undefined(cur_act.extra["Spawn_LastExec"]) || cur_act.extra["Spawn_LastExec"] < this.runtime.execcount)
- {
- reset_sol = true;
- cur_act.extra["Spawn_LastExec"] = this.runtime.execcount;
- }
- var sol;
- if (obj != this.type)
- {
- sol = obj.getCurrentSol();
- sol.select_all = false;
- if (reset_sol)
- {
- cr.clearArray(sol.instances);
- sol.instances[0] = inst;
- }
- else
- sol.instances.push(inst);
- if (inst.is_contained)
- {
- for (i = 0, len = inst.siblings.length; i < len; i++)
- {
- s = inst.siblings[i];
- sol = s.type.getCurrentSol();
- sol.select_all = false;
- if (reset_sol)
- {
- cr.clearArray(sol.instances);
- sol.instances[0] = s;
- }
- else
- sol.instances.push(s);
- }
- }
- }
- };
- Acts.prototype.SetEffect = function (effect)
- {
- this.blend_mode = effect;
- this.compositeOp = cr.effectToCompositeOp(effect);
- cr.setGLBlend(this, effect, this.runtime.gl);
- this.runtime.redraw = true;
- };
- Acts.prototype.StopAnim = function ()
- {
- this.animPlaying = false;
- };
- Acts.prototype.StartAnim = function (from)
- {
- this.animPlaying = true;
- this.frameStart = this.getNowTime();
- if (from === 1 && this.cur_frame !== 0)
- {
- this.changeAnimFrame = 0;
- if (!this.inAnimTrigger)
- this.doChangeAnimFrame();
- }
- if (!this.isTicking)
- {
- this.runtime.tickMe(this);
- this.isTicking = true;
- }
- };
- Acts.prototype.SetAnim = function (animname, from)
- {
- this.changeAnimName = animname;
- this.changeAnimFrom = from;
- if (!this.isTicking)
- {
- this.runtime.tickMe(this);
- this.isTicking = true;
- }
- if (!this.inAnimTrigger)
- this.doChangeAnim();
- };
- Acts.prototype.SetAnimFrame = function (framenumber)
- {
- this.changeAnimFrame = framenumber;
- if (!this.isTicking)
- {
- this.runtime.tickMe(this);
- this.isTicking = true;
- }
- if (!this.inAnimTrigger)
- this.doChangeAnimFrame();
- };
- Acts.prototype.SetAnimSpeed = function (s)
- {
- this.cur_anim_speed = cr.abs(s);
- this.animForwards = (s >= 0);
- if (!this.isTicking)
- {
- this.runtime.tickMe(this);
- this.isTicking = true;
- }
- };
- Acts.prototype.SetMirrored = function (m)
- {
- var neww = cr.abs(this.width) * (m === 0 ? -1 : 1);
- if (this.width === neww)
- return;
- this.width = neww;
- this.set_bbox_changed();
- };
- Acts.prototype.SetFlipped = function (f)
- {
- var newh = cr.abs(this.height) * (f === 0 ? -1 : 1);
- if (this.height === newh)
- return;
- this.height = newh;
- this.set_bbox_changed();
- };
- Acts.prototype.SetScale = function (s)
- {
- var cur_frame = this.curFrame;
- var mirror_factor = (this.width < 0 ? -1 : 1);
- var flip_factor = (this.height < 0 ? -1 : 1);
- var new_width = cur_frame.width * s * mirror_factor;
- var new_height = cur_frame.height * s * flip_factor;
- if (this.width !== new_width || this.height !== new_height)
- {
- this.width = new_width;
- this.height = new_height;
- this.set_bbox_changed();
- }
- };
- Acts.prototype.LoadURL = function (url_, resize_)
- {
- var img = new Image();
- var self = this;
- var curFrame_ = this.curFrame;
- img.onload = function ()
- {
- if (curFrame_.texture_img.src === img.src)
- {
- if (self.runtime.glwrap && self.curFrame === curFrame_)
- self.curWebGLTexture = curFrame_.webGL_texture;
- if (resize_ === 0) // resize to image size
- {
- self.width = img.width;
- self.height = img.height;
- self.set_bbox_changed();
- }
- self.runtime.redraw = true;
- self.runtime.trigger(cr.plugins_.Sprite.prototype.cnds.OnURLLoaded, self);
- return;
- }
- curFrame_.texture_img = img;
- curFrame_.offx = 0;
- curFrame_.offy = 0;
- curFrame_.width = img.width;
- curFrame_.height = img.height;
- curFrame_.spritesheeted = false;
- curFrame_.datauri = "";
- curFrame_.pixelformat = 0; // reset to RGBA, since we don't know what type of image will have come in
- if (self.runtime.glwrap)
- {
- if (curFrame_.webGL_texture)
- self.runtime.glwrap.deleteTexture(curFrame_.webGL_texture);
- curFrame_.webGL_texture = self.runtime.glwrap.loadTexture(img, false, self.runtime.linearSampling);
- if (self.curFrame === curFrame_)
- self.curWebGLTexture = curFrame_.webGL_texture;
- self.type.updateAllCurrentTexture();
- }
- if (resize_ === 0) // resize to image size
- {
- self.width = img.width;
- self.height = img.height;
- self.set_bbox_changed();
- }
- self.runtime.redraw = true;
- self.runtime.trigger(cr.plugins_.Sprite.prototype.cnds.OnURLLoaded, self);
- };
- if (url_.substr(0, 5) !== "data:")
- img["crossOrigin"] = "anonymous";
- img.src = url_;
- };
- Acts.prototype.SetCollisions = function (set_)
- {
- if (this.collisionsEnabled === (set_ !== 0))
- return; // no change
- this.collisionsEnabled = (set_ !== 0);
- if (this.collisionsEnabled)
- this.set_bbox_changed(); // needs to be added back to cells
- else
- {
- if (this.collcells.right >= this.collcells.left)
- this.type.collision_grid.update(this, this.collcells, null);
- this.collcells.set(0, 0, -1, -1);
- }
- };
- pluginProto.acts = new Acts();
- function Exps() {};
- Exps.prototype.AnimationFrame = function (ret)
- {
- ret.set_int(this.cur_frame);
- };
- Exps.prototype.AnimationFrameCount = function (ret)
- {
- ret.set_int(this.cur_animation.frames.length);
- };
- Exps.prototype.AnimationName = function (ret)
- {
- ret.set_string(this.cur_animation.name);
- };
- Exps.prototype.AnimationSpeed = function (ret)
- {
- ret.set_float(this.animForwards ? this.cur_anim_speed : -this.cur_anim_speed);
- };
- Exps.prototype.ImagePointX = function (ret, imgpt)
- {
- ret.set_float(this.getImagePoint(imgpt, true));
- };
- Exps.prototype.ImagePointY = function (ret, imgpt)
- {
- ret.set_float(this.getImagePoint(imgpt, false));
- };
- Exps.prototype.ImagePointCount = function (ret)
- {
- ret.set_int(this.curFrame.image_points.length);
- };
- Exps.prototype.ImageWidth = function (ret)
- {
- ret.set_float(this.curFrame.width);
- };
- Exps.prototype.ImageHeight = function (ret)
- {
- ret.set_float(this.curFrame.height);
- };
- pluginProto.exps = new Exps();
- }());
- /* global cr,log,assert2 */
- /* jshint globalstrict: true */
- /* jshint strict: true */
- ;
- ;
- cr.plugins_.Spritefont2 = function(runtime)
- {
- this.runtime = runtime;
- };
- (function ()
- {
- var pluginProto = cr.plugins_.Spritefont2.prototype;
- pluginProto.onCreate = function ()
- {
- };
- pluginProto.Type = function(plugin)
- {
- this.plugin = plugin;
- this.runtime = plugin.runtime;
- };
- var typeProto = pluginProto.Type.prototype;
- typeProto.onCreate = function()
- {
- if (this.is_family)
- return;
- this.texture_img = new Image();
- this.runtime.waitForImageLoad(this.texture_img, this.texture_file);
- this.webGL_texture = null;
- };
- typeProto.onLostWebGLContext = function ()
- {
- if (this.is_family)
- return;
- this.webGL_texture = null;
- };
- typeProto.onRestoreWebGLContext = function ()
- {
- if (this.is_family || !this.instances.length)
- return;
- if (!this.webGL_texture)
- {
- this.webGL_texture = this.runtime.glwrap.loadTexture(this.texture_img, false, this.runtime.linearSampling, this.texture_pixelformat);
- }
- var i, len;
- for (i = 0, len = this.instances.length; i < len; i++)
- this.instances[i].webGL_texture = this.webGL_texture;
- };
- typeProto.unloadTextures = function ()
- {
- if (this.is_family || this.instances.length || !this.webGL_texture)
- return;
- this.runtime.glwrap.deleteTexture(this.webGL_texture);
- this.webGL_texture = null;
- };
- typeProto.preloadCanvas2D = function (ctx)
- {
- ctx.drawImage(this.texture_img, 0, 0);
- };
- pluginProto.Instance = function(type)
- {
- this.type = type;
- this.runtime = type.runtime;
- };
- var instanceProto = pluginProto.Instance.prototype;
- instanceProto.onDestroy = function()
- {
- freeAllLines (this.lines);
- freeAllClip (this.clipList);
- freeAllClipUV(this.clipUV);
- cr.wipe(this.characterWidthList);
- };
- instanceProto.onCreate = function()
- {
- this.texture_img = this.type.texture_img;
- this.characterWidth = this.properties[0];
- this.characterHeight = this.properties[1];
- this.characterSet = this.properties[2];
- this.text = this.properties[3];
- this.characterScale = this.properties[4];
- this.visible = (this.properties[5] === 0); // 0=visible, 1=invisible
- this.halign = this.properties[6]/2.0; // 0=left, 1=center, 2=right
- this.valign = this.properties[7]/2.0; // 0=top, 1=center, 2=bottom
- this.wrapbyword = (this.properties[9] === 0); // 0=word, 1=character
- this.characterSpacing = this.properties[10];
- this.lineHeight = this.properties[11];
- this.textWidth = 0;
- this.textHeight = 0;
- if (this.recycled)
- {
- cr.clearArray(this.lines);
- cr.wipe(this.clipList);
- cr.wipe(this.clipUV);
- cr.wipe(this.characterWidthList);
- }
- else
- {
- this.lines = [];
- this.clipList = {};
- this.clipUV = {};
- this.characterWidthList = {};
- }
- this.text_changed = true;
- this.lastwrapwidth = this.width;
- if (this.runtime.glwrap)
- {
- if (!this.type.webGL_texture)
- {
- this.type.webGL_texture = this.runtime.glwrap.loadTexture(this.type.texture_img, false, this.runtime.linearSampling, this.type.texture_pixelformat);
- }
- this.webGL_texture = this.type.webGL_texture;
- }
- this.SplitSheet();
- };
- instanceProto.saveToJSON = function ()
- {
- var save = {
- "t": this.text,
- "csc": this.characterScale,
- "csp": this.characterSpacing,
- "lh": this.lineHeight,
- "tw": this.textWidth,
- "th": this.textHeight,
- "lrt": this.last_render_tick,
- "ha": this.halign,
- "va": this.valign,
- "cw": {}
- };
- for (var ch in this.characterWidthList)
- save["cw"][ch] = this.characterWidthList[ch];
- return save;
- };
- instanceProto.loadFromJSON = function (o)
- {
- this.text = o["t"];
- this.characterScale = o["csc"];
- this.characterSpacing = o["csp"];
- this.lineHeight = o["lh"];
- this.textWidth = o["tw"];
- this.textHeight = o["th"];
- this.last_render_tick = o["lrt"];
- if (o.hasOwnProperty("ha"))
- this.halign = o["ha"];
- if (o.hasOwnProperty("va"))
- this.valign = o["va"];
- for(var ch in o["cw"])
- this.characterWidthList[ch] = o["cw"][ch];
- this.text_changed = true;
- this.lastwrapwidth = this.width;
- };
- function trimRight(text)
- {
- return text.replace(/\s\s*$/, '');
- }
- var MAX_CACHE_SIZE = 1000;
- function alloc(cache,Constructor)
- {
- if (cache.length)
- return cache.pop();
- else
- return new Constructor();
- }
- function free(cache,data)
- {
- if (cache.length < MAX_CACHE_SIZE)
- {
- cache.push(data);
- }
- }
- function freeAll(cache,dataList,isArray)
- {
- if (isArray) {
- var i, len;
- for (i = 0, len = dataList.length; i < len; i++)
- {
- free(cache,dataList[i]);
- }
- cr.clearArray(dataList);
- } else {
- var prop;
- for(prop in dataList) {
- if(Object.prototype.hasOwnProperty.call(dataList,prop)) {
- free(cache,dataList[prop]);
- delete dataList[prop];
- }
- }
- }
- }
- function addLine(inst,lineIndex,cur_line) {
- var lines = inst.lines;
- var line;
- cur_line = trimRight(cur_line);
- if (lineIndex >= lines.length)
- lines.push(allocLine());
- line = lines[lineIndex];
- line.text = cur_line;
- line.width = inst.measureWidth(cur_line);
- inst.textWidth = cr.max(inst.textWidth,line.width);
- }
- var linesCache = [];
- function allocLine() { return alloc(linesCache,Object); }
- function freeLine(l) { free(linesCache,l); }
- function freeAllLines(arr) { freeAll(linesCache,arr,true); }
- function addClip(obj,property,x,y,w,h) {
- if (obj[property] === undefined) {
- obj[property] = alloc(clipCache,Object);
- }
- obj[property].x = x;
- obj[property].y = y;
- obj[property].w = w;
- obj[property].h = h;
- }
- var clipCache = [];
- function allocClip() { return alloc(clipCache,Object); }
- function freeAllClip(obj) { freeAll(clipCache,obj,false);}
- function addClipUV(obj,property,left,top,right,bottom) {
- if (obj[property] === undefined) {
- obj[property] = alloc(clipUVCache,cr.rect);
- }
- obj[property].left = left;
- obj[property].top = top;
- obj[property].right = right;
- obj[property].bottom = bottom;
- }
- var clipUVCache = [];
- function allocClipUV() { return alloc(clipUVCache,cr.rect);}
- function freeAllClipUV(obj) { freeAll(clipUVCache,obj,false);}
- instanceProto.SplitSheet = function() {
- var texture = this.texture_img;
- var texWidth = texture.width;
- var texHeight = texture.height;
- var charWidth = this.characterWidth;
- var charHeight = this.characterHeight;
- var charU = charWidth /texWidth;
- var charV = charHeight/texHeight;
- var charSet = this.characterSet ;
- var cols = Math.floor(texWidth/charWidth);
- var rows = Math.floor(texHeight/charHeight);
- for ( var c = 0; c < charSet.length; c++) {
- if (c >= cols * rows) break;
- var x = c%cols;
- var y = Math.floor(c/cols);
- var letter = charSet.charAt(c);
- if (this.runtime.glwrap) {
- addClipUV(
- this.clipUV, letter,
- x * charU ,
- y * charV ,
- (x+1) * charU ,
- (y+1) * charV
- );
- } else {
- addClip(
- this.clipList, letter,
- x * charWidth,
- y * charHeight,
- charWidth,
- charHeight
- );
- }
- }
- };
- /*
- * Word-Wrapping
- */
- var wordsCache = [];
- pluginProto.TokeniseWords = function (text)
- {
- cr.clearArray(wordsCache);
- var cur_word = "";
- var ch;
- var i = 0;
- while (i < text.length)
- {
- ch = text.charAt(i);
- if (ch === "\n")
- {
- if (cur_word.length)
- {
- wordsCache.push(cur_word);
- cur_word = "";
- }
- wordsCache.push("\n");
- ++i;
- }
- else if (ch === " " || ch === "\t" || ch === "-")
- {
- do {
- cur_word += text.charAt(i);
- i++;
- }
- while (i < text.length && (text.charAt(i) === " " || text.charAt(i) === "\t"));
- wordsCache.push(cur_word);
- cur_word = "";
- }
- else if (i < text.length)
- {
- cur_word += ch;
- i++;
- }
- }
- if (cur_word.length)
- wordsCache.push(cur_word);
- };
- pluginProto.WordWrap = function (inst)
- {
- var text = inst.text;
- var lines = inst.lines;
- if (!text || !text.length)
- {
- freeAllLines(lines);
- return;
- }
- var width = inst.width;
- if (width <= 2.0)
- {
- freeAllLines(lines);
- return;
- }
- var charWidth = inst.characterWidth;
- var charScale = inst.characterScale;
- var charSpacing = inst.characterSpacing;
- if ( (text.length * (charWidth * charScale + charSpacing) - charSpacing) <= width && text.indexOf("\n") === -1)
- {
- var all_width = inst.measureWidth(text);
- if (all_width <= width)
- {
- freeAllLines(lines);
- lines.push(allocLine());
- lines[0].text = text;
- lines[0].width = all_width;
- inst.textWidth = all_width;
- inst.textHeight = inst.characterHeight * charScale + inst.lineHeight;
- return;
- }
- }
- var wrapbyword = inst.wrapbyword;
- this.WrapText(inst);
- inst.textHeight = lines.length * (inst.characterHeight * charScale + inst.lineHeight);
- };
- pluginProto.WrapText = function (inst)
- {
- var wrapbyword = inst.wrapbyword;
- var text = inst.text;
- var lines = inst.lines;
- var width = inst.width;
- var wordArray;
- if (wrapbyword) {
- this.TokeniseWords(text); // writes to wordsCache
- wordArray = wordsCache;
- } else {
- wordArray = text;
- }
- var cur_line = "";
- var prev_line;
- var line_width;
- var i;
- var lineIndex = 0;
- var line;
- var ignore_newline = false;
- for (i = 0; i < wordArray.length; i++)
- {
- if (wordArray[i] === "\n")
- {
- if (ignore_newline === true) {
- ignore_newline = false;
- } else {
- addLine(inst,lineIndex,cur_line);
- lineIndex++;
- }
- cur_line = "";
- continue;
- }
- ignore_newline = false;
- prev_line = cur_line;
- cur_line += wordArray[i];
- line_width = inst.measureWidth(trimRight(cur_line));
- if (line_width > width)
- {
- if (prev_line === "") {
- addLine(inst,lineIndex,cur_line);
- cur_line = "";
- ignore_newline = true;
- } else {
- addLine(inst,lineIndex,prev_line);
- cur_line = wordArray[i];
- }
- lineIndex++;
- if (!wrapbyword && cur_line === " ")
- cur_line = "";
- }
- }
- if (trimRight(cur_line).length)
- {
- addLine(inst,lineIndex,cur_line);
- lineIndex++;
- }
- for (i = lineIndex; i < lines.length; i++)
- freeLine(lines[i]);
- lines.length = lineIndex;
- };
- instanceProto.measureWidth = function(text) {
- var spacing = this.characterSpacing;
- var len = text.length;
- var width = 0;
- for (var i = 0; i < len; i++) {
- width += this.getCharacterWidth(text.charAt(i)) * this.characterScale + spacing;
- }
- width -= (width > 0) ? spacing : 0;
- return width;
- };
- /***/
- instanceProto.getCharacterWidth = function(character) {
- var widthList = this.characterWidthList;
- if (widthList[character] !== undefined) {
- return widthList[character];
- } else {
- return this.characterWidth;
- }
- };
- instanceProto.rebuildText = function() {
- if (this.text_changed || this.width !== this.lastwrapwidth) {
- this.textWidth = 0;
- this.textHeight = 0;
- this.type.plugin.WordWrap(this);
- this.text_changed = false;
- this.lastwrapwidth = this.width;
- }
- };
- var EPSILON = 0.00001;
- instanceProto.draw = function(ctx, glmode)
- {
- var texture = this.texture_img;
- if (this.text !== "" && texture != null) {
- this.rebuildText();
- if (this.height < this.characterHeight*this.characterScale + this.lineHeight) {
- return;
- }
- ctx.globalAlpha = this.opacity;
- var myx = this.x;
- var myy = this.y;
- if (this.runtime.pixel_rounding)
- {
- myx = Math.round(myx);
- myy = Math.round(myy);
- }
- var viewLeft = this.layer.viewLeft;
- var viewTop = this.layer.viewTop;
- var viewRight = this.layer.viewRight;
- var viewBottom = this.layer.viewBottom;
- ctx.save();
- ctx.translate(myx, myy);
- ctx.rotate(this.angle);
- var ha = this.halign;
- var va = this.valign;
- var scale = this.characterScale;
- var charHeight = this.characterHeight * scale;
- var lineHeight = this.lineHeight;
- var charSpace = this.characterSpacing;
- var lines = this.lines;
- var textHeight = this.textHeight;
- var letterWidth;
- var halign;
- var valign = va * cr.max(0,(this.height - textHeight));
- var offx = -(this.hotspotX * this.width);
- var offy = -(this.hotspotY * this.height);
- offy += valign;
- var drawX ;
- var drawY = offy;
- var roundX, roundY;
- for(var i = 0; i < lines.length; i++) {
- var line = lines[i].text;
- var len = lines[i].width;
- halign = ha * cr.max(0,this.width - len);
- drawX = offx + halign;
- drawY += lineHeight;
- if (myy + drawY + charHeight < viewTop)
- {
- drawY += charHeight;
- continue;
- }
- for(var j = 0; j < line.length; j++) {
- var letter = line.charAt(j);
- letterWidth = this.getCharacterWidth(letter);
- var clip = this.clipList[letter];
- if (myx + drawX + letterWidth * scale + charSpace < viewLeft)
- {
- drawX += letterWidth * scale + charSpace;
- continue;
- }
- if ( drawX + letterWidth * scale > this.width + EPSILON ) {
- break;
- }
- if (clip !== undefined) {
- roundX = drawX;
- roundY = drawY;
- if (this.angle === 0)
- {
- roundX = Math.round(roundX);
- roundY = Math.round(roundY);
- }
- ctx.drawImage( this.texture_img,
- clip.x, clip.y, clip.w, clip.h,
- roundX,roundY,clip.w*scale,clip.h*scale);
- }
- drawX += letterWidth * scale + charSpace;
- if (myx + drawX > viewRight)
- break;
- }
- drawY += charHeight;
- if (drawY + charHeight + lineHeight > this.height || myy + drawY > viewBottom)
- {
- break;
- }
- }
- ctx.restore();
- }
- };
- var dQuad = new cr.quad();
- function rotateQuad(quad,cosa,sina) {
- var x_temp;
- x_temp = (quad.tlx * cosa) - (quad.tly * sina);
- quad.tly = (quad.tly * cosa) + (quad.tlx * sina);
- quad.tlx = x_temp;
- x_temp = (quad.trx * cosa) - (quad.try_ * sina);
- quad.try_ = (quad.try_ * cosa) + (quad.trx * sina);
- quad.trx = x_temp;
- x_temp = (quad.blx * cosa) - (quad.bly * sina);
- quad.bly = (quad.bly * cosa) + (quad.blx * sina);
- quad.blx = x_temp;
- x_temp = (quad.brx * cosa) - (quad.bry * sina);
- quad.bry = (quad.bry * cosa) + (quad.brx * sina);
- quad.brx = x_temp;
- }
- instanceProto.drawGL = function(glw)
- {
- glw.setTexture(this.webGL_texture);
- glw.setOpacity(this.opacity);
- if (!this.text)
- return;
- this.rebuildText();
- if (this.height < this.characterHeight*this.characterScale + this.lineHeight) {
- return;
- }
- this.update_bbox();
- var q = this.bquad;
- var ox = 0;
- var oy = 0;
- if (this.runtime.pixel_rounding)
- {
- ox = Math.round(this.x) - this.x;
- oy = Math.round(this.y) - this.y;
- }
- var viewLeft = this.layer.viewLeft;
- var viewTop = this.layer.viewTop;
- var viewRight = this.layer.viewRight;
- var viewBottom = this.layer.viewBottom;
- var angle = this.angle;
- var ha = this.halign;
- var va = this.valign;
- var scale = this.characterScale;
- var charHeight = this.characterHeight * scale; // to precalculate in onCreate or on change
- var lineHeight = this.lineHeight;
- var charSpace = this.characterSpacing;
- var lines = this.lines;
- var textHeight = this.textHeight;
- var letterWidth;
- var cosa,sina;
- if (angle !== 0)
- {
- cosa = Math.cos(angle);
- sina = Math.sin(angle);
- }
- var halign;
- var valign = va * cr.max(0,(this.height - textHeight));
- var offx = q.tlx + ox;
- var offy = q.tly + oy;
- var drawX ;
- var drawY = valign;
- var roundX, roundY;
- for(var i = 0; i < lines.length; i++) {
- var line = lines[i].text;
- var lineWidth = lines[i].width;
- halign = ha * cr.max(0,this.width - lineWidth);
- drawX = halign;
- drawY += lineHeight;
- if (angle === 0 && offy + drawY + charHeight < viewTop)
- {
- drawY += charHeight;
- continue;
- }
- for(var j = 0; j < line.length; j++) {
- var letter = line.charAt(j);
- letterWidth = this.getCharacterWidth(letter);
- var clipUV = this.clipUV[letter];
- if (offx + drawX + letterWidth * scale + charSpace < viewLeft)
- {
- drawX += letterWidth * scale + charSpace;
- continue;
- }
- if (drawX + letterWidth * scale > this.width + EPSILON)
- {
- break;
- }
- if (clipUV !== undefined) {
- var clipWidth = this.characterWidth*scale;
- var clipHeight = this.characterHeight*scale;
- roundX = drawX;
- roundY = drawY;
- if (angle === 0)
- {
- roundX = Math.round(roundX);
- roundY = Math.round(roundY);
- }
- dQuad.tlx = roundX;
- dQuad.tly = roundY;
- dQuad.trx = roundX + clipWidth;
- dQuad.try_ = roundY ;
- dQuad.blx = roundX;
- dQuad.bly = roundY + clipHeight;
- dQuad.brx = roundX + clipWidth;
- dQuad.bry = roundY + clipHeight;
- if(angle !== 0)
- {
- rotateQuad(dQuad,cosa,sina);
- }
- dQuad.offset(offx,offy);
- glw.quadTex(
- dQuad.tlx, dQuad.tly,
- dQuad.trx, dQuad.try_,
- dQuad.brx, dQuad.bry,
- dQuad.blx, dQuad.bly,
- clipUV
- );
- }
- drawX += letterWidth * scale + charSpace;
- if (angle === 0 && offx + drawX > viewRight)
- break;
- }
- drawY += charHeight;
- if (drawY + charHeight + lineHeight > this.height || offy + drawY > viewBottom)
- {
- break;
- }
- }
- };
- function Cnds() {}
- Cnds.prototype.CompareText = function(text_to_compare, case_sensitive)
- {
- if (case_sensitive)
- return this.text == text_to_compare;
- else
- return cr.equals_nocase(this.text, text_to_compare);
- };
- pluginProto.cnds = new Cnds();
- function Acts() {}
- Acts.prototype.SetText = function(param)
- {
- if (cr.is_number(param) && param < 1e9)
- param = Math.round(param * 1e10) / 1e10; // round to nearest ten billionth - hides floating point errors
- var text_to_set = param.toString();
- if (this.text !== text_to_set)
- {
- this.text = text_to_set;
- this.text_changed = true;
- this.runtime.redraw = true;
- }
- };
- Acts.prototype.AppendText = function(param)
- {
- if (cr.is_number(param))
- param = Math.round(param * 1e10) / 1e10; // round to nearest ten billionth - hides floating point errors
- var text_to_append = param.toString();
- if (text_to_append) // not empty
- {
- this.text += text_to_append;
- this.text_changed = true;
- this.runtime.redraw = true;
- }
- };
- Acts.prototype.SetScale = function(param)
- {
- if (param !== this.characterScale) {
- this.characterScale = param;
- this.text_changed = true;
- this.runtime.redraw = true;
- }
- };
- Acts.prototype.SetCharacterSpacing = function(param)
- {
- if (param !== this.CharacterSpacing) {
- this.characterSpacing = param;
- this.text_changed = true;
- this.runtime.redraw = true;
- }
- };
- Acts.prototype.SetLineHeight = function(param)
- {
- if (param !== this.lineHeight) {
- this.lineHeight = param;
- this.text_changed = true;
- this.runtime.redraw = true;
- }
- };
- instanceProto.SetCharWidth = function(character,width) {
- var w = parseInt(width,10);
- if (this.characterWidthList[character] !== w) {
- this.characterWidthList[character] = w;
- this.text_changed = true;
- this.runtime.redraw = true;
- }
- };
- Acts.prototype.SetCharacterWidth = function(characterSet,width)
- {
- if (characterSet !== "") {
- for(var c = 0; c < characterSet.length; c++) {
- this.SetCharWidth(characterSet.charAt(c),width);
- }
- }
- };
- Acts.prototype.SetEffect = function (effect)
- {
- this.blend_mode = effect;
- this.compositeOp = cr.effectToCompositeOp(effect);
- cr.setGLBlend(this, effect, this.runtime.gl);
- this.runtime.redraw = true;
- };
- Acts.prototype.SetHAlign = function (a)
- {
- this.halign = a / 2.0;
- this.text_changed = true;
- this.runtime.redraw = true;
- };
- Acts.prototype.SetVAlign = function (a)
- {
- this.valign = a / 2.0;
- this.text_changed = true;
- this.runtime.redraw = true;
- };
- pluginProto.acts = new Acts();
- function Exps() {}
- Exps.prototype.CharacterWidth = function(ret,character)
- {
- ret.set_int(this.getCharacterWidth(character));
- };
- Exps.prototype.CharacterHeight = function(ret)
- {
- ret.set_int(this.characterHeight);
- };
- Exps.prototype.CharacterScale = function(ret)
- {
- ret.set_float(this.characterScale);
- };
- Exps.prototype.CharacterSpacing = function(ret)
- {
- ret.set_int(this.characterSpacing);
- };
- Exps.prototype.LineHeight = function(ret)
- {
- ret.set_int(this.lineHeight);
- };
- Exps.prototype.Text = function(ret)
- {
- ret.set_string(this.text);
- };
- Exps.prototype.TextWidth = function (ret)
- {
- this.rebuildText();
- ret.set_float(this.textWidth);
- };
- Exps.prototype.TextHeight = function (ret)
- {
- this.rebuildText();
- ret.set_float(this.textHeight);
- };
- pluginProto.exps = new Exps();
- }());
- ;
- ;
- cr.plugins_.Text = function(runtime)
- {
- this.runtime = runtime;
- };
- (function ()
- {
- var pluginProto = cr.plugins_.Text.prototype;
- pluginProto.onCreate = function ()
- {
- pluginProto.acts.SetWidth = function (w)
- {
- if (this.width !== w)
- {
- this.width = w;
- this.text_changed = true; // also recalculate text wrapping
- this.set_bbox_changed();
- }
- };
- };
- pluginProto.Type = function(plugin)
- {
- this.plugin = plugin;
- this.runtime = plugin.runtime;
- };
- var typeProto = pluginProto.Type.prototype;
- typeProto.onCreate = function()
- {
- };
- typeProto.onLostWebGLContext = function ()
- {
- if (this.is_family)
- return;
- var i, len, inst;
- for (i = 0, len = this.instances.length; i < len; i++)
- {
- inst = this.instances[i];
- inst.mycanvas = null;
- inst.myctx = null;
- inst.mytex = null;
- }
- };
- pluginProto.Instance = function(type)
- {
- this.type = type;
- this.runtime = type.runtime;
- if (this.recycled)
- cr.clearArray(this.lines);
- else
- this.lines = []; // for word wrapping
- this.text_changed = true;
- };
- var instanceProto = pluginProto.Instance.prototype;
- var requestedWebFonts = {}; // already requested web fonts have an entry here
- instanceProto.onCreate = function()
- {
- this.text = this.properties[0];
- this.visible = (this.properties[1] === 0); // 0=visible, 1=invisible
- this.font = this.properties[2];
- this.color = this.properties[3];
- this.halign = this.properties[4]; // 0=left, 1=center, 2=right
- this.valign = this.properties[5]; // 0=top, 1=center, 2=bottom
- this.wrapbyword = (this.properties[7] === 0); // 0=word, 1=character
- this.lastwidth = this.width;
- this.lastwrapwidth = this.width;
- this.lastheight = this.height;
- this.line_height_offset = this.properties[8];
- this.facename = "";
- this.fontstyle = "";
- this.ptSize = 0;
- this.textWidth = 0;
- this.textHeight = 0;
- this.parseFont();
- this.mycanvas = null;
- this.myctx = null;
- this.mytex = null;
- this.need_text_redraw = false;
- this.last_render_tick = this.runtime.tickcount;
- if (this.recycled)
- this.rcTex.set(0, 0, 1, 1);
- else
- this.rcTex = new cr.rect(0, 0, 1, 1);
- if (this.runtime.glwrap)
- this.runtime.tickMe(this);
- ;
- };
- instanceProto.parseFont = function ()
- {
- var arr = this.font.split(" ");
- var i;
- for (i = 0; i < arr.length; i++)
- {
- if (arr[i].substr(arr[i].length - 2, 2) === "pt")
- {
- this.ptSize = parseInt(arr[i].substr(0, arr[i].length - 2));
- this.pxHeight = Math.ceil((this.ptSize / 72.0) * 96.0) + 4; // assume 96dpi...
- if (i > 0)
- this.fontstyle = arr[i - 1];
- this.facename = arr[i + 1];
- for (i = i + 2; i < arr.length; i++)
- this.facename += " " + arr[i];
- break;
- }
- }
- };
- instanceProto.saveToJSON = function ()
- {
- return {
- "t": this.text,
- "f": this.font,
- "c": this.color,
- "ha": this.halign,
- "va": this.valign,
- "wr": this.wrapbyword,
- "lho": this.line_height_offset,
- "fn": this.facename,
- "fs": this.fontstyle,
- "ps": this.ptSize,
- "pxh": this.pxHeight,
- "tw": this.textWidth,
- "th": this.textHeight,
- "lrt": this.last_render_tick
- };
- };
- instanceProto.loadFromJSON = function (o)
- {
- this.text = o["t"];
- this.font = o["f"];
- this.color = o["c"];
- this.halign = o["ha"];
- this.valign = o["va"];
- this.wrapbyword = o["wr"];
- this.line_height_offset = o["lho"];
- this.facename = o["fn"];
- this.fontstyle = o["fs"];
- this.ptSize = o["ps"];
- this.pxHeight = o["pxh"];
- this.textWidth = o["tw"];
- this.textHeight = o["th"];
- this.last_render_tick = o["lrt"];
- this.text_changed = true;
- this.lastwidth = this.width;
- this.lastwrapwidth = this.width;
- this.lastheight = this.height;
- };
- instanceProto.tick = function ()
- {
- if (this.runtime.glwrap && this.mytex && (this.runtime.tickcount - this.last_render_tick >= 300))
- {
- var layer = this.layer;
- this.update_bbox();
- var bbox = this.bbox;
- if (bbox.right < layer.viewLeft || bbox.bottom < layer.viewTop || bbox.left > layer.viewRight || bbox.top > layer.viewBottom)
- {
- this.runtime.glwrap.deleteTexture(this.mytex);
- this.mytex = null;
- this.myctx = null;
- this.mycanvas = null;
- }
- }
- };
- instanceProto.onDestroy = function ()
- {
- this.myctx = null;
- this.mycanvas = null;
- if (this.runtime.glwrap && this.mytex)
- this.runtime.glwrap.deleteTexture(this.mytex);
- this.mytex = null;
- };
- instanceProto.updateFont = function ()
- {
- this.font = this.fontstyle + " " + this.ptSize.toString() + "pt " + this.facename;
- this.text_changed = true;
- this.runtime.redraw = true;
- };
- instanceProto.draw = function(ctx, glmode)
- {
- ctx.font = this.font;
- ctx.textBaseline = "top";
- ctx.fillStyle = this.color;
- ctx.globalAlpha = glmode ? 1 : this.opacity;
- var myscale = 1;
- if (glmode)
- {
- myscale = this.layer.getScale();
- ctx.save();
- ctx.scale(myscale, myscale);
- }
- if (this.text_changed || this.width !== this.lastwrapwidth)
- {
- this.type.plugin.WordWrap(this.text, this.lines, ctx, this.width, this.wrapbyword);
- this.text_changed = false;
- this.lastwrapwidth = this.width;
- }
- this.update_bbox();
- var penX = glmode ? 0 : this.bquad.tlx;
- var penY = glmode ? 0 : this.bquad.tly;
- if (this.runtime.pixel_rounding)
- {
- penX = (penX + 0.5) | 0;
- penY = (penY + 0.5) | 0;
- }
- if (this.angle !== 0 && !glmode)
- {
- ctx.save();
- ctx.translate(penX, penY);
- ctx.rotate(this.angle);
- penX = 0;
- penY = 0;
- }
- var endY = penY + this.height;
- var line_height = this.pxHeight;
- line_height += this.line_height_offset;
- var drawX;
- var i;
- if (this.valign === 1) // center
- penY += Math.max(this.height / 2 - (this.lines.length * line_height) / 2, 0);
- else if (this.valign === 2) // bottom
- penY += Math.max(this.height - (this.lines.length * line_height) - 2, 0);
- for (i = 0; i < this.lines.length; i++)
- {
- drawX = penX;
- if (this.halign === 1) // center
- drawX = penX + (this.width - this.lines[i].width) / 2;
- else if (this.halign === 2) // right
- drawX = penX + (this.width - this.lines[i].width);
- ctx.fillText(this.lines[i].text, drawX, penY);
- penY += line_height;
- if (penY >= endY - line_height)
- break;
- }
- if (this.angle !== 0 || glmode)
- ctx.restore();
- this.last_render_tick = this.runtime.tickcount;
- };
- instanceProto.drawGL = function(glw)
- {
- if (this.width < 1 || this.height < 1)
- return;
- var need_redraw = this.text_changed || this.need_text_redraw;
- this.need_text_redraw = false;
- var layer_scale = this.layer.getScale();
- var layer_angle = this.layer.getAngle();
- var rcTex = this.rcTex;
- var floatscaledwidth = layer_scale * this.width;
- var floatscaledheight = layer_scale * this.height;
- var scaledwidth = Math.ceil(floatscaledwidth);
- var scaledheight = Math.ceil(floatscaledheight);
- var halfw = this.runtime.draw_width / 2;
- var halfh = this.runtime.draw_height / 2;
- if (!this.myctx)
- {
- this.mycanvas = document.createElement("canvas");
- this.mycanvas.width = scaledwidth;
- this.mycanvas.height = scaledheight;
- this.lastwidth = scaledwidth;
- this.lastheight = scaledheight;
- need_redraw = true;
- this.myctx = this.mycanvas.getContext("2d");
- }
- if (scaledwidth !== this.lastwidth || scaledheight !== this.lastheight)
- {
- this.mycanvas.width = scaledwidth;
- this.mycanvas.height = scaledheight;
- if (this.mytex)
- {
- glw.deleteTexture(this.mytex);
- this.mytex = null;
- }
- need_redraw = true;
- }
- if (need_redraw)
- {
- this.myctx.clearRect(0, 0, scaledwidth, scaledheight);
- this.draw(this.myctx, true);
- if (!this.mytex)
- this.mytex = glw.createEmptyTexture(scaledwidth, scaledheight, this.runtime.linearSampling, this.runtime.isMobile);
- glw.videoToTexture(this.mycanvas, this.mytex, this.runtime.isMobile);
- }
- this.lastwidth = scaledwidth;
- this.lastheight = scaledheight;
- glw.setTexture(this.mytex);
- glw.setOpacity(this.opacity);
- glw.resetModelView();
- glw.translate(-halfw, -halfh);
- glw.updateModelView();
- var q = this.bquad;
- var tlx = this.layer.layerToCanvas(q.tlx, q.tly, true, true);
- var tly = this.layer.layerToCanvas(q.tlx, q.tly, false, true);
- var trx = this.layer.layerToCanvas(q.trx, q.try_, true, true);
- var try_ = this.layer.layerToCanvas(q.trx, q.try_, false, true);
- var brx = this.layer.layerToCanvas(q.brx, q.bry, true, true);
- var bry = this.layer.layerToCanvas(q.brx, q.bry, false, true);
- var blx = this.layer.layerToCanvas(q.blx, q.bly, true, true);
- var bly = this.layer.layerToCanvas(q.blx, q.bly, false, true);
- if (this.runtime.pixel_rounding || (this.angle === 0 && layer_angle === 0))
- {
- var ox = ((tlx + 0.5) | 0) - tlx;
- var oy = ((tly + 0.5) | 0) - tly
- tlx += ox;
- tly += oy;
- trx += ox;
- try_ += oy;
- brx += ox;
- bry += oy;
- blx += ox;
- bly += oy;
- }
- if (this.angle === 0 && layer_angle === 0)
- {
- trx = tlx + scaledwidth;
- try_ = tly;
- brx = trx;
- bry = tly + scaledheight;
- blx = tlx;
- bly = bry;
- rcTex.right = 1;
- rcTex.bottom = 1;
- }
- else
- {
- rcTex.right = floatscaledwidth / scaledwidth;
- rcTex.bottom = floatscaledheight / scaledheight;
- }
- glw.quadTex(tlx, tly, trx, try_, brx, bry, blx, bly, rcTex);
- glw.resetModelView();
- glw.scale(layer_scale, layer_scale);
- glw.rotateZ(-this.layer.getAngle());
- glw.translate((this.layer.viewLeft + this.layer.viewRight) / -2, (this.layer.viewTop + this.layer.viewBottom) / -2);
- glw.updateModelView();
- this.last_render_tick = this.runtime.tickcount;
- };
- var wordsCache = [];
- pluginProto.TokeniseWords = function (text)
- {
- cr.clearArray(wordsCache);
- var cur_word = "";
- var ch;
- var i = 0;
- while (i < text.length)
- {
- ch = text.charAt(i);
- if (ch === "\n")
- {
- if (cur_word.length)
- {
- wordsCache.push(cur_word);
- cur_word = "";
- }
- wordsCache.push("\n");
- ++i;
- }
- else if (ch === " " || ch === "\t" || ch === "-")
- {
- do {
- cur_word += text.charAt(i);
- i++;
- }
- while (i < text.length && (text.charAt(i) === " " || text.charAt(i) === "\t"));
- wordsCache.push(cur_word);
- cur_word = "";
- }
- else if (i < text.length)
- {
- cur_word += ch;
- i++;
- }
- }
- if (cur_word.length)
- wordsCache.push(cur_word);
- };
- var linesCache = [];
- function allocLine()
- {
- if (linesCache.length)
- return linesCache.pop();
- else
- return {};
- };
- function freeLine(l)
- {
- linesCache.push(l);
- };
- function freeAllLines(arr)
- {
- var i, len;
- for (i = 0, len = arr.length; i < len; i++)
- {
- freeLine(arr[i]);
- }
- cr.clearArray(arr);
- };
- pluginProto.WordWrap = function (text, lines, ctx, width, wrapbyword)
- {
- if (!text || !text.length)
- {
- freeAllLines(lines);
- return;
- }
- if (width <= 2.0)
- {
- freeAllLines(lines);
- return;
- }
- if (text.length <= 100 && text.indexOf("\n") === -1)
- {
- var all_width = ctx.measureText(text).width;
- if (all_width <= width)
- {
- freeAllLines(lines);
- lines.push(allocLine());
- lines[0].text = text;
- lines[0].width = all_width;
- return;
- }
- }
- this.WrapText(text, lines, ctx, width, wrapbyword);
- };
- pluginProto.WrapText = function (text, lines, ctx, width, wrapbyword)
- {
- var wordArray;
- if (wrapbyword)
- {
- this.TokeniseWords(text); // writes to wordsCache
- wordArray = wordsCache;
- }
- else
- wordArray = text;
- var cur_line = "";
- var prev_line;
- var line_width;
- var i;
- var lineIndex = 0;
- var line;
- for (i = 0; i < wordArray.length; i++)
- {
- if (wordArray[i] === "\n")
- {
- if (lineIndex >= lines.length)
- lines.push(allocLine());
- line = lines[lineIndex];
- line.text = cur_line;
- line.width = ctx.measureText(cur_line).width;
- lineIndex++;
- cur_line = "";
- continue;
- }
- prev_line = cur_line;
- cur_line += wordArray[i];
- line_width = ctx.measureText(cur_line).width;
- if (line_width >= width)
- {
- if (lineIndex >= lines.length)
- lines.push(allocLine());
- line = lines[lineIndex];
- line.text = prev_line;
- line.width = ctx.measureText(prev_line).width;
- lineIndex++;
- cur_line = wordArray[i];
- if (!wrapbyword && cur_line === " ")
- cur_line = "";
- }
- }
- if (cur_line.length)
- {
- if (lineIndex >= lines.length)
- lines.push(allocLine());
- line = lines[lineIndex];
- line.text = cur_line;
- line.width = ctx.measureText(cur_line).width;
- lineIndex++;
- }
- for (i = lineIndex; i < lines.length; i++)
- freeLine(lines[i]);
- lines.length = lineIndex;
- };
- function Cnds() {};
- Cnds.prototype.CompareText = function(text_to_compare, case_sensitive)
- {
- if (case_sensitive)
- return this.text == text_to_compare;
- else
- return cr.equals_nocase(this.text, text_to_compare);
- };
- pluginProto.cnds = new Cnds();
- function Acts() {};
- Acts.prototype.SetText = function(param)
- {
- if (cr.is_number(param) && param < 1e9)
- param = Math.round(param * 1e10) / 1e10; // round to nearest ten billionth - hides floating point errors
- var text_to_set = param.toString();
- if (this.text !== text_to_set)
- {
- this.text = text_to_set;
- this.text_changed = true;
- this.runtime.redraw = true;
- }
- };
- Acts.prototype.AppendText = function(param)
- {
- if (cr.is_number(param))
- param = Math.round(param * 1e10) / 1e10; // round to nearest ten billionth - hides floating point errors
- var text_to_append = param.toString();
- if (text_to_append) // not empty
- {
- this.text += text_to_append;
- this.text_changed = true;
- this.runtime.redraw = true;
- }
- };
- Acts.prototype.SetFontFace = function (face_, style_)
- {
- var newstyle = "";
- switch (style_) {
- case 1: newstyle = "bold"; break;
- case 2: newstyle = "italic"; break;
- case 3: newstyle = "bold italic"; break;
- }
- if (face_ === this.facename && newstyle === this.fontstyle)
- return; // no change
- this.facename = face_;
- this.fontstyle = newstyle;
- this.updateFont();
- };
- Acts.prototype.SetFontSize = function (size_)
- {
- if (this.ptSize === size_)
- return;
- this.ptSize = size_;
- this.pxHeight = Math.ceil((this.ptSize / 72.0) * 96.0) + 4; // assume 96dpi...
- this.updateFont();
- };
- Acts.prototype.SetFontColor = function (rgb)
- {
- var newcolor = "rgb(" + cr.GetRValue(rgb).toString() + "," + cr.GetGValue(rgb).toString() + "," + cr.GetBValue(rgb).toString() + ")";
- if (newcolor === this.color)
- return;
- this.color = newcolor;
- this.need_text_redraw = true;
- this.runtime.redraw = true;
- };
- Acts.prototype.SetWebFont = function (familyname_, cssurl_)
- {
- if (this.runtime.isDomFree)
- {
- cr.logexport("[Construct 2] Text plugin: 'Set web font' not supported on this platform - the action has been ignored");
- return; // DC todo
- }
- var self = this;
- var refreshFunc = (function () {
- self.runtime.redraw = true;
- self.text_changed = true;
- });
- if (requestedWebFonts.hasOwnProperty(cssurl_))
- {
- var newfacename = "'" + familyname_ + "'";
- if (this.facename === newfacename)
- return; // no change
- this.facename = newfacename;
- this.updateFont();
- for (var i = 1; i < 10; i++)
- {
- setTimeout(refreshFunc, i * 100);
- setTimeout(refreshFunc, i * 1000);
- }
- return;
- }
- var wf = document.createElement("link");
- wf.href = cssurl_;
- wf.rel = "stylesheet";
- wf.type = "text/css";
- wf.onload = refreshFunc;
- document.getElementsByTagName('head')[0].appendChild(wf);
- requestedWebFonts[cssurl_] = true;
- this.facename = "'" + familyname_ + "'";
- this.updateFont();
- for (var i = 1; i < 10; i++)
- {
- setTimeout(refreshFunc, i * 100);
- setTimeout(refreshFunc, i * 1000);
- }
- ;
- };
- Acts.prototype.SetEffect = function (effect)
- {
- this.blend_mode = effect;
- this.compositeOp = cr.effectToCompositeOp(effect);
- cr.setGLBlend(this, effect, this.runtime.gl);
- this.runtime.redraw = true;
- };
- pluginProto.acts = new Acts();
- function Exps() {};
- Exps.prototype.Text = function(ret)
- {
- ret.set_string(this.text);
- };
- Exps.prototype.FaceName = function (ret)
- {
- ret.set_string(this.facename);
- };
- Exps.prototype.FaceSize = function (ret)
- {
- ret.set_int(this.ptSize);
- };
- Exps.prototype.TextWidth = function (ret)
- {
- var w = 0;
- var i, len, x;
- for (i = 0, len = this.lines.length; i < len; i++)
- {
- x = this.lines[i].width;
- if (w < x)
- w = x;
- }
- ret.set_int(w);
- };
- Exps.prototype.TextHeight = function (ret)
- {
- ret.set_int(this.lines.length * (this.pxHeight + this.line_height_offset) - this.line_height_offset);
- };
- pluginProto.exps = new Exps();
- }());
- ;
- ;
- cr.plugins_.TiledBg = function(runtime)
- {
- this.runtime = runtime;
- };
- (function ()
- {
- var pluginProto = cr.plugins_.TiledBg.prototype;
- pluginProto.Type = function(plugin)
- {
- this.plugin = plugin;
- this.runtime = plugin.runtime;
- };
- var typeProto = pluginProto.Type.prototype;
- typeProto.onCreate = function()
- {
- if (this.is_family)
- return;
- this.texture_img = new Image();
- this.texture_img.cr_filesize = this.texture_filesize;
- this.runtime.waitForImageLoad(this.texture_img, this.texture_file);
- this.pattern = null;
- this.webGL_texture = null;
- };
- typeProto.onLostWebGLContext = function ()
- {
- if (this.is_family)
- return;
- this.webGL_texture = null;
- };
- typeProto.onRestoreWebGLContext = function ()
- {
- if (this.is_family || !this.instances.length)
- return;
- if (!this.webGL_texture)
- {
- this.webGL_texture = this.runtime.glwrap.loadTexture(this.texture_img, true, this.runtime.linearSampling, this.texture_pixelformat);
- }
- var i, len;
- for (i = 0, len = this.instances.length; i < len; i++)
- this.instances[i].webGL_texture = this.webGL_texture;
- };
- typeProto.loadTextures = function ()
- {
- if (this.is_family || this.webGL_texture || !this.runtime.glwrap)
- return;
- this.webGL_texture = this.runtime.glwrap.loadTexture(this.texture_img, true, this.runtime.linearSampling, this.texture_pixelformat);
- };
- typeProto.unloadTextures = function ()
- {
- if (this.is_family || this.instances.length || !this.webGL_texture)
- return;
- this.runtime.glwrap.deleteTexture(this.webGL_texture);
- this.webGL_texture = null;
- };
- typeProto.preloadCanvas2D = function (ctx)
- {
- ctx.drawImage(this.texture_img, 0, 0);
- };
- pluginProto.Instance = function(type)
- {
- this.type = type;
- this.runtime = type.runtime;
- };
- var instanceProto = pluginProto.Instance.prototype;
- instanceProto.onCreate = function()
- {
- this.visible = (this.properties[0] === 0); // 0=visible, 1=invisible
- this.rcTex = new cr.rect(0, 0, 0, 0);
- this.has_own_texture = false; // true if a texture loaded in from URL
- this.texture_img = this.type.texture_img;
- if (this.runtime.glwrap)
- {
- this.type.loadTextures();
- this.webGL_texture = this.type.webGL_texture;
- }
- else
- {
- if (!this.type.pattern)
- this.type.pattern = this.runtime.ctx.createPattern(this.type.texture_img, "repeat");
- this.pattern = this.type.pattern;
- }
- };
- instanceProto.afterLoad = function ()
- {
- this.has_own_texture = false;
- this.texture_img = this.type.texture_img;
- };
- instanceProto.onDestroy = function ()
- {
- if (this.runtime.glwrap && this.has_own_texture && this.webGL_texture)
- {
- this.runtime.glwrap.deleteTexture(this.webGL_texture);
- this.webGL_texture = null;
- }
- };
- instanceProto.draw = function(ctx)
- {
- ctx.globalAlpha = this.opacity;
- ctx.save();
- ctx.fillStyle = this.pattern;
- var myx = this.x;
- var myy = this.y;
- if (this.runtime.pixel_rounding)
- {
- myx = Math.round(myx);
- myy = Math.round(myy);
- }
- var drawX = -(this.hotspotX * this.width);
- var drawY = -(this.hotspotY * this.height);
- var offX = drawX % this.texture_img.width;
- var offY = drawY % this.texture_img.height;
- if (offX < 0)
- offX += this.texture_img.width;
- if (offY < 0)
- offY += this.texture_img.height;
- ctx.translate(myx, myy);
- ctx.rotate(this.angle);
- ctx.translate(offX, offY);
- ctx.fillRect(drawX - offX,
- drawY - offY,
- this.width,
- this.height);
- ctx.restore();
- };
- instanceProto.drawGL_earlyZPass = function(glw)
- {
- this.drawGL(glw);
- };
- instanceProto.drawGL = function(glw)
- {
- glw.setTexture(this.webGL_texture);
- glw.setOpacity(this.opacity);
- var rcTex = this.rcTex;
- rcTex.right = this.width / this.texture_img.width;
- rcTex.bottom = this.height / this.texture_img.height;
- var q = this.bquad;
- if (this.runtime.pixel_rounding)
- {
- var ox = Math.round(this.x) - this.x;
- var oy = Math.round(this.y) - this.y;
- glw.quadTex(q.tlx + ox, q.tly + oy, q.trx + ox, q.try_ + oy, q.brx + ox, q.bry + oy, q.blx + ox, q.bly + oy, rcTex);
- }
- else
- glw.quadTex(q.tlx, q.tly, q.trx, q.try_, q.brx, q.bry, q.blx, q.bly, rcTex);
- };
- function Cnds() {};
- Cnds.prototype.OnURLLoaded = function ()
- {
- return true;
- };
- pluginProto.cnds = new Cnds();
- function Acts() {};
- Acts.prototype.SetEffect = function (effect)
- {
- this.blend_mode = effect;
- this.compositeOp = cr.effectToCompositeOp(effect);
- cr.setGLBlend(this, effect, this.runtime.gl);
- this.runtime.redraw = true;
- };
- Acts.prototype.LoadURL = function (url_)
- {
- var img = new Image();
- var self = this;
- img.onload = function ()
- {
- self.texture_img = img;
- if (self.runtime.glwrap)
- {
- if (self.has_own_texture && self.webGL_texture)
- self.runtime.glwrap.deleteTexture(self.webGL_texture);
- self.webGL_texture = self.runtime.glwrap.loadTexture(img, true, self.runtime.linearSampling);
- }
- else
- {
- self.pattern = self.runtime.ctx.createPattern(img, "repeat");
- }
- self.has_own_texture = true;
- self.runtime.redraw = true;
- self.runtime.trigger(cr.plugins_.TiledBg.prototype.cnds.OnURLLoaded, self);
- };
- if (url_.substr(0, 5) !== "data:")
- img.crossOrigin = "anonymous";
- img.src = url_;
- };
- pluginProto.acts = new Acts();
- function Exps() {};
- Exps.prototype.ImageWidth = function (ret)
- {
- ret.set_float(this.texture_img.width);
- };
- Exps.prototype.ImageHeight = function (ret)
- {
- ret.set_float(this.texture_img.height);
- };
- pluginProto.exps = new Exps();
- }());
- ;
- ;
- cr.plugins_.Touch = function(runtime)
- {
- this.runtime = runtime;
- };
- (function ()
- {
- var pluginProto = cr.plugins_.Touch.prototype;
- pluginProto.Type = function(plugin)
- {
- this.plugin = plugin;
- this.runtime = plugin.runtime;
- };
- var typeProto = pluginProto.Type.prototype;
- typeProto.onCreate = function()
- {
- };
- pluginProto.Instance = function(type)
- {
- this.type = type;
- this.runtime = type.runtime;
- this.touches = [];
- this.mouseDown = false;
- };
- var instanceProto = pluginProto.Instance.prototype;
- var dummyoffset = {left: 0, top: 0};
- instanceProto.findTouch = function (id)
- {
- var i, len;
- for (i = 0, len = this.touches.length; i < len; i++)
- {
- if (this.touches[i]["id"] === id)
- return i;
- }
- return -1;
- };
- var appmobi_accx = 0;
- var appmobi_accy = 0;
- var appmobi_accz = 0;
- function AppMobiGetAcceleration(evt)
- {
- appmobi_accx = evt.x;
- appmobi_accy = evt.y;
- appmobi_accz = evt.z;
- };
- var pg_accx = 0;
- var pg_accy = 0;
- var pg_accz = 0;
- function PhoneGapGetAcceleration(evt)
- {
- pg_accx = evt.x;
- pg_accy = evt.y;
- pg_accz = evt.z;
- };
- var theInstance = null;
- var touchinfo_cache = [];
- function AllocTouchInfo(x, y, id, index)
- {
- var ret;
- if (touchinfo_cache.length)
- ret = touchinfo_cache.pop();
- else
- ret = new TouchInfo();
- ret.init(x, y, id, index);
- return ret;
- };
- function ReleaseTouchInfo(ti)
- {
- if (touchinfo_cache.length < 100)
- touchinfo_cache.push(ti);
- };
- var GESTURE_HOLD_THRESHOLD = 15; // max px motion for hold gesture to register
- var GESTURE_HOLD_TIMEOUT = 500; // time for hold gesture to register
- var GESTURE_TAP_TIMEOUT = 333; // time for tap gesture to register
- var GESTURE_DOUBLETAP_THRESHOLD = 25; // max distance apart for taps to be
- function TouchInfo()
- {
- this.starttime = 0;
- this.time = 0;
- this.lasttime = 0;
- this.startx = 0;
- this.starty = 0;
- this.x = 0;
- this.y = 0;
- this.lastx = 0;
- this.lasty = 0;
- this["id"] = 0;
- this.startindex = 0;
- this.triggeredHold = false;
- this.tooFarForHold = false;
- };
- TouchInfo.prototype.init = function (x, y, id, index)
- {
- var nowtime = cr.performance_now();
- this.time = nowtime;
- this.lasttime = nowtime;
- this.starttime = nowtime;
- this.startx = x;
- this.starty = y;
- this.x = x;
- this.y = y;
- this.lastx = x;
- this.lasty = y;
- this["id"] = id;
- this.startindex = index;
- this.triggeredHold = false;
- this.tooFarForHold = false;
- };
- TouchInfo.prototype.update = function (nowtime, x, y)
- {
- this.lasttime = this.time;
- this.time = nowtime;
- this.lastx = this.x;
- this.lasty = this.y;
- this.x = x;
- this.y = y;
- if (!this.tooFarForHold && cr.distanceTo(this.startx, this.starty, this.x, this.y) >= GESTURE_HOLD_THRESHOLD)
- {
- this.tooFarForHold = true;
- }
- };
- TouchInfo.prototype.maybeTriggerHold = function (inst, index)
- {
- if (this.triggeredHold)
- return; // already triggered this gesture
- var nowtime = cr.performance_now();
- if (nowtime - this.starttime >= GESTURE_HOLD_TIMEOUT && !this.tooFarForHold && cr.distanceTo(this.startx, this.starty, this.x, this.y) < GESTURE_HOLD_THRESHOLD)
- {
- this.triggeredHold = true;
- inst.trigger_index = this.startindex;
- inst.trigger_id = this["id"];
- inst.getTouchIndex = index;
- inst.runtime.trigger(cr.plugins_.Touch.prototype.cnds.OnHoldGesture, inst);
- inst.curTouchX = this.x;
- inst.curTouchY = this.y;
- inst.runtime.trigger(cr.plugins_.Touch.prototype.cnds.OnHoldGestureObject, inst);
- inst.getTouchIndex = 0;
- }
- };
- var lastTapX = -1000;
- var lastTapY = -1000;
- var lastTapTime = -10000;
- TouchInfo.prototype.maybeTriggerTap = function (inst, index)
- {
- if (this.triggeredHold)
- return;
- var nowtime = cr.performance_now();
- if (nowtime - this.starttime <= GESTURE_TAP_TIMEOUT && !this.tooFarForHold && cr.distanceTo(this.startx, this.starty, this.x, this.y) < GESTURE_HOLD_THRESHOLD)
- {
- inst.trigger_index = this.startindex;
- inst.trigger_id = this["id"];
- inst.getTouchIndex = index;
- if ((nowtime - lastTapTime <= GESTURE_TAP_TIMEOUT * 2) && cr.distanceTo(lastTapX, lastTapY, this.x, this.y) < GESTURE_DOUBLETAP_THRESHOLD)
- {
- inst.runtime.trigger(cr.plugins_.Touch.prototype.cnds.OnDoubleTapGesture, inst);
- inst.curTouchX = this.x;
- inst.curTouchY = this.y;
- inst.runtime.trigger(cr.plugins_.Touch.prototype.cnds.OnDoubleTapGestureObject, inst);
- lastTapX = -1000;
- lastTapY = -1000;
- lastTapTime = -10000;
- }
- else
- {
- inst.runtime.trigger(cr.plugins_.Touch.prototype.cnds.OnTapGesture, inst);
- inst.curTouchX = this.x;
- inst.curTouchY = this.y;
- inst.runtime.trigger(cr.plugins_.Touch.prototype.cnds.OnTapGestureObject, inst);
- lastTapX = this.x;
- lastTapY = this.y;
- lastTapTime = nowtime;
- }
- inst.getTouchIndex = 0;
- }
- };
- instanceProto.onCreate = function()
- {
- theInstance = this;
- this.isWindows8 = !!(typeof window["c2isWindows8"] !== "undefined" && window["c2isWindows8"]);
- this.orient_alpha = 0;
- this.orient_beta = 0;
- this.orient_gamma = 0;
- this.acc_g_x = 0;
- this.acc_g_y = 0;
- this.acc_g_z = 0;
- this.acc_x = 0;
- this.acc_y = 0;
- this.acc_z = 0;
- this.curTouchX = 0;
- this.curTouchY = 0;
- this.trigger_index = 0;
- this.trigger_id = 0;
- this.getTouchIndex = 0;
- this.useMouseInput = (this.properties[0] !== 0);
- var elem = (this.runtime.fullscreen_mode > 0) ? document : this.runtime.canvas;
- var elem2 = document;
- if (this.runtime.isDirectCanvas)
- elem2 = elem = window["Canvas"];
- else if (this.runtime.isCocoonJs)
- elem2 = elem = window;
- var self = this;
- if (window.navigator["pointerEnabled"])
- {
- elem.addEventListener("pointerdown",
- function(info) {
- self.onPointerStart(info);
- },
- false
- );
- elem.addEventListener("pointermove",
- function(info) {
- self.onPointerMove(info);
- },
- false
- );
- elem2.addEventListener("pointerup",
- function(info) {
- self.onPointerEnd(info, false);
- },
- false
- );
- elem2.addEventListener("pointercancel",
- function(info) {
- self.onPointerEnd(info, true);
- },
- false
- );
- if (this.runtime.canvas)
- {
- this.runtime.canvas.addEventListener("MSGestureHold", function(e) {
- e.preventDefault();
- }, false);
- document.addEventListener("MSGestureHold", function(e) {
- e.preventDefault();
- }, false);
- this.runtime.canvas.addEventListener("gesturehold", function(e) {
- e.preventDefault();
- }, false);
- document.addEventListener("gesturehold", function(e) {
- e.preventDefault();
- }, false);
- }
- }
- else if (window.navigator["msPointerEnabled"])
- {
- elem.addEventListener("MSPointerDown",
- function(info) {
- self.onPointerStart(info);
- },
- false
- );
- elem.addEventListener("MSPointerMove",
- function(info) {
- self.onPointerMove(info);
- },
- false
- );
- elem2.addEventListener("MSPointerUp",
- function(info) {
- self.onPointerEnd(info, false);
- },
- false
- );
- elem2.addEventListener("MSPointerCancel",
- function(info) {
- self.onPointerEnd(info, true);
- },
- false
- );
- if (this.runtime.canvas)
- {
- this.runtime.canvas.addEventListener("MSGestureHold", function(e) {
- e.preventDefault();
- }, false);
- document.addEventListener("MSGestureHold", function(e) {
- e.preventDefault();
- }, false);
- }
- }
- else
- {
- elem.addEventListener("touchstart",
- function(info) {
- self.onTouchStart(info);
- },
- false
- );
- elem.addEventListener("touchmove",
- function(info) {
- self.onTouchMove(info);
- },
- false
- );
- elem2.addEventListener("touchend",
- function(info) {
- self.onTouchEnd(info, false);
- },
- false
- );
- elem2.addEventListener("touchcancel",
- function(info) {
- self.onTouchEnd(info, true);
- },
- false
- );
- }
- if (this.isWindows8)
- {
- var win8accelerometerFn = function(e) {
- var reading = e["reading"];
- self.acc_x = reading["accelerationX"];
- self.acc_y = reading["accelerationY"];
- self.acc_z = reading["accelerationZ"];
- };
- var win8inclinometerFn = function(e) {
- var reading = e["reading"];
- self.orient_alpha = reading["yawDegrees"];
- self.orient_beta = reading["pitchDegrees"];
- self.orient_gamma = reading["rollDegrees"];
- };
- var accelerometer = Windows["Devices"]["Sensors"]["Accelerometer"]["getDefault"]();
- if (accelerometer)
- {
- accelerometer["reportInterval"] = Math.max(accelerometer["minimumReportInterval"], 16);
- accelerometer.addEventListener("readingchanged", win8accelerometerFn);
- }
- var inclinometer = Windows["Devices"]["Sensors"]["Inclinometer"]["getDefault"]();
- if (inclinometer)
- {
- inclinometer["reportInterval"] = Math.max(inclinometer["minimumReportInterval"], 16);
- inclinometer.addEventListener("readingchanged", win8inclinometerFn);
- }
- document.addEventListener("visibilitychange", function(e) {
- if (document["hidden"] || document["msHidden"])
- {
- if (accelerometer)
- accelerometer.removeEventListener("readingchanged", win8accelerometerFn);
- if (inclinometer)
- inclinometer.removeEventListener("readingchanged", win8inclinometerFn);
- }
- else
- {
- if (accelerometer)
- accelerometer.addEventListener("readingchanged", win8accelerometerFn);
- if (inclinometer)
- inclinometer.addEventListener("readingchanged", win8inclinometerFn);
- }
- }, false);
- }
- else
- {
- window.addEventListener("deviceorientation", function (eventData) {
- self.orient_alpha = eventData["alpha"] || 0;
- self.orient_beta = eventData["beta"] || 0;
- self.orient_gamma = eventData["gamma"] || 0;
- }, false);
- window.addEventListener("devicemotion", function (eventData) {
- if (eventData["accelerationIncludingGravity"])
- {
- self.acc_g_x = eventData["accelerationIncludingGravity"]["x"] || 0;
- self.acc_g_y = eventData["accelerationIncludingGravity"]["y"] || 0;
- self.acc_g_z = eventData["accelerationIncludingGravity"]["z"] || 0;
- }
- if (eventData["acceleration"])
- {
- self.acc_x = eventData["acceleration"]["x"] || 0;
- self.acc_y = eventData["acceleration"]["y"] || 0;
- self.acc_z = eventData["acceleration"]["z"] || 0;
- }
- }, false);
- }
- if (this.useMouseInput && !this.runtime.isDomFree)
- {
- jQuery(document).mousemove(
- function(info) {
- self.onMouseMove(info);
- }
- );
- jQuery(document).mousedown(
- function(info) {
- self.onMouseDown(info);
- }
- );
- jQuery(document).mouseup(
- function(info) {
- self.onMouseUp(info);
- }
- );
- }
- if (this.runtime.isAppMobi && !this.runtime.isDirectCanvas)
- {
- AppMobi["accelerometer"]["watchAcceleration"](AppMobiGetAcceleration, { "frequency": 40, "adjustForRotation": true });
- }
- if (this.runtime.isCordova && navigator["accelerometer"] && navigator["accelerometer"]["watchAcceleration"])
- {
- navigator["accelerometer"]["watchAcceleration"](PhoneGapGetAcceleration, null, { "frequency": 40 });
- }
- this.runtime.tick2Me(this);
- };
- instanceProto.onPointerMove = function (info)
- {
- if (info["pointerType"] === info["MSPOINTER_TYPE_MOUSE"] || info["pointerType"] === "mouse")
- return;
- if (info.preventDefault)
- info.preventDefault();
- var i = this.findTouch(info["pointerId"]);
- var nowtime = cr.performance_now();
- if (i >= 0)
- {
- var offset = this.runtime.isDomFree ? dummyoffset : jQuery(this.runtime.canvas).offset();
- var t = this.touches[i];
- if (nowtime - t.time < 2)
- return;
- t.update(nowtime, info.pageX - offset.left, info.pageY - offset.top);
- }
- };
- instanceProto.onPointerStart = function (info)
- {
- if (info["pointerType"] === info["MSPOINTER_TYPE_MOUSE"] || info["pointerType"] === "mouse")
- return;
- if (info.preventDefault && cr.isCanvasInputEvent(info))
- info.preventDefault();
- var offset = this.runtime.isDomFree ? dummyoffset : jQuery(this.runtime.canvas).offset();
- var touchx = info.pageX - offset.left;
- var touchy = info.pageY - offset.top;
- var nowtime = cr.performance_now();
- this.trigger_index = this.touches.length;
- this.trigger_id = info["pointerId"];
- this.touches.push(AllocTouchInfo(touchx, touchy, info["pointerId"], this.trigger_index));
- this.runtime.isInUserInputEvent = true;
- this.runtime.trigger(cr.plugins_.Touch.prototype.cnds.OnNthTouchStart, this);
- this.runtime.trigger(cr.plugins_.Touch.prototype.cnds.OnTouchStart, this);
- this.curTouchX = touchx;
- this.curTouchY = touchy;
- this.runtime.trigger(cr.plugins_.Touch.prototype.cnds.OnTouchObject, this);
- this.runtime.isInUserInputEvent = false;
- };
- instanceProto.onPointerEnd = function (info, isCancel)
- {
- if (info["pointerType"] === info["MSPOINTER_TYPE_MOUSE"] || info["pointerType"] === "mouse")
- return;
- if (info.preventDefault && cr.isCanvasInputEvent(info))
- info.preventDefault();
- var i = this.findTouch(info["pointerId"]);
- this.trigger_index = (i >= 0 ? this.touches[i].startindex : -1);
- this.trigger_id = (i >= 0 ? this.touches[i]["id"] : -1);
- this.runtime.isInUserInputEvent = true;
- this.runtime.trigger(cr.plugins_.Touch.prototype.cnds.OnNthTouchEnd, this);
- this.runtime.trigger(cr.plugins_.Touch.prototype.cnds.OnTouchEnd, this);
- if (i >= 0)
- {
- if (!isCancel)
- this.touches[i].maybeTriggerTap(this, i);
- ReleaseTouchInfo(this.touches[i]);
- this.touches.splice(i, 1);
- }
- this.runtime.isInUserInputEvent = false;
- };
- instanceProto.onTouchMove = function (info)
- {
- if (info.preventDefault)
- info.preventDefault();
- var nowtime = cr.performance_now();
- var i, len, t, u;
- for (i = 0, len = info.changedTouches.length; i < len; i++)
- {
- t = info.changedTouches[i];
- var j = this.findTouch(t["identifier"]);
- if (j >= 0)
- {
- var offset = this.runtime.isDomFree ? dummyoffset : jQuery(this.runtime.canvas).offset();
- u = this.touches[j];
- if (nowtime - u.time < 2)
- continue;
- u.update(nowtime, t.pageX - offset.left, t.pageY - offset.top);
- }
- }
- };
- instanceProto.onTouchStart = function (info)
- {
- if (info.preventDefault && cr.isCanvasInputEvent(info))
- info.preventDefault();
- var offset = this.runtime.isDomFree ? dummyoffset : jQuery(this.runtime.canvas).offset();
- var nowtime = cr.performance_now();
- this.runtime.isInUserInputEvent = true;
- var i, len, t, j;
- for (i = 0, len = info.changedTouches.length; i < len; i++)
- {
- t = info.changedTouches[i];
- j = this.findTouch(t["identifier"]);
- if (j !== -1)
- continue;
- var touchx = t.pageX - offset.left;
- var touchy = t.pageY - offset.top;
- this.trigger_index = this.touches.length;
- this.trigger_id = t["identifier"];
- this.touches.push(AllocTouchInfo(touchx, touchy, t["identifier"], this.trigger_index));
- this.runtime.trigger(cr.plugins_.Touch.prototype.cnds.OnNthTouchStart, this);
- this.runtime.trigger(cr.plugins_.Touch.prototype.cnds.OnTouchStart, this);
- this.curTouchX = touchx;
- this.curTouchY = touchy;
- this.runtime.trigger(cr.plugins_.Touch.prototype.cnds.OnTouchObject, this);
- }
- this.runtime.isInUserInputEvent = false;
- };
- instanceProto.onTouchEnd = function (info, isCancel)
- {
- if (info.preventDefault && cr.isCanvasInputEvent(info))
- info.preventDefault();
- this.runtime.isInUserInputEvent = true;
- var i, len, t, j;
- for (i = 0, len = info.changedTouches.length; i < len; i++)
- {
- t = info.changedTouches[i];
- j = this.findTouch(t["identifier"]);
- if (j >= 0)
- {
- this.trigger_index = this.touches[j].startindex;
- this.trigger_id = this.touches[j]["id"];
- this.runtime.trigger(cr.plugins_.Touch.prototype.cnds.OnNthTouchEnd, this);
- this.runtime.trigger(cr.plugins_.Touch.prototype.cnds.OnTouchEnd, this);
- if (!isCancel)
- this.touches[j].maybeTriggerTap(this, j);
- ReleaseTouchInfo(this.touches[j]);
- this.touches.splice(j, 1);
- }
- }
- this.runtime.isInUserInputEvent = false;
- };
- instanceProto.getAlpha = function ()
- {
- if (this.runtime.isAppMobi && this.orient_alpha === 0 && appmobi_accz !== 0)
- return appmobi_accz * 90;
- else if (this.runtime.isCordova && this.orient_alpha === 0 && pg_accz !== 0)
- return pg_accz * 90;
- else
- return this.orient_alpha;
- };
- instanceProto.getBeta = function ()
- {
- if (this.runtime.isAppMobi && this.orient_beta === 0 && appmobi_accy !== 0)
- return appmobi_accy * -90;
- else if (this.runtime.isCordova && this.orient_beta === 0 && pg_accy !== 0)
- return pg_accy * 90;
- else
- return this.orient_beta;
- };
- instanceProto.getGamma = function ()
- {
- if (this.runtime.isAppMobi && this.orient_gamma === 0 && appmobi_accx !== 0)
- return appmobi_accx * 90;
- else if (this.runtime.isCordova && this.orient_gamma === 0 && pg_accx !== 0)
- return pg_accx * 90;
- else
- return this.orient_gamma;
- };
- var noop_func = function(){};
- instanceProto.onMouseDown = function(info)
- {
- var t = { pageX: info.pageX, pageY: info.pageY, "identifier": 0 };
- var fakeinfo = { changedTouches: [t] };
- this.onTouchStart(fakeinfo);
- this.mouseDown = true;
- };
- instanceProto.onMouseMove = function(info)
- {
- if (!this.mouseDown)
- return;
- var t = { pageX: info.pageX, pageY: info.pageY, "identifier": 0 };
- var fakeinfo = { changedTouches: [t] };
- this.onTouchMove(fakeinfo);
- };
- instanceProto.onMouseUp = function(info)
- {
- if (info.preventDefault && this.runtime.had_a_click && !this.runtime.isMobile)
- info.preventDefault();
- this.runtime.had_a_click = true;
- var t = { pageX: info.pageX, pageY: info.pageY, "identifier": 0 };
- var fakeinfo = { changedTouches: [t] };
- this.onTouchEnd(fakeinfo);
- this.mouseDown = false;
- };
- instanceProto.tick2 = function()
- {
- var i, len, t;
- var nowtime = cr.performance_now();
- for (i = 0, len = this.touches.length; i < len; ++i)
- {
- t = this.touches[i];
- if (t.time <= nowtime - 50)
- t.lasttime = nowtime;
- t.maybeTriggerHold(this, i);
- }
- };
- function Cnds() {};
- Cnds.prototype.OnTouchStart = function ()
- {
- return true;
- };
- Cnds.prototype.OnTouchEnd = function ()
- {
- return true;
- };
- Cnds.prototype.IsInTouch = function ()
- {
- return this.touches.length;
- };
- Cnds.prototype.OnTouchObject = function (type)
- {
- if (!type)
- return false;
- return this.runtime.testAndSelectCanvasPointOverlap(type, this.curTouchX, this.curTouchY, false);
- };
- var touching = [];
- Cnds.prototype.IsTouchingObject = function (type)
- {
- if (!type)
- return false;
- var sol = type.getCurrentSol();
- var instances = sol.getObjects();
- var px, py;
- var i, leni, j, lenj;
- for (i = 0, leni = instances.length; i < leni; i++)
- {
- var inst = instances[i];
- inst.update_bbox();
- for (j = 0, lenj = this.touches.length; j < lenj; j++)
- {
- var touch = this.touches[j];
- px = inst.layer.canvasToLayer(touch.x, touch.y, true);
- py = inst.layer.canvasToLayer(touch.x, touch.y, false);
- if (inst.contains_pt(px, py))
- {
- touching.push(inst);
- break;
- }
- }
- }
- if (touching.length)
- {
- sol.select_all = false;
- cr.shallowAssignArray(sol.instances, touching);
- type.applySolToContainer();
- cr.clearArray(touching);
- return true;
- }
- else
- return false;
- };
- Cnds.prototype.CompareTouchSpeed = function (index, cmp, s)
- {
- index = Math.floor(index);
- if (index < 0 || index >= this.touches.length)
- return false;
- var t = this.touches[index];
- var dist = cr.distanceTo(t.x, t.y, t.lastx, t.lasty);
- var timediff = (t.time - t.lasttime) / 1000;
- var speed = 0;
- if (timediff > 0)
- speed = dist / timediff;
- return cr.do_cmp(speed, cmp, s);
- };
- Cnds.prototype.OrientationSupported = function ()
- {
- return typeof window["DeviceOrientationEvent"] !== "undefined";
- };
- Cnds.prototype.MotionSupported = function ()
- {
- return typeof window["DeviceMotionEvent"] !== "undefined";
- };
- Cnds.prototype.CompareOrientation = function (orientation_, cmp_, angle_)
- {
- var v = 0;
- if (orientation_ === 0)
- v = this.getAlpha();
- else if (orientation_ === 1)
- v = this.getBeta();
- else
- v = this.getGamma();
- return cr.do_cmp(v, cmp_, angle_);
- };
- Cnds.prototype.CompareAcceleration = function (acceleration_, cmp_, angle_)
- {
- var v = 0;
- if (acceleration_ === 0)
- v = this.acc_g_x;
- else if (acceleration_ === 1)
- v = this.acc_g_y;
- else if (acceleration_ === 2)
- v = this.acc_g_z;
- else if (acceleration_ === 3)
- v = this.acc_x;
- else if (acceleration_ === 4)
- v = this.acc_y;
- else if (acceleration_ === 5)
- v = this.acc_z;
- return cr.do_cmp(v, cmp_, angle_);
- };
- Cnds.prototype.OnNthTouchStart = function (touch_)
- {
- touch_ = Math.floor(touch_);
- return touch_ === this.trigger_index;
- };
- Cnds.prototype.OnNthTouchEnd = function (touch_)
- {
- touch_ = Math.floor(touch_);
- return touch_ === this.trigger_index;
- };
- Cnds.prototype.HasNthTouch = function (touch_)
- {
- touch_ = Math.floor(touch_);
- return this.touches.length >= touch_ + 1;
- };
- Cnds.prototype.OnHoldGesture = function ()
- {
- return true;
- };
- Cnds.prototype.OnTapGesture = function ()
- {
- return true;
- };
- Cnds.prototype.OnDoubleTapGesture = function ()
- {
- return true;
- };
- Cnds.prototype.OnHoldGestureObject = function (type)
- {
- if (!type)
- return false;
- return this.runtime.testAndSelectCanvasPointOverlap(type, this.curTouchX, this.curTouchY, false);
- };
- Cnds.prototype.OnTapGestureObject = function (type)
- {
- if (!type)
- return false;
- return this.runtime.testAndSelectCanvasPointOverlap(type, this.curTouchX, this.curTouchY, false);
- };
- Cnds.prototype.OnDoubleTapGestureObject = function (type)
- {
- if (!type)
- return false;
- return this.runtime.testAndSelectCanvasPointOverlap(type, this.curTouchX, this.curTouchY, false);
- };
- pluginProto.cnds = new Cnds();
- function Exps() {};
- Exps.prototype.TouchCount = function (ret)
- {
- ret.set_int(this.touches.length);
- };
- Exps.prototype.X = function (ret, layerparam)
- {
- var index = this.getTouchIndex;
- if (index < 0 || index >= this.touches.length)
- {
- ret.set_float(0);
- return;
- }
- var layer, oldScale, oldZoomRate, oldParallaxX, oldAngle;
- if (cr.is_undefined(layerparam))
- {
- layer = this.runtime.getLayerByNumber(0);
- oldScale = layer.scale;
- oldZoomRate = layer.zoomRate;
- oldParallaxX = layer.parallaxX;
- oldAngle = layer.angle;
- layer.scale = 1;
- layer.zoomRate = 1.0;
- layer.parallaxX = 1.0;
- layer.angle = 0;
- ret.set_float(layer.canvasToLayer(this.touches[index].x, this.touches[index].y, true));
- layer.scale = oldScale;
- layer.zoomRate = oldZoomRate;
- layer.parallaxX = oldParallaxX;
- layer.angle = oldAngle;
- }
- else
- {
- if (cr.is_number(layerparam))
- layer = this.runtime.getLayerByNumber(layerparam);
- else
- layer = this.runtime.getLayerByName(layerparam);
- if (layer)
- ret.set_float(layer.canvasToLayer(this.touches[index].x, this.touches[index].y, true));
- else
- ret.set_float(0);
- }
- };
- Exps.prototype.XAt = function (ret, index, layerparam)
- {
- index = Math.floor(index);
- if (index < 0 || index >= this.touches.length)
- {
- ret.set_float(0);
- return;
- }
- var layer, oldScale, oldZoomRate, oldParallaxX, oldAngle;
- if (cr.is_undefined(layerparam))
- {
- layer = this.runtime.getLayerByNumber(0);
- oldScale = layer.scale;
- oldZoomRate = layer.zoomRate;
- oldParallaxX = layer.parallaxX;
- oldAngle = layer.angle;
- layer.scale = 1;
- layer.zoomRate = 1.0;
- layer.parallaxX = 1.0;
- layer.angle = 0;
- ret.set_float(layer.canvasToLayer(this.touches[index].x, this.touches[index].y, true));
- layer.scale = oldScale;
- layer.zoomRate = oldZoomRate;
- layer.parallaxX = oldParallaxX;
- layer.angle = oldAngle;
- }
- else
- {
- if (cr.is_number(layerparam))
- layer = this.runtime.getLayerByNumber(layerparam);
- else
- layer = this.runtime.getLayerByName(layerparam);
- if (layer)
- ret.set_float(layer.canvasToLayer(this.touches[index].x, this.touches[index].y, true));
- else
- ret.set_float(0);
- }
- };
- Exps.prototype.XForID = function (ret, id, layerparam)
- {
- var index = this.findTouch(id);
- if (index < 0)
- {
- ret.set_float(0);
- return;
- }
- var touch = this.touches[index];
- var layer, oldScale, oldZoomRate, oldParallaxX, oldAngle;
- if (cr.is_undefined(layerparam))
- {
- layer = this.runtime.getLayerByNumber(0);
- oldScale = layer.scale;
- oldZoomRate = layer.zoomRate;
- oldParallaxX = layer.parallaxX;
- oldAngle = layer.angle;
- layer.scale = 1;
- layer.zoomRate = 1.0;
- layer.parallaxX = 1.0;
- layer.angle = 0;
- ret.set_float(layer.canvasToLayer(touch.x, touch.y, true));
- layer.scale = oldScale;
- layer.zoomRate = oldZoomRate;
- layer.parallaxX = oldParallaxX;
- layer.angle = oldAngle;
- }
- else
- {
- if (cr.is_number(layerparam))
- layer = this.runtime.getLayerByNumber(layerparam);
- else
- layer = this.runtime.getLayerByName(layerparam);
- if (layer)
- ret.set_float(layer.canvasToLayer(touch.x, touch.y, true));
- else
- ret.set_float(0);
- }
- };
- Exps.prototype.Y = function (ret, layerparam)
- {
- var index = this.getTouchIndex;
- if (index < 0 || index >= this.touches.length)
- {
- ret.set_float(0);
- return;
- }
- var layer, oldScale, oldZoomRate, oldParallaxY, oldAngle;
- if (cr.is_undefined(layerparam))
- {
- layer = this.runtime.getLayerByNumber(0);
- oldScale = layer.scale;
- oldZoomRate = layer.zoomRate;
- oldParallaxY = layer.parallaxY;
- oldAngle = layer.angle;
- layer.scale = 1;
- layer.zoomRate = 1.0;
- layer.parallaxY = 1.0;
- layer.angle = 0;
- ret.set_float(layer.canvasToLayer(this.touches[index].x, this.touches[index].y, false));
- layer.scale = oldScale;
- layer.zoomRate = oldZoomRate;
- layer.parallaxY = oldParallaxY;
- layer.angle = oldAngle;
- }
- else
- {
- if (cr.is_number(layerparam))
- layer = this.runtime.getLayerByNumber(layerparam);
- else
- layer = this.runtime.getLayerByName(layerparam);
- if (layer)
- ret.set_float(layer.canvasToLayer(this.touches[index].x, this.touches[index].y, false));
- else
- ret.set_float(0);
- }
- };
- Exps.prototype.YAt = function (ret, index, layerparam)
- {
- index = Math.floor(index);
- if (index < 0 || index >= this.touches.length)
- {
- ret.set_float(0);
- return;
- }
- var layer, oldScale, oldZoomRate, oldParallaxY, oldAngle;
- if (cr.is_undefined(layerparam))
- {
- layer = this.runtime.getLayerByNumber(0);
- oldScale = layer.scale;
- oldZoomRate = layer.zoomRate;
- oldParallaxY = layer.parallaxY;
- oldAngle = layer.angle;
- layer.scale = 1;
- layer.zoomRate = 1.0;
- layer.parallaxY = 1.0;
- layer.angle = 0;
- ret.set_float(layer.canvasToLayer(this.touches[index].x, this.touches[index].y, false));
- layer.scale = oldScale;
- layer.zoomRate = oldZoomRate;
- layer.parallaxY = oldParallaxY;
- layer.angle = oldAngle;
- }
- else
- {
- if (cr.is_number(layerparam))
- layer = this.runtime.getLayerByNumber(layerparam);
- else
- layer = this.runtime.getLayerByName(layerparam);
- if (layer)
- ret.set_float(layer.canvasToLayer(this.touches[index].x, this.touches[index].y, false));
- else
- ret.set_float(0);
- }
- };
- Exps.prototype.YForID = function (ret, id, layerparam)
- {
- var index = this.findTouch(id);
- if (index < 0)
- {
- ret.set_float(0);
- return;
- }
- var touch = this.touches[index];
- var layer, oldScale, oldZoomRate, oldParallaxY, oldAngle;
- if (cr.is_undefined(layerparam))
- {
- layer = this.runtime.getLayerByNumber(0);
- oldScale = layer.scale;
- oldZoomRate = layer.zoomRate;
- oldParallaxY = layer.parallaxY;
- oldAngle = layer.angle;
- layer.scale = 1;
- layer.zoomRate = 1.0;
- layer.parallaxY = 1.0;
- layer.angle = 0;
- ret.set_float(layer.canvasToLayer(touch.x, touch.y, false));
- layer.scale = oldScale;
- layer.zoomRate = oldZoomRate;
- layer.parallaxY = oldParallaxY;
- layer.angle = oldAngle;
- }
- else
- {
- if (cr.is_number(layerparam))
- layer = this.runtime.getLayerByNumber(layerparam);
- else
- layer = this.runtime.getLayerByName(layerparam);
- if (layer)
- ret.set_float(layer.canvasToLayer(touch.x, touch.y, false));
- else
- ret.set_float(0);
- }
- };
- Exps.prototype.AbsoluteX = function (ret)
- {
- if (this.touches.length)
- ret.set_float(this.touches[0].x);
- else
- ret.set_float(0);
- };
- Exps.prototype.AbsoluteXAt = function (ret, index)
- {
- index = Math.floor(index);
- if (index < 0 || index >= this.touches.length)
- {
- ret.set_float(0);
- return;
- }
- ret.set_float(this.touches[index].x);
- };
- Exps.prototype.AbsoluteXForID = function (ret, id)
- {
- var index = this.findTouch(id);
- if (index < 0)
- {
- ret.set_float(0);
- return;
- }
- var touch = this.touches[index];
- ret.set_float(touch.x);
- };
- Exps.prototype.AbsoluteY = function (ret)
- {
- if (this.touches.length)
- ret.set_float(this.touches[0].y);
- else
- ret.set_float(0);
- };
- Exps.prototype.AbsoluteYAt = function (ret, index)
- {
- index = Math.floor(index);
- if (index < 0 || index >= this.touches.length)
- {
- ret.set_float(0);
- return;
- }
- ret.set_float(this.touches[index].y);
- };
- Exps.prototype.AbsoluteYForID = function (ret, id)
- {
- var index = this.findTouch(id);
- if (index < 0)
- {
- ret.set_float(0);
- return;
- }
- var touch = this.touches[index];
- ret.set_float(touch.y);
- };
- Exps.prototype.SpeedAt = function (ret, index)
- {
- index = Math.floor(index);
- if (index < 0 || index >= this.touches.length)
- {
- ret.set_float(0);
- return;
- }
- var t = this.touches[index];
- var dist = cr.distanceTo(t.x, t.y, t.lastx, t.lasty);
- var timediff = (t.time - t.lasttime) / 1000;
- if (timediff === 0)
- ret.set_float(0);
- else
- ret.set_float(dist / timediff);
- };
- Exps.prototype.SpeedForID = function (ret, id)
- {
- var index = this.findTouch(id);
- if (index < 0)
- {
- ret.set_float(0);
- return;
- }
- var touch = this.touches[index];
- var dist = cr.distanceTo(touch.x, touch.y, touch.lastx, touch.lasty);
- var timediff = (touch.time - touch.lasttime) / 1000;
- if (timediff === 0)
- ret.set_float(0);
- else
- ret.set_float(dist / timediff);
- };
- Exps.prototype.AngleAt = function (ret, index)
- {
- index = Math.floor(index);
- if (index < 0 || index >= this.touches.length)
- {
- ret.set_float(0);
- return;
- }
- var t = this.touches[index];
- ret.set_float(cr.to_degrees(cr.angleTo(t.lastx, t.lasty, t.x, t.y)));
- };
- Exps.prototype.AngleForID = function (ret, id)
- {
- var index = this.findTouch(id);
- if (index < 0)
- {
- ret.set_float(0);
- return;
- }
- var touch = this.touches[index];
- ret.set_float(cr.to_degrees(cr.angleTo(touch.lastx, touch.lasty, touch.x, touch.y)));
- };
- Exps.prototype.Alpha = function (ret)
- {
- ret.set_float(this.getAlpha());
- };
- Exps.prototype.Beta = function (ret)
- {
- ret.set_float(this.getBeta());
- };
- Exps.prototype.Gamma = function (ret)
- {
- ret.set_float(this.getGamma());
- };
- Exps.prototype.AccelerationXWithG = function (ret)
- {
- ret.set_float(this.acc_g_x);
- };
- Exps.prototype.AccelerationYWithG = function (ret)
- {
- ret.set_float(this.acc_g_y);
- };
- Exps.prototype.AccelerationZWithG = function (ret)
- {
- ret.set_float(this.acc_g_z);
- };
- Exps.prototype.AccelerationX = function (ret)
- {
- ret.set_float(this.acc_x);
- };
- Exps.prototype.AccelerationY = function (ret)
- {
- ret.set_float(this.acc_y);
- };
- Exps.prototype.AccelerationZ = function (ret)
- {
- ret.set_float(this.acc_z);
- };
- Exps.prototype.TouchIndex = function (ret)
- {
- ret.set_int(this.trigger_index);
- };
- Exps.prototype.TouchID = function (ret)
- {
- ret.set_float(this.trigger_id);
- };
- pluginProto.exps = new Exps();
- }());
- ;
- ;
- cr.plugins_.WebStorage = function(runtime)
- {
- this.runtime = runtime;
- };
- (function()
- {
- var pluginProto = cr.plugins_.WebStorage.prototype;
- pluginProto.Type = function(plugin)
- {
- this.plugin = plugin;
- this.runtime = plugin.runtime;
- };
- var typeProto = pluginProto.Type.prototype;
- typeProto.onCreate = function()
- {
- };
- pluginProto.Instance = function(type)
- {
- this.type = type;
- this.runtime = type.runtime;
- };
- var instanceProto = pluginProto.Instance.prototype;
- var prefix = "";
- var is_arcade = (typeof window["is_scirra_arcade"] !== "undefined");
- if (is_arcade)
- prefix = "arcade" + window["scirra_arcade_id"];
- var isSupported = false;
- try {
- localStorage.getItem("test");
- isSupported = true;
- }
- catch (e)
- {
- isSupported = false;
- }
- instanceProto.onCreate = function()
- {
- if (!isSupported)
- {
- cr.logexport("[Construct 2] Webstorage plugin: local storage is not supported on this platform.");
- }
- };
- function Cnds() {};
- Cnds.prototype.LocalStorageEnabled = function()
- {
- return isSupported;
- };
- Cnds.prototype.SessionStorageEnabled = function()
- {
- return isSupported;
- };
- Cnds.prototype.LocalStorageExists = function(key)
- {
- if (!isSupported)
- return false;
- return localStorage.getItem(prefix + key) != null;
- };
- Cnds.prototype.SessionStorageExists = function(key)
- {
- if (!isSupported)
- return false;
- return sessionStorage.getItem(prefix + key) != null;
- };
- Cnds.prototype.OnQuotaExceeded = function ()
- {
- return true;
- };
- Cnds.prototype.CompareKeyText = function (key, text_to_compare, case_sensitive)
- {
- if (!isSupported)
- return false;
- var value = localStorage.getItem(prefix + key) || "";
- if (case_sensitive)
- return value == text_to_compare;
- else
- return cr.equals_nocase(value, text_to_compare);
- };
- Cnds.prototype.CompareKeyNumber = function (key, cmp, x)
- {
- if (!isSupported)
- return false;
- var value = localStorage.getItem(prefix + key) || "";
- return cr.do_cmp(parseFloat(value), cmp, x);
- };
- pluginProto.cnds = new Cnds();
- function Acts() {};
- Acts.prototype.StoreLocal = function(key, data)
- {
- if (!isSupported)
- return;
- try {
- localStorage.setItem(prefix + key, data);
- }
- catch (e)
- {
- this.runtime.trigger(cr.plugins_.WebStorage.prototype.cnds.OnQuotaExceeded, this);
- }
- };
- Acts.prototype.StoreSession = function(key,data)
- {
- if (!isSupported)
- return;
- try {
- sessionStorage.setItem(prefix + key, data);
- }
- catch (e)
- {
- this.runtime.trigger(cr.plugins_.WebStorage.prototype.cnds.OnQuotaExceeded, this);
- }
- };
- Acts.prototype.RemoveLocal = function(key)
- {
- if (!isSupported)
- return;
- localStorage.removeItem(prefix + key);
- };
- Acts.prototype.RemoveSession = function(key)
- {
- if (!isSupported)
- return;
- sessionStorage.removeItem(prefix + key);
- };
- Acts.prototype.ClearLocal = function()
- {
- if (!isSupported)
- return;
- if (!is_arcade)
- localStorage.clear();
- };
- Acts.prototype.ClearSession = function()
- {
- if (!isSupported)
- return;
- if (!is_arcade)
- sessionStorage.clear();
- };
- Acts.prototype.JSONLoad = function (json_, mode_)
- {
- if (!isSupported)
- return;
- var d;
- try {
- d = JSON.parse(json_);
- }
- catch(e) { return; }
- if (!d["c2dictionary"]) // presumably not a c2dictionary object
- return;
- var o = d["data"];
- if (mode_ === 0 && !is_arcade) // 'set' mode: must clear webstorage first
- localStorage.clear();
- var p;
- for (p in o)
- {
- if (o.hasOwnProperty(p))
- {
- try {
- localStorage.setItem(prefix + p, o[p]);
- }
- catch (e)
- {
- this.runtime.trigger(cr.plugins_.WebStorage.prototype.cnds.OnQuotaExceeded, this);
- return;
- }
- }
- }
- };
- pluginProto.acts = new Acts();
- function Exps() {};
- Exps.prototype.LocalValue = function(ret,key)
- {
- if (!isSupported)
- {
- ret.set_string("");
- return;
- }
- ret.set_string(localStorage.getItem(prefix + key) || "");
- };
- Exps.prototype.SessionValue = function(ret,key)
- {
- if (!isSupported)
- {
- ret.set_string("");
- return;
- }
- ret.set_string(sessionStorage.getItem(prefix + key) || "");
- };
- Exps.prototype.LocalCount = function(ret)
- {
- if (!isSupported)
- {
- ret.set_int(0);
- return;
- }
- ret.set_int(is_arcade ? 0 : localStorage.length);
- };
- Exps.prototype.SessionCount = function(ret)
- {
- if (!isSupported)
- {
- ret.set_int(0);
- return;
- }
- ret.set_int(is_arcade ? 0 : sessionStorage.length);
- };
- Exps.prototype.LocalAt = function(ret,n)
- {
- if (is_arcade || !isSupported)
- ret.set_string("");
- else
- ret.set_string(localStorage.getItem(localStorage.key(n)) || "");
- };
- Exps.prototype.SessionAt = function(ret,n)
- {
- if (is_arcade || !isSupported)
- ret.set_string("");
- else
- ret.set_string(sessionStorage.getItem(sessionStorage.key(n)) || "");
- };
- Exps.prototype.LocalKeyAt = function(ret,n)
- {
- if (is_arcade || !isSupported)
- ret.set_string("");
- else
- ret.set_string(localStorage.key(n) || "");
- };
- Exps.prototype.SessionKeyAt = function(ret,n)
- {
- if (is_arcade || !isSupported)
- ret.set_string("");
- else
- ret.set_string(sessionStorage.key(n) || "");
- };
- Exps.prototype.AsJSON = function (ret)
- {
- if (!isSupported)
- {
- ret.set_string("");
- return;
- }
- var o = {}, i, len, k;
- for (i = 0, len = localStorage.length; i < len; i++)
- {
- k = localStorage.key(i);
- if (is_arcade)
- {
- if (k.substr(0, prefix.length) === prefix)
- {
- o[k.substr(prefix.length)] = localStorage.getItem(k);
- }
- }
- else
- o[k] = localStorage.getItem(k);
- }
- ret.set_string(JSON.stringify({
- "c2dictionary": true,
- "data": o
- }));
- };
- pluginProto.exps = new Exps();
- }());
- ;
- ;
- cr.behaviors.Anchor = function(runtime)
- {
- this.runtime = runtime;
- };
- (function ()
- {
- var behaviorProto = cr.behaviors.Anchor.prototype;
- behaviorProto.Type = function(behavior, objtype)
- {
- this.behavior = behavior;
- this.objtype = objtype;
- this.runtime = behavior.runtime;
- };
- var behtypeProto = behaviorProto.Type.prototype;
- behtypeProto.onCreate = function()
- {
- };
- behaviorProto.Instance = function(type, inst)
- {
- this.type = type;
- this.behavior = type.behavior;
- this.inst = inst; // associated object instance to modify
- this.runtime = type.runtime;
- };
- var behinstProto = behaviorProto.Instance.prototype;
- behinstProto.onCreate = function()
- {
- this.anch_left = this.properties[0]; // 0 = left, 1 = right, 2 = none
- this.anch_top = this.properties[1]; // 0 = top, 1 = bottom, 2 = none
- this.anch_right = this.properties[2]; // 0 = none, 1 = right
- this.anch_bottom = this.properties[3]; // 0 = none, 1 = bottom
- this.inst.update_bbox();
- this.xleft = this.inst.bbox.left;
- this.ytop = this.inst.bbox.top;
- this.xright = this.runtime.original_width - this.inst.bbox.left;
- this.ybottom = this.runtime.original_height - this.inst.bbox.top;
- this.rdiff = this.runtime.original_width - this.inst.bbox.right;
- this.bdiff = this.runtime.original_height - this.inst.bbox.bottom;
- this.enabled = (this.properties[4] !== 0);
- };
- behinstProto.saveToJSON = function ()
- {
- return {
- "xleft": this.xleft,
- "ytop": this.ytop,
- "xright": this.xright,
- "ybottom": this.ybottom,
- "rdiff": this.rdiff,
- "bdiff": this.bdiff,
- "enabled": this.enabled
- };
- };
- behinstProto.loadFromJSON = function (o)
- {
- this.xleft = o["xleft"];
- this.ytop = o["ytop"];
- this.xright = o["xright"];
- this.ybottom = o["ybottom"];
- this.rdiff = o["rdiff"];
- this.bdiff = o["bdiff"];
- this.enabled = o["enabled"];
- };
- behinstProto.tick = function ()
- {
- if (!this.enabled)
- return;
- var n;
- var layer = this.inst.layer;
- var inst = this.inst;
- var bbox = this.inst.bbox;
- if (this.anch_left === 0)
- {
- inst.update_bbox();
- n = (layer.viewLeft + this.xleft) - bbox.left;
- if (n !== 0)
- {
- inst.x += n;
- inst.set_bbox_changed();
- }
- }
- else if (this.anch_left === 1)
- {
- inst.update_bbox();
- n = (layer.viewRight - this.xright) - bbox.left;
- if (n !== 0)
- {
- inst.x += n;
- inst.set_bbox_changed();
- }
- }
- if (this.anch_top === 0)
- {
- inst.update_bbox();
- n = (layer.viewTop + this.ytop) - bbox.top;
- if (n !== 0)
- {
- inst.y += n;
- inst.set_bbox_changed();
- }
- }
- else if (this.anch_top === 1)
- {
- inst.update_bbox();
- n = (layer.viewBottom - this.ybottom) - bbox.top;
- if (n !== 0)
- {
- inst.y += n;
- inst.set_bbox_changed();
- }
- }
- if (this.anch_right === 1)
- {
- inst.update_bbox();
- n = (layer.viewRight - this.rdiff) - bbox.right;
- if (n !== 0)
- {
- inst.width += n;
- if (inst.width < 0)
- inst.width = 0;
- inst.set_bbox_changed();
- }
- }
- if (this.anch_bottom === 1)
- {
- inst.update_bbox();
- n = (layer.viewBottom - this.bdiff) - bbox.bottom;
- if (n !== 0)
- {
- inst.height += n;
- if (inst.height < 0)
- inst.height = 0;
- inst.set_bbox_changed();
- }
- }
- };
- function Cnds() {};
- behaviorProto.cnds = new Cnds();
- function Acts() {};
- Acts.prototype.SetEnabled = function (e)
- {
- if (this.enabled && e === 0)
- this.enabled = false;
- else if (!this.enabled && e !== 0)
- {
- this.inst.update_bbox();
- this.xleft = this.inst.bbox.left;
- this.ytop = this.inst.bbox.top;
- this.xright = this.runtime.original_width - this.inst.bbox.left;
- this.ybottom = this.runtime.original_height - this.inst.bbox.top;
- this.rdiff = this.runtime.original_width - this.inst.bbox.right;
- this.bdiff = this.runtime.original_height - this.inst.bbox.bottom;
- this.enabled = true;
- }
- };
- behaviorProto.acts = new Acts();
- function Exps() {};
- behaviorProto.exps = new Exps();
- }());
- ;
- ;
- cr.behaviors.Pin = function(runtime)
- {
- this.runtime = runtime;
- };
- (function ()
- {
- var behaviorProto = cr.behaviors.Pin.prototype;
- behaviorProto.Type = function(behavior, objtype)
- {
- this.behavior = behavior;
- this.objtype = objtype;
- this.runtime = behavior.runtime;
- };
- var behtypeProto = behaviorProto.Type.prototype;
- behtypeProto.onCreate = function()
- {
- };
- behaviorProto.Instance = function(type, inst)
- {
- this.type = type;
- this.behavior = type.behavior;
- this.inst = inst; // associated object instance to modify
- this.runtime = type.runtime;
- };
- var behinstProto = behaviorProto.Instance.prototype;
- behinstProto.onCreate = function()
- {
- this.pinObject = null;
- this.pinObjectUid = -1; // for loading
- this.pinAngle = 0;
- this.pinDist = 0;
- this.myStartAngle = 0;
- this.theirStartAngle = 0;
- this.lastKnownAngle = 0;
- this.mode = 0; // 0 = position & angle; 1 = position; 2 = angle; 3 = rope; 4 = bar
- var self = this;
- if (!this.recycled)
- {
- this.myDestroyCallback = (function(inst) {
- self.onInstanceDestroyed(inst);
- });
- }
- this.runtime.addDestroyCallback(this.myDestroyCallback);
- };
- behinstProto.saveToJSON = function ()
- {
- return {
- "uid": this.pinObject ? this.pinObject.uid : -1,
- "pa": this.pinAngle,
- "pd": this.pinDist,
- "msa": this.myStartAngle,
- "tsa": this.theirStartAngle,
- "lka": this.lastKnownAngle,
- "m": this.mode
- };
- };
- behinstProto.loadFromJSON = function (o)
- {
- this.pinObjectUid = o["uid"]; // wait until afterLoad to look up
- this.pinAngle = o["pa"];
- this.pinDist = o["pd"];
- this.myStartAngle = o["msa"];
- this.theirStartAngle = o["tsa"];
- this.lastKnownAngle = o["lka"];
- this.mode = o["m"];
- };
- behinstProto.afterLoad = function ()
- {
- if (this.pinObjectUid === -1)
- this.pinObject = null;
- else
- {
- this.pinObject = this.runtime.getObjectByUID(this.pinObjectUid);
- ;
- }
- this.pinObjectUid = -1;
- };
- behinstProto.onInstanceDestroyed = function (inst)
- {
- if (this.pinObject == inst)
- this.pinObject = null;
- };
- behinstProto.onDestroy = function()
- {
- this.pinObject = null;
- this.runtime.removeDestroyCallback(this.myDestroyCallback);
- };
- behinstProto.tick = function ()
- {
- };
- behinstProto.tick2 = function ()
- {
- if (!this.pinObject)
- return;
- if (this.lastKnownAngle !== this.inst.angle)
- this.myStartAngle = cr.clamp_angle(this.myStartAngle + (this.inst.angle - this.lastKnownAngle));
- var newx = this.inst.x;
- var newy = this.inst.y;
- if (this.mode === 3 || this.mode === 4) // rope mode or bar mode
- {
- var dist = cr.distanceTo(this.inst.x, this.inst.y, this.pinObject.x, this.pinObject.y);
- if ((dist > this.pinDist) || (this.mode === 4 && dist < this.pinDist))
- {
- var a = cr.angleTo(this.pinObject.x, this.pinObject.y, this.inst.x, this.inst.y);
- newx = this.pinObject.x + Math.cos(a) * this.pinDist;
- newy = this.pinObject.y + Math.sin(a) * this.pinDist;
- }
- }
- else
- {
- newx = this.pinObject.x + Math.cos(this.pinObject.angle + this.pinAngle) * this.pinDist;
- newy = this.pinObject.y + Math.sin(this.pinObject.angle + this.pinAngle) * this.pinDist;
- }
- var newangle = cr.clamp_angle(this.myStartAngle + (this.pinObject.angle - this.theirStartAngle));
- this.lastKnownAngle = newangle;
- if ((this.mode === 0 || this.mode === 1 || this.mode === 3 || this.mode === 4)
- && (this.inst.x !== newx || this.inst.y !== newy))
- {
- this.inst.x = newx;
- this.inst.y = newy;
- this.inst.set_bbox_changed();
- }
- if ((this.mode === 0 || this.mode === 2) && (this.inst.angle !== newangle))
- {
- this.inst.angle = newangle;
- this.inst.set_bbox_changed();
- }
- };
- function Cnds() {};
- Cnds.prototype.IsPinned = function ()
- {
- return !!this.pinObject;
- };
- behaviorProto.cnds = new Cnds();
- function Acts() {};
- Acts.prototype.Pin = function (obj, mode_)
- {
- if (!obj)
- return;
- var otherinst = obj.getFirstPicked(this.inst);
- if (!otherinst)
- return;
- this.pinObject = otherinst;
- this.pinAngle = cr.angleTo(otherinst.x, otherinst.y, this.inst.x, this.inst.y) - otherinst.angle;
- this.pinDist = cr.distanceTo(otherinst.x, otherinst.y, this.inst.x, this.inst.y);
- this.myStartAngle = this.inst.angle;
- this.lastKnownAngle = this.inst.angle;
- this.theirStartAngle = otherinst.angle;
- this.mode = mode_;
- };
- Acts.prototype.Unpin = function ()
- {
- this.pinObject = null;
- };
- behaviorProto.acts = new Acts();
- function Exps() {};
- Exps.prototype.PinnedUID = function (ret)
- {
- ret.set_int(this.pinObject ? this.pinObject.uid : -1);
- };
- behaviorProto.exps = new Exps();
- }());
- var easeOutBounceArray = [];
- var easeInElasticArray = [];
- var easeOutElasticArray = [];
- var easeInOutElasticArray = [];
- var easeInCircle = [];
- var easeOutCircle = [];
- var easeInOutCircle = [];
- var easeOutBack = [];
- var easeInOutBack = [];
- var litetween_precision = 10000;
- var updateLimit = 0; //0.0165;
- function easeOutBounce(t,b,c,d) {
- if ((t/=d) < (1/2.75)) {
- return c*(7.5625*t*t) + b;
- } else if (t < (2/2.75)) {
- return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
- } else if (t < (2.5/2.75)) {
- return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
- } else {
- return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
- }
- }
- function integerize(t, d)
- {
- return Math.round(t/d*litetween_precision);
- }
- function easeFunc(easing, t, b, c, d, flip)
- {
- var ret_ease = 0;
- switch (easing) {
- case 0: // linear
- ret_ease = c*t/d + b;
- break;
- case 1: // easeInQuad
- ret_ease = c*(t/=d)*t + b;
- break;
- case 2: // easeOutQuad
- ret_ease = -c *(t/=d)*(t-2) + b;
- break;
- case 3: // easeInOutQuad
- if ((t/=d/2) < 1)
- ret_ease = c/2*t*t + b
- else
- ret_ease = -c/2 * ((--t)*(t-2) - 1) + b;
- break;
- case 4: // easeInCubic
- ret_ease = c*(t/=d)*t*t + b;
- break;
- case 5: // easeOutCubic
- ret_ease = c*((t=t/d-1)*t*t + 1) + b;
- break;
- case 6: // easeInOutCubic
- if ((t/=d/2) < 1)
- ret_ease = c/2*t*t*t + b
- else
- ret_ease = c/2*((t-=2)*t*t + 2) + b;
- break;
- case 7: // easeInQuart
- ret_ease = c*(t/=d)*t*t*t + b;
- break;
- case 8: // easeOutQuart
- ret_ease = -c * ((t=t/d-1)*t*t*t - 1) + b;
- break;
- case 9: // easeInOutQuart
- if ((t/=d/2) < 1)
- ret_ease = c/2*t*t*t*t + b
- else
- ret_ease = -c/2 * ((t-=2)*t*t*t - 2) + b;
- break;
- case 10: // easeInQuint
- ret_ease = c*(t/=d)*t*t*t*t + b;
- break;
- case 11: // easeOutQuint
- ret_ease = c*((t=t/d-1)*t*t*t*t + 1) + b;
- break;
- case 12: // easeInOutQuint
- if ((t/=d/2) < 1)
- ret_ease = c/2*t*t*t*t*t + b
- else
- ret_ease = c/2*((t-=2)*t*t*t*t + 2) + b;
- break;
- case 13: // easeInCircle
- ret_ease = easeInCircle[integerize(t,d)];
- break;
- case 14: // easeOutCircle
- ret_ease = easeOutCircle[integerize(t,d)];
- break;
- case 15: // easeInOutCircle
- ret_ease = easeInOutCircle[integerize(t,d)];
- break;
- case 16: // easeInBack
- var s = 0;
- if (s==0) s = 1.70158;
- ret_ease = c*(t/=d)*t*((s+1)*t - s) + b;
- break;
- case 17: // easeOutBack
- ret_ease = easeOutBack[integerize(t,d)];
- break;
- case 18: // easeInOutBack
- ret_ease = easeInOutBack[integerize(t,d)];
- break;
- case 19: //easeInElastic
- ret_ease = easeInElasticArray[integerize(t, d)];
- break;
- case 20: //easeOutElastic
- ret_ease = easeOutElasticArray[integerize(t,d)];
- break;
- case 21: //easeInOutElastic
- ret_ease = easeInOutElasticArray[integerize(t,d)];
- break;
- case 22: //easeInBounce
- ret_ease = c - easeOutBounceArray[integerize(d-t, d)] + b;
- break;
- case 23: //easeOutBounce
- ret_ease = easeOutBounceArray[integerize(t, d)];
- break;
- case 24: //easeInOutBounce
- if (t < d/2)
- ret_ease = (c - easeOutBounceArray[integerize(d-(t*2), d)] + b) * 0.5 +b;
- else
- ret_ease = easeOutBounceArray[integerize(t*2-d, d)] * .5 + c*.5 + b;
- break;
- case 25: //easeInSmoothstep
- var mt = (t/d) / 2;
- ret_ease = (2*(mt * mt * (3 - 2*mt)));
- break;
- case 26: //easeOutSmoothstep
- var mt = ((t/d) + 1) / 2;
- ret_ease = ((2*(mt * mt * (3 - 2*mt))) - 1);
- break;
- case 27: //easeInOutSmoothstep
- var mt = (t / d);
- ret_ease = (mt * mt * (3 - 2*mt));
- break;
- };
- if (flip)
- return (c - b) - ret_ease
- else
- return ret_ease;
- };
- (function preCalculateArray() {
- var d = 1.0;
- var b = 0.0;
- var c = 1.0;
- var result = 0.0;
- var a = 0;
- var p = 0;
- var t = 0;
- var s = 0;
- for (var ti = 0; ti <= litetween_precision; ti++) {
- t = ti/litetween_precision;
- if ((t/=d) < (1/2.75)) {
- result = c*(7.5625*t*t) + b;
- } else if (t < (2/2.75)) {
- result = c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
- } else if (t < (2.5/2.75)) {
- result = c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
- } else {
- result = c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
- }
- easeOutBounceArray[ti] = easeOutBounce(ti/litetween_precision, b, c, d);
- t = ti/litetween_precision; a = 0; p = 0;
- if (t==0) result = b; if ((t/=d)==1) result = b+c;
- if (p==0) p=d*.3; if (a==0 || a < Math.abs(c)) { a=c; var s=p/4; }
- else var s = p/(2*Math.PI) * Math.asin (c/a);
- result = -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
- easeInElasticArray[ti] = result;
- t = ti/litetween_precision; a = 0; p = 0;
- if (t==0) result= b; if ((t/=d)==1) result= b+c; if (p == 0) p=d*.3;
- if (a==0 || a < Math.abs(c)) { a=c; var s=p/4; }
- else var s = p/(2*Math.PI) * Math.asin (c/a);
- result= (a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b);
- easeOutElasticArray[ti] = result;
- t = ti/litetween_precision; a = 0; p = 0;
- if (t==0) result = b;
- if ((t/=d/2)==2) result = b+c;
- if (p==0) p=d*(.3*1.5);
- if (a==0 || a < Math.abs(c)) { a=c; var s=p/4; }
- else var s = p/(2*Math.PI) * Math.asin (c/a);
- if (t < 1)
- result = -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b
- else
- result = a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
- easeInOutElasticArray[ti] = result;
- t = ti/litetween_precision; easeInCircle[ti] = -(Math.sqrt(1-t*t) - 1);
- t = ti/litetween_precision; easeOutCircle[ti] = Math.sqrt(1 - ((t-1)*(t-1)));
- t = ti/litetween_precision;
- if ((t/=d/2) < 1) result = -c/2 * (Math.sqrt(1 - t*t) - 1) + b
- else result = c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
- easeInOutCircle[ti] = result;
- t = ti/litetween_precision; s = 0;
- if (s==0) s = 1.70158;
- result = c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
- easeOutBack[ti] = result;
- t = ti/litetween_precision; s = 0; if (s==0) s = 1.70158;
- if ((t/=d/2) < 1)
- result = c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b
- else
- result = c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
- easeInOutBack[ti] = result;
- }
- }())
- var TweenObject = function()
- {
- var constructor = function (tname, tweened, easefunc, initial, target, duration, enforce)
- {
- this.name = tname;
- this.value = 0;
- this.setInitial(initial);
- this.setTarget(target);
- this.easefunc = easefunc;
- this.tweened = tweened;
- this.duration = duration;
- this.progress = 0;
- this.state = 0;
- this.onStart = false;
- this.onEnd = false;
- this.onReverseStart = false;
- this.onReverseEnd = false;
- this.lastKnownValue = 0;
- this.lastKnownValue2 = 0;
- this.enforce = enforce;
- this.pingpong = 1.0;
- this.flipEase = false;
- }
- return constructor;
- }();
- (function () {
- TweenObject.prototype = {
- };
- TweenObject.prototype.flipTarget = function ()
- {
- var x1 = this.initialparam1;
- var x2 = this.initialparam2;
- this.initialparam1 = this.targetparam1;
- this.initialparam2 = this.targetparam2;
- this.targetparam1 = x1;
- this.targetparam2 = x2;
- this.lastKnownValue = 0;
- this.lastKnownValue2 = 0;
- }
- TweenObject.prototype.setInitial = function (initial)
- {
- this.initialparam1 = parseFloat(initial.split(",")[0]);
- this.initialparam2 = parseFloat(initial.split(",")[1]);
- this.lastKnownValue = 0;
- this.lastKnownValue2 = 0;
- }
- TweenObject.prototype.setTarget = function (target)
- {
- this.targetparam1 = parseFloat(target.split(",")[0]);
- this.targetparam2 = parseFloat(target.split(",")[1]);
- if (isNaN(this.targetparam2)) this.targetparam2 = this.targetparam1;
- }
- TweenObject.prototype.OnTick = function(dt)
- {
- if (this.state === 0) return -1.0;
- if (this.state === 1)
- this.progress += dt;
- if (this.state === 2)
- this.progress -= dt;
- if (this.state === 3) {
- this.state = 0;
- }
- if ((this.state === 4) || (this.state === 6)) {
- this.progress += dt * this.pingpong;
- }
- if (this.state === 5) {
- this.progress += dt * this.pingpong;
- }
- if (this.progress < 0) {
- this.progress = 0;
- if (this.state === 4) {
- this.pingpong = 1;
- } else if (this.state === 6) {
- this.pingpong = 1;
- this.flipEase = false;
- } else {
- this.state = 0;
- }
- this.onReverseEnd = true;
- return 0.0;
- } else if (this.progress > this.duration) {
- this.progress = this.duration;
- if (this.state === 4) {
- this.pingpong = -1;
- } else if (this.state === 6) {
- this.pingpong = -1;
- this.flipEase = true;
- } else if (this.state === 5) {
- this.progress = 0.0;
- } else {
- this.state = 0;
- }
- this.onEnd = true;
- return 1.0;
- } else {
- if (this.flipEase) {
- var factor = easeFunc(this.easefunc, this.duration - this.progress, 0, 1, this.duration, this.flipEase);
- } else {
- var factor = easeFunc(this.easefunc, this.progress, 0, 1, this.duration, this.flipEase);
- }
- return factor;
- }
- };
- }());
- ;
- ;
- function trim (str) {
- return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
- }
- cr.behaviors.lunarray_LiteTween = function(runtime)
- {
- this.runtime = runtime;
- };
- (function ()
- {
- var behaviorProto = cr.behaviors.lunarray_LiteTween.prototype;
- behaviorProto.Type = function(behavior, objtype)
- {
- this.behavior = behavior;
- this.objtype = objtype;
- this.runtime = behavior.runtime;
- };
- var behtypeProto = behaviorProto.Type.prototype;
- behtypeProto.onCreate = function()
- {
- };
- behaviorProto.Instance = function(type, inst)
- {
- this.type = type;
- this.behavior = type.behavior;
- this.inst = inst; // associated object instance to modify
- this.runtime = type.runtime;
- this.i = 0; // progress
- };
- var behinstProto = behaviorProto.Instance.prototype;
- behinstProto.onCreate = function()
- {
- this.playmode = this.properties[0];
- this.active = (this.playmode == 1) || (this.playmode == 2) || (this.playmode == 3) || (this.playmode == 4);
- this.tweened = this.properties[1]; // 0=Position|1=Size|2=Width|3=Height|4=Angle|5=Opacity|6=Value only|7=Horizontal|8=Vertical|9=Scale
- this.easing = this.properties[2];
- this.target = this.properties[3];
- this.targetmode = this.properties[4];
- this.useCurrent = false;
- if (this.targetmode === 1) this.target = "relative("+this.target+")";
- this.duration = this.properties[5];
- this.enforce = (this.properties[6] === 1);
- this.value = 0;
- this.tween_list = {};
- this.addToTweenList("default", this.tweened, this.easing, "current", this.target, this.duration, this.enforce);
- if (this.properties[0] === 1) this.startTween(0)
- if (this.properties[0] === 2) this.startTween(2)
- if (this.properties[0] === 3) this.startTween(3)
- if (this.properties[0] === 4) this.startTween(4)
- };
- behinstProto.parseCurrent = function(tweened, parseText)
- {
- if (parseText === undefined) parseText = "current";
- var parsed = trim(parseText);
- parseText = trim(parseText);
- var value = this.value;
- if (parseText === "current") {
- switch (tweened) {
- case 0: parsed = this.inst.x + "," + this.inst.y; break;
- case 1: parsed = this.inst.width + "," + this.inst.height; break;
- case 2: parsed = this.inst.width + "," + this.inst.height; break;
- case 3: parsed = this.inst.width + "," + this.inst.height; break;
- case 4: parsed = cr.to_degrees(this.inst.angle) + "," + cr.to_degrees(this.inst.angle); break;
- case 5: parsed = (this.inst.opacity*100) + "," + (this.inst.opacity*100); break;
- case 6: parsed = value + "," + value; break;
- case 7: parsed = this.inst.x + "," + this.inst.y; break;
- case 8: parsed = this.inst.x + "," + this.inst.y; break;
- case 9:
- if (this.inst.curFrame !== undefined)
- parsed = (this.inst.width/this.inst.curFrame.width) + "," +(this.inst.height/this.inst.curFrame.height)
- else
- parsed = "1,1";
- break;
- default: break;
- }
- }
- if (parseText.substring(0,8) === "relative") {
- var param1 = parseText.match(/\((.*?)\)/);
- if (param1) {
- var relativex = parseFloat(param1[1].split(",")[0]);
- var relativey = parseFloat(param1[1].split(",")[1]);
- }
- if (isNaN(relativex)) relativex = 0;
- if (isNaN(relativey)) relativey = 0;
- switch (tweened) {
- case 0: parsed = (this.inst.x+relativex) + "," + (this.inst.y+relativey); break;
- case 1: parsed = (this.inst.width+relativex) + "," + (this.inst.height+relativey); break;
- case 2: parsed = (this.inst.width+relativex) + "," + (this.inst.height+relativey); break;
- case 3: parsed = (this.inst.width+relativex) + "," + (this.inst.height+relativey); break;
- case 4: parsed = (cr.to_degrees(this.inst.angle)+relativex) + "," + (cr.to_degrees(this.inst.angle)+relativey); break;
- case 5: parsed = (this.inst.opacity*100+relativex) + "," + (this.inst.opacity*100+relativey); break;
- case 6: parsed = value+relativex + "," + value+relativex; break;
- case 7: parsed = (this.inst.x+relativex) + "," + (this.inst.y); break;
- case 8: parsed = (this.inst.x) + "," + (this.inst.y+relativex); break;
- case 9: parsed = (relativex) + "," + (relativey); break;
- default: break;
- }
- }
- return parsed;
- };
- behinstProto.addToTweenList = function(tname, tweened, easing, init, targ, duration, enforce)
- {
- init = this.parseCurrent(tweened, init);
- targ = this.parseCurrent(tweened, targ);
- if (this.tween_list[tname] !== undefined) {
- delete this.tween_list[tname]
- }
- this.tween_list[tname] = new TweenObject(tname, tweened, easing, init, targ, duration, enforce);
- this.tween_list[tname].dt = 0;
- };
- behinstProto.saveToJSON = function ()
- {
- };
- behinstProto.loadFromJSON = function (o)
- {
- };
- behinstProto.setProgressTo = function (mark)
- {
- if (mark > 1.0) mark = 1.0;
- if (mark < 0.0) mark = 0.0;
- for (var i in this.tween_list) {
- var inst = this.tween_list[i];
- inst.lastKnownValue = 0;
- inst.lastKnownValue2 = 0;
- inst.state = 3;
- inst.progress = mark * inst.duration;
- var factor = inst.OnTick(0);
- this.updateTween(inst, factor);
- }
- }
- behinstProto.startTween = function (startMode)
- {
- for (var i in this.tween_list) {
- var inst = this.tween_list[i];
- if (this.useCurrent) {
- var init = this.parseCurrent(inst.tweened, "current");
- var target = this.parseCurrent(inst.tweened, this.target);
- inst.setInitial(init);
- inst.setTarget(target);
- }
- if (startMode === 0) {
- inst.progress = 0.000001;
- inst.lastKnownValue = 0;
- inst.lastKnownValue2 = 0;
- inst.onStart = true;
- inst.state = 1;
- }
- if (startMode === 1) {
- inst.state = 1;
- }
- if ((startMode === 2) || (startMode === 4)) {
- inst.progress = 0.000001;
- inst.lastKnownValue = 0;
- inst.lastKnownValue2 = 0;
- inst.onStart = true;
- if (startMode == 2) inst.state = 4; //state ping pong
- if (startMode == 4) inst.state = 6; //state flip flop
- }
- if (startMode === 3) {
- inst.progress = 0.000001;
- inst.lastKnownValue = 0;
- inst.lastKnownValue2 = 0;
- inst.onStart = true;
- inst.state = 5;
- }
- }
- }
- behinstProto.stopTween = function (stopMode)
- {
- for (var i in this.tween_list) {
- var inst = this.tween_list[i];
- if (stopMode === 1) inst.progress = 0.0;
- if (stopMode === 2) inst.progress = inst.duration;
- inst.state = 3;
- var factor = inst.OnTick(0);
- this.updateTween(inst, factor);
- }
- }
- behinstProto.reverseTween = function(reverseMode)
- {
- for (var i in this.tween_list) {
- var inst = this.tween_list[i];
- if (reverseMode === 1) {
- inst.progress = inst.duration;
- inst.lastKnownValue = 0;
- inst.lastKnownValue2 = 0;
- inst.onReverseStart = true;
- }
- inst.state = 2;
- }
- }
- behinstProto.updateTween = function (inst, factor)
- {
- if (inst.tweened === 0) {
- if (inst.enforce) {
- this.inst.x = inst.initialparam1 + (inst.targetparam1 - inst.initialparam1) * factor;
- this.inst.y = inst.initialparam2 + (inst.targetparam2 - inst.initialparam2) * factor;
- } else {
- this.inst.x += ((inst.targetparam1 - inst.initialparam1) * factor) - inst.lastKnownValue;
- this.inst.y += ((inst.targetparam2 - inst.initialparam2) * factor) - inst.lastKnownValue2;
- inst.lastKnownValue = ((inst.targetparam1 - inst.initialparam1) * factor);
- inst.lastKnownValue2 = ((inst.targetparam2 - inst.initialparam2) * factor);
- }
- } else if (inst.tweened === 1) {
- if (inst.enforce) {
- this.inst.width = inst.initialparam1 + (inst.targetparam1 - inst.initialparam1) * factor;
- this.inst.height = inst.initialparam2 + (inst.targetparam2 - inst.initialparam2) * factor;
- } else {
- this.inst.width += ((inst.targetparam1 - inst.initialparam1) * factor) - inst.lastKnownValue;
- this.inst.height += ((inst.targetparam2 - inst.initialparam2) * factor) - inst.lastKnownValue2;
- inst.lastKnownValue = ((inst.targetparam1 - inst.initialparam1) * factor);
- inst.lastKnownValue2 = ((inst.targetparam2 - inst.initialparam2) * factor);
- }
- } else if (inst.tweened === 2) {
- if (inst.enforce) {
- this.inst.width = inst.initialparam1 + ((inst.targetparam1 - inst.initialparam1) * factor);
- } else {
- this.inst.width += ((inst.targetparam1 - inst.initialparam1) * factor) - inst.lastKnownValue;
- inst.lastKnownValue = ((inst.targetparam1 - inst.initialparam1) * factor);
- }
- } else if (inst.tweened === 3) {
- if (inst.enforce) {
- this.inst.height = inst.initialparam2 + ((inst.targetparam2 - inst.initialparam2) * factor);
- } else {
- this.inst.height += ((inst.targetparam2 - inst.initialparam2) * factor) - inst.lastKnownValue2;
- inst.lastKnownValue2 = ((inst.targetparam2 - inst.initialparam2) * factor);
- }
- } else if (inst.tweened === 4) {
- if (inst.enforce) {
- var tangle = inst.initialparam1 + (inst.targetparam1 - inst.initialparam1) * factor;
- this.inst.angle = cr.clamp_angle(cr.to_radians(tangle));
- } else {
- var tangle = ((inst.targetparam1 - inst.initialparam1) * factor) - inst.lastKnownValue;
- this.inst.angle = cr.clamp_angle(this.inst.angle + cr.to_radians(tangle));
- inst.lastKnownValue = (inst.targetparam1 - inst.initialparam1) * factor;
- }
- } else if (inst.tweened === 5) {
- if (inst.enforce) {
- this.inst.opacity = (inst.initialparam1 + (inst.targetparam1 - inst.initialparam1) * factor) / 100;
- } else {
- this.inst.opacity += (((inst.targetparam1 - inst.initialparam1) * factor) - inst.lastKnownValue) / 100;
- inst.lastKnownValue = ((inst.targetparam1 - inst.initialparam1) * factor);
- }
- } else if (inst.tweened === 6) {
- if (inst.enforce) {
- this.value = (inst.initialparam1 + (inst.targetparam1 - inst.initialparam1) * factor);
- } else {
- this.value += (((inst.targetparam1 - inst.initialparam1) * factor) - inst.lastKnownValue);
- inst.lastKnownValue = ((inst.targetparam1 - inst.initialparam1) * factor);
- }
- } else if (inst.tweened === 7) {
- if (inst.enforce) {
- this.inst.x = inst.initialparam1 + (inst.targetparam1 - inst.initialparam1) * factor;
- } else {
- this.inst.x += ((inst.targetparam1 - inst.initialparam1) * factor) - inst.lastKnownValue;
- inst.lastKnownValue = ((inst.targetparam1 - inst.initialparam1) * factor);
- }
- } else if (inst.tweened === 8) {
- if (inst.enforce) {
- this.inst.y = inst.initialparam2 + (inst.targetparam2 - inst.initialparam2) * factor;
- } else {
- this.inst.y += ((inst.targetparam2 - inst.initialparam2) * factor) - inst.lastKnownValue2;
- inst.lastKnownValue2 = ((inst.targetparam2 - inst.initialparam2) * factor);
- }
- } else if (inst.tweened === 9) {
- var scalex = inst.initialparam1 + (inst.targetparam1 - inst.initialparam1) * factor;
- var scaley = inst.initialparam2 + (inst.targetparam2 - inst.initialparam2) * factor;
- if (this.inst.width < 0) scalex = inst.initialparam1 + (inst.targetparam1 + inst.initialparam1) * -factor;
- if (this.inst.height < 0) scaley = inst.initialparam2 + (inst.targetparam2 + inst.initialparam2) * -factor;
- if (inst.enforce) {
- this.inst.width = this.inst.curFrame.width * scalex;
- this.inst.height = this.inst.curFrame.height * scaley;
- } else {
- if (this.inst.width < 0) {
- this.inst.width = scalex * (this.inst.width / (-1+inst.lastKnownValue));
- inst.lastKnownValue = scalex + 1
- } else {
- this.inst.width = scalex * (this.inst.width / (1+inst.lastKnownValue));
- inst.lastKnownValue = scalex - 1;
- }
- if (this.inst.height < 0) {
- this.inst.height = scaley * (this.inst.height / (-1+inst.lastKnownValue2));
- inst.lastKnownValue2 = scaley + 1
- } else {
- this.inst.height = scaley * (this.inst.height / (1+inst.lastKnownValue2));
- inst.lastKnownValue2 = scaley - 1;
- }
- }
- }
- this.inst.set_bbox_changed();
- }
- behinstProto.tick = function ()
- {
- var dt = this.runtime.getDt(this.inst);
- var inst = this.tween_list["default"];
- if (inst.state !== 0) {
- if (inst.onStart) {
- this.runtime.trigger(cr.behaviors.lunarray_LiteTween.prototype.cnds.OnStart, this.inst);
- inst.onStart = false;
- }
- if (inst.onReverseStart) {
- this.runtime.trigger(cr.behaviors.lunarray_LiteTween.prototype.cnds.OnReverseStart, this.inst);
- inst.onReverseStart = false;
- }
- this.active = (inst.state == 1) || (inst.state == 2) || (inst.state == 4) || (inst.state == 5) || (inst.state == 6);
- var factor = inst.OnTick(dt);
- this.updateTween(inst, factor);
- if (inst.onEnd) {
- this.runtime.trigger(cr.behaviors.lunarray_LiteTween.prototype.cnds.OnEnd, this.inst);
- inst.onEnd = false;
- }
- if (inst.onReverseEnd) {
- this.runtime.trigger(cr.behaviors.lunarray_LiteTween.prototype.cnds.OnReverseEnd, this.inst);
- inst.onReverseEnd = false;
- }
- }
- };
- behaviorProto.cnds = {};
- var cnds = behaviorProto.cnds;
- cnds.IsActive = function ()
- {
- return (this.tween_list["default"].state !== 0);
- };
- cnds.CompareProgress = function (cmp, v)
- {
- var inst = this.tween_list["default"];
- return cr.do_cmp((inst.progress / inst.duration), cmp, v);
- };
- cnds.OnStart = function ()
- {
- if (this.tween_list["default"] === undefined)
- return false;
- return this.tween_list["default"].onStart;
- };
- cnds.OnReverseStart = function ()
- {
- if (this.tween_list["default"] === undefined)
- return false;
- return this.tween_list["default"].onReverseStart;
- };
- cnds.OnEnd = function ()
- {
- if (this.tween_list["default"] === undefined)
- return false;
- return this.tween_list["default"].onEnd;
- };
- cnds.OnReverseEnd = function ()
- {
- if (this.tween_list["default"] === undefined)
- return false;
- return this.tween_list["default"].onReverseEnd;
- };
- behaviorProto.acts = {};
- var acts = behaviorProto.acts;
- acts.Start = function (startmode, current)
- {
- this.useCurrent = (current == 1);
- this.startTween(startmode);
- };
- acts.Stop = function (stopmode)
- {
- this.stopTween(stopmode);
- };
- acts.Reverse = function (revMode)
- {
- this.reverseTween(revMode);
- };
- acts.ProgressTo = function (progress)
- {
- this.setProgressTo(progress);
- };
- acts.SetDuration = function (x)
- {
- if (isNaN(x)) return;
- if (x < 0) return;
- if (this.tween_list["default"] === undefined) return;
- this.tween_list["default"].duration = x;
- };
- acts.SetEnforce = function (x)
- {
- if (this.tween_list["default"] === undefined) return;
- this.tween_list["default"].enforce = (x===1);
- };
- acts.SetInitial = function (x)
- {
- if (this.tween_list["default"] === undefined) return;
- var init = this.parseCurrent(this.tween_list["default"].tweened, x);
- this.tween_list["default"].setInitial(init);
- };
- acts.SetTarget = function (targettype, absrel, x)
- {
- if (this.tween_list["default"] === undefined) return;
- if (isNaN(x)) return;
- var inst = this.tween_list["default"];
- var parsed = x + "";
- this.targetmode = absrel;
- var x1 = "";
- var x2 = "";
- if (absrel === 1) {
- this.target = "relative(" + parsed + ")";
- switch (targettype) {
- case 0: x1 = (this.inst.x + x); x2 = inst.targetparam2; break;
- case 1: x1 = inst.targetparam1; x2 = (this.inst.y + x); break;
- case 2: x1 = "" + cr.to_degrees(this.inst.angle + cr.to_radians(x)); x2 = x1; break; //angle
- case 3: x1 = "" + (this.inst.opacity*100) + x; x2 = x1; break; //opacity
- case 4: x1 = (this.inst.width + x); x2 = inst.targetparam2; break; //width
- case 5: x1 = inst.targetparam1; x2 = (this.inst.height + x); break; //height
- case 6: x1 = x; x2 = x; break; //value
- default: break;
- }
- parsed = x1 + "," + x2;
- } else {
- switch (targettype) {
- case 0: x1 = x; x2 = inst.targetparam2; break;
- case 1: x1 = inst.targetparam1; x2 = x; break;
- case 2: x1 = x; x2 = x; break; //angle
- case 3: x1 = x; x2 = x; break; //opacity
- case 4: x1 = x; x2 = inst.targetparam2; break; //width
- case 5: x1 = inst.targetparam1; x2 = x; break; //height
- case 6: x1 = x; x2 = x; break; //value
- default: break;
- }
- parsed = x1 + "," + x2;
- this.target = parsed;
- }
- var init = this.parseCurrent(this.tween_list["default"].tweened, "current");
- var targ = this.parseCurrent(this.tween_list["default"].tweened, parsed);
- inst.setInitial(init);
- inst.setTarget(targ);
- };
- acts.SetTweenedProperty = function (x)
- {
- if (this.tween_list["default"] === undefined) return;
- this.tween_list["default"].tweened = x;
- };
- acts.SetEasing = function (x)
- {
- if (this.tween_list["default"] === undefined) return;
- this.tween_list["default"].easefunc = x;
- };
- acts.SetValue = function (x)
- {
- var inst = this.tween_list["default"];
- this.value = x;
- if (inst.tweened === 6)
- inst.setInitial( this.parseCurrent(inst.tweened, "current") );
- };
- acts.SetParameter = function (tweened, easefunction, target, duration, enforce)
- {
- if (this.tween_list["default"] === undefined) {
- this.addToTweenList("default", tweened, easefunction, initial, target, duration, enforce, 0);
- } else {
- var inst = this.tween_list["default"];
- inst.tweened = tweened;
- inst.easefunc = easefunction;
- inst.setInitial( this.parseCurrent(tweened, "current") );
- inst.setTarget( this.parseCurrent(tweened, target) );
- inst.duration = duration;
- inst.enforce = (enforce === 1);
- }
- };
- behaviorProto.exps = {};
- var exps = behaviorProto.exps;
- exps.Progress = function (ret)
- {
- var progress = this.tween_list["default"].progress/this.tween_list["default"].duration;
- ret.set_float(progress);
- };
- exps.Duration = function (ret)
- {
- ret.set_float(this.tween_list["default"].duration);
- };
- exps.Target = function (ret)
- {
- var inst = this.tween_list["default"];
- var parsed = "N/A";
- switch (inst.tweened) {
- case 0: parsed = inst.targetparam1; break;
- case 1: parsed = inst.targetparam2; break;
- case 2: parsed = inst.targetparam1; break;
- case 3: parsed = inst.targetparam1; break;
- case 4: parsed = inst.targetparam1; break;
- case 5: parsed = inst.targetparam2; break;
- case 6: parsed = inst.targetparam1; break;
- default: break;
- }
- ret.set_float(parsed);
- };
- exps.Value = function (ret)
- {
- var tval = this.value;
- ret.set_float(tval);
- };
- }());
- cr.getObjectRefTable = function () { return [
- cr.plugins_.Arr,
- cr.plugins_.Browser,
- cr.plugins_.Audio,
- cr.plugins_.Function,
- cr.plugins_.Keyboard,
- cr.plugins_.Mouse,
- cr.plugins_.Rex_ZSorter,
- cr.plugins_.Sprite,
- cr.plugins_.Spritefont2,
- cr.plugins_.Text,
- cr.plugins_.TiledBg,
- cr.plugins_.Touch,
- cr.plugins_.WebStorage,
- cr.behaviors.Anchor,
- cr.behaviors.lunarray_LiteTween,
- cr.behaviors.Pin,
- cr.system_object.prototype.cnds.IsGroupActive,
- cr.plugins_.Touch.prototype.cnds.OnTouchEnd,
- cr.plugins_.Sprite.prototype.acts.SetAnimFrame,
- cr.system_object.prototype.cnds.ForEach,
- cr.plugins_.Touch.prototype.cnds.IsTouchingObject,
- cr.plugins_.Sprite.prototype.cnds.CompareInstanceVar,
- cr.plugins_.Sprite.prototype.acts.SetInstanceVar,
- cr.system_object.prototype.cnds.Else,
- cr.plugins_.Function.prototype.acts.CallFunction,
- cr.plugins_.Audio.prototype.acts.Play,
- cr.plugins_.Touch.prototype.cnds.OnTouchObject,
- cr.plugins_.Sprite.prototype.cnds.IsVisible,
- cr.system_object.prototype.cnds.OnLayoutStart,
- cr.plugins_.Sprite.prototype.acts.StopAnim,
- cr.plugins_.Function.prototype.cnds.OnFunction,
- cr.system_object.prototype.cnds.EveryTick,
- cr.system_object.prototype.acts.SetVar,
- cr.plugins_.Function.prototype.exps.Param,
- cr.system_object.prototype.cnds.Compare,
- cr.plugins_.Function.prototype.acts.SetReturnValue,
- cr.plugins_.Sprite.prototype.acts.SetVisible,
- cr.system_object.prototype.exps.time,
- cr.system_object.prototype.exps.timescale,
- cr.plugins_.Audio.prototype.acts.SetSilent,
- cr.plugins_.Audio.prototype.acts.StopAll,
- cr.plugins_.Browser.prototype.exps.ExecJS,
- cr.system_object.prototype.cnds.TriggerOnce,
- cr.system_object.prototype.acts.SetTimescale,
- cr.plugins_.WebStorage.prototype.cnds.LocalStorageExists,
- cr.system_object.prototype.exps["int"],
- cr.plugins_.WebStorage.prototype.exps.LocalValue,
- cr.plugins_.WebStorage.prototype.acts.StoreLocal,
- cr.system_object.prototype.cnds.For,
- cr.system_object.prototype.exps.len,
- cr.plugins_.Arr.prototype.acts.SetX,
- cr.system_object.prototype.exps.loopindex,
- cr.system_object.prototype.exps.right,
- cr.system_object.prototype.exps.left,
- cr.plugins_.Arr.prototype.exps.Width,
- cr.plugins_.Arr.prototype.exps.At,
- cr.plugins_.Sprite.prototype.acts.Destroy,
- cr.plugins_.TiledBg.prototype.acts.Destroy,
- cr.system_object.prototype.acts.CreateObject,
- cr.plugins_.TiledBg.prototype.acts.SetWidth,
- cr.plugins_.TiledBg.prototype.acts.SetHeight,
- cr.system_object.prototype.exps.viewportleft,
- cr.system_object.prototype.exps.viewportright,
- cr.system_object.prototype.exps.viewportbottom,
- cr.system_object.prototype.exps.viewporttop,
- cr.system_object.prototype.exps.scrollx,
- cr.system_object.prototype.cnds.PickAll,
- cr.behaviors.lunarray_LiteTween.prototype.cnds.IsActive,
- cr.behaviors.lunarray_LiteTween.prototype.acts.Stop,
- cr.plugins_.Sprite.prototype.exps.X,
- cr.plugins_.Sprite.prototype.exps.Y,
- cr.plugins_.Sprite.prototype.acts.SetX,
- cr.plugins_.Sprite.prototype.exps.LayerName,
- cr.plugins_.Sprite.prototype.acts.SetY,
- cr.plugins_.Sprite.prototype.acts.SetPos,
- cr.behaviors.lunarray_LiteTween.prototype.acts.SetParameter,
- cr.system_object.prototype.exps.str,
- cr.plugins_.Sprite.prototype.exps.UID,
- cr.system_object.prototype.cnds.PickByComparison,
- cr.plugins_.Sprite.prototype.exps.LayerNumber,
- cr.system_object.prototype.cnds.LayerVisible,
- cr.plugins_.Sprite.prototype.cnds.PickByUID,
- cr.behaviors.lunarray_LiteTween.prototype.acts.Start,
- cr.behaviors.lunarray_LiteTween.prototype.cnds.OnEnd,
- cr.plugins_.Sprite.prototype.acts.SetOpacity,
- cr.system_object.prototype.cnds.OnLayoutEnd,
- cr.system_object.prototype.acts.SetGroupActive,
- cr.behaviors.Pin.prototype.acts.Pin,
- cr.plugins_.Spritefont2.prototype.acts.SetText,
- cr.system_object.prototype.exps.floor,
- cr.system_object.prototype.exps.random,
- cr.plugins_.Sprite.prototype.exps.ImagePointX,
- cr.plugins_.Sprite.prototype.exps.ImagePointY,
- cr.system_object.prototype.exps.distance,
- cr.plugins_.Spritefont2.prototype.acts.Destroy,
- cr.system_object.prototype.acts.GoToLayoutByName,
- cr.system_object.prototype.acts.GoToLayout,
- cr.system_object.prototype.exps.loadingprogress,
- cr.system_object.prototype.exps.round,
- cr.plugins_.Sprite.prototype.acts.SetScale,
- cr.system_object.prototype.exps.min,
- cr.plugins_.Spritefont2.prototype.exps.Y,
- cr.plugins_.Spritefont2.prototype.acts.SetX,
- cr.plugins_.Spritefont2.prototype.exps.Width,
- cr.plugins_.Spritefont2.prototype.acts.SetY,
- cr.system_object.prototype.cnds.IsMobile,
- cr.plugins_.Sprite.prototype.acts.SetAnim,
- cr.plugins_.Touch.prototype.cnds.OnTouchStart,
- cr.system_object.prototype.exps.dt,
- cr.plugins_.Sprite.prototype.cnds.PickTopBottom,
- cr.plugins_.Sprite.prototype.cnds.IsMirrored,
- cr.plugins_.Sprite.prototype.exps.AnimationFrame,
- cr.plugins_.Sprite.prototype.acts.SetMirrored,
- cr.plugins_.Rex_ZSorter.prototype.acts.SortObjsLayerByY,
- cr.system_object.prototype.exps.abs,
- cr.system_object.prototype.exps.clamp,
- cr.plugins_.Sprite.prototype.acts.SetCollisions,
- cr.plugins_.Sprite.prototype.cnds.OnCreated,
- cr.plugins_.Sprite.prototype.exps.AnimationName,
- cr.plugins_.Sprite.prototype.acts.SetSize,
- cr.behaviors.Anchor.prototype.acts.SetEnabled,
- cr.plugins_.Keyboard.prototype.cnds.IsKeyDown,
- cr.plugins_.Sprite.prototype.exps.Count,
- cr.system_object.prototype.exps.max,
- cr.plugins_.Sprite.prototype.exps.AnimationFrameCount,
- cr.plugins_.Sprite.prototype.cnds.OnCollision,
- cr.plugins_.Sprite.prototype.cnds.OnAnyAnimFinished,
- cr.plugins_.Sprite.prototype.exps.Width,
- cr.plugins_.Sprite.prototype.acts.StartAnim,
- cr.plugins_.Keyboard.prototype.cnds.OnKey,
- cr.plugins_.Sprite.prototype.cnds.OnAnimFinished,
- cr.plugins_.Sprite.prototype.acts.SetAnimSpeed,
- cr.plugins_.Sprite.prototype.acts.SetAngle,
- cr.plugins_.Sprite.prototype.exps.Angle,
- cr.plugins_.Sprite.prototype.cnds.OnDestroyed,
- cr.system_object.prototype.cnds.PickByEvaluate,
- cr.behaviors.Pin.prototype.exps.PinnedUID,
- cr.plugins_.Sprite.prototype.cnds.PickDistance,
- cr.system_object.prototype.cnds.While
- ];};
|